en50221.c 76.8 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * en50221.c : implementation of the transport, session and applications
 * layers of EN 50 221
 *****************************************************************************
5
 * Copyright (C) 2004-2005, 2010, 2015 VideoLAN
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
 * Based on code from libdvbci Copyright (C) 2000 Klaus Schmidinger
 *
 * 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
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23
 *****************************************************************************/
24 25 26
#include "config.h"

#ifdef HAVE_DVB_SUPPORT
27 28 29

#include <stdlib.h>
#include <stdint.h>
30
#include <stdbool.h>
31
#include <stddef.h>
32 33 34
#include <stdio.h>
#include <unistd.h>
#include <string.h>
35
#include <inttypes.h>
36 37 38 39 40 41 42 43 44 45
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <errno.h>
#include <time.h>
46
#include <ev.h>
47 48 49 50 51 52 53

/* DVB Card Drivers */
#include <linux/dvb/version.h>
#include <linux/dvb/dmx.h>
#include <linux/dvb/frontend.h>
#include <linux/dvb/ca.h>

54 55 56 57
#include <bitstream/mpeg/psi.h>
#include <bitstream/dvb/ci.h>
#include <bitstream/dvb/si.h>

58 59 60 61 62 63 64 65 66 67 68 69 70
#include "dvblast.h"
#include "en50221.h"
#include "comm.h"

#define TAB_APPEND( count, tab, p )             \
    if( (count) > 0 )                           \
    {                                           \
        (tab) = realloc( tab, sizeof( void ** ) * ( (count) + 1 ) ); \
    }                                           \
    else                                        \
    {                                           \
        (tab) = malloc( sizeof( void ** ) );    \
    }                                           \
71
    (tab)[count] = (p);                         \
72 73 74 75 76 77
    (count)++

/*****************************************************************************
 * Local declarations
 *****************************************************************************/
#undef DEBUG_TPDU
78 79
#define CAM_INIT_TIMEOUT 15000000 /* 15 s */
#undef HLCI_WAIT_CAM_READY
80
#define CAPMT_WAIT 100 /* ms */
81
#define CA_POLL_PERIOD 100000 /* 100 ms */
82

83 84 85 86 87 88 89
typedef struct en50221_msg_t
{
    uint8_t *p_data;
    int i_size;
    struct en50221_msg_t *p_next;
} en50221_msg_t;

90 91 92 93 94 95 96 97 98 99
typedef struct en50221_session_t
{
    int i_slot;
    int i_resource_id;
    void (* pf_handle)( access_t *, int, uint8_t *, int );
    void (* pf_close)( access_t *, int );
    void (* pf_manage)( access_t *, int );
    void *p_sys;
} en50221_session_t;

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
typedef struct ci_slot_t
{
    bool b_active;
    bool b_expect_answer;
    bool b_has_data;
    bool b_mmi_expected;
    bool b_mmi_undisplayed;

    /* TPDU reception */
    en50221_msg_t *p_recv;

    /* TPDU emission */
    en50221_msg_t *p_send;
    en50221_msg_t **pp_send_last;
    uint8_t *p;

116 117
    /* InitSlot timer */
    struct ev_timer init_watcher;
118 119 120 121 122 123

    /* SPDUSend callback, if p_spdu is not NULL */
    /* SessionOpen callback, if not 0 */
    int i_pending_session_id;
} ci_slot_t;

124 125
int i_ca_handle = 0;
int i_ca_type = -1;
126

127 128
static struct ev_io cam_watcher;
static struct ev_timer slot_watcher;
129
static int i_nb_slots = 0;
130
static ci_slot_t p_slots[MAX_CI_SLOTS];
131 132 133 134 135
static en50221_session_t p_sessions[MAX_SESSIONS];

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
136 137 138 139
static void SessionOpenCb( access_t *p_access, uint8_t i_slot );
static void SPDUHandle( access_t * p_access, uint8_t i_slot,
                        uint8_t *p_spdu, int i_size );

140 141 142 143
static void ResourceManagerOpen( access_t * p_access, int i_session_id );
static void ApplicationInformationOpen( access_t * p_access, int i_session_id );
static void ConditionalAccessOpen( access_t * p_access, int i_session_id );
static void DateTimeOpen( access_t * p_access, int i_session_id );
144 145 146
static void ResetSlotCb(struct ev_loop *loop, struct ev_timer *w, int revents);
static void en50221_Read(struct ev_loop *loop, struct ev_io *w, int revents);
static void en50221_Poll(struct ev_loop *loop, struct ev_timer *w, int revents);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
static void MMIOpen( access_t * p_access, int i_session_id );

/*****************************************************************************
 * Utility functions
 *****************************************************************************/
#define SIZE_INDICATOR 0x80

static uint8_t *GetLength( uint8_t *p_data, int *pi_length )
{
    *pi_length = *p_data++;

    if ( (*pi_length & SIZE_INDICATOR) != 0 )
    {
        int l = *pi_length & ~SIZE_INDICATOR;
        int i;

        *pi_length = 0;
        for ( i = 0; i < l; i++ )
            *pi_length = (*pi_length << 8) | *p_data++;
    }

    return p_data;
}

static uint8_t *SetLength( uint8_t *p_data, int i_length )
{
    uint8_t *p = p_data;

    if ( i_length < 128 )
    {
        *p++ = i_length;
    }
    else if ( i_length < 256 )
    {
        *p++ = SIZE_INDICATOR | 0x1;
        *p++ = i_length;
    }
    else if ( i_length < 65536 )
    {
        *p++ = SIZE_INDICATOR | 0x2;
        *p++ = i_length >> 8;
        *p++ = i_length & 0xff;
    }
    else if ( i_length < 16777216 )
    {
        *p++ = SIZE_INDICATOR | 0x3;
        *p++ = i_length >> 16;
        *p++ = (i_length >> 8) & 0xff;
        *p++ = i_length & 0xff;
    }
    else
    {
        *p++ = SIZE_INDICATOR | 0x4;
        *p++ = i_length >> 24;
        *p++ = (i_length >> 16) & 0xff;
        *p++ = (i_length >> 8) & 0xff;
        *p++ = i_length & 0xff;
    }

    return p;
}


/*
 * Transport layer
 */

#define MAX_TPDU_SIZE  4096
215
#define MAX_TPDU_DATA  (MAX_TPDU_SIZE - 7)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

#define DATA_INDICATOR 0x80

#define T_SB           0x80
#define T_RCV          0x81
#define T_CREATE_TC    0x82
#define T_CTC_REPLY    0x83
#define T_DELETE_TC    0x84
#define T_DTC_REPLY    0x85
#define T_REQUEST_TC   0x86
#define T_NEW_TC       0x87
#define T_TC_ERROR     0x88
#define T_DATA_LAST    0xA0
#define T_DATA_MORE    0xA1

231
static void Dump( bool b_outgoing, uint8_t *p_data, int i_size )
232 233 234 235 236 237 238 239 240 241 242
{
#ifdef DEBUG_TPDU
    int i;
#define MAX_DUMP 256
    fprintf(stderr, "%s ", b_outgoing ? "-->" : "<--");
    for ( i = 0; i < i_size && i < MAX_DUMP; i++)
        fprintf(stderr, "%02X ", p_data[i]);
    fprintf(stderr, "%s\n", i_size >= MAX_DUMP ? "..." : "");
#endif
}

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
/*****************************************************************************
 * TPDUWrite
 *****************************************************************************/
static int TPDUWrite( access_t * p_access, uint8_t i_slot )
{
    ci_slot_t *p_slot = &p_slots[i_slot];
    en50221_msg_t *p_send = p_slot->p_send;

    if ( p_slot->b_expect_answer )
        msg_Warn( p_access,
                  "en50221: writing while expecting an answer on slot %u",
                  i_slot );
    if ( p_send == NULL )
    {
        msg_Warn( p_access, "en50221: no data to write on slot %u !", i_slot );
        return -1;
    }
    p_slot->p_send = p_send->p_next;
    if ( p_slot->p_send == NULL )
        p_slot->pp_send_last = &p_slot->p_send;

    Dump( true, p_send->p_data, p_send->i_size );

    if ( write( i_ca_handle, p_send->p_data, p_send->i_size )
          != p_send->i_size )
    {
        msg_Err( p_access, "en50221: cannot write to CAM device (%m)" );
        free( p_send->p_data );
        free( p_send );
        return -1;
    }

    free( p_send->p_data );
    free( p_send );
    p_slot->b_expect_answer = true;

    return 0;
}

282 283 284 285 286 287
/*****************************************************************************
 * TPDUSend
 *****************************************************************************/
static int TPDUSend( access_t * p_access, uint8_t i_slot, uint8_t i_tag,
                     const uint8_t *p_content, int i_length )
{
288
    ci_slot_t *p_slot = &p_slots[i_slot];
289
    uint8_t i_tcid = i_slot + 1;
290 291
    en50221_msg_t *p_send = malloc( sizeof(en50221_msg_t) );
    uint8_t *p_data = malloc( MAX_TPDU_SIZE );
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    int i_size;

    i_size = 0;
    p_data[0] = i_slot;
    p_data[1] = i_tcid;
    p_data[2] = i_tag;

    switch ( i_tag )
    {
    case T_RCV:
    case T_CREATE_TC:
    case T_CTC_REPLY:
    case T_DELETE_TC:
    case T_DTC_REPLY:
    case T_REQUEST_TC:
        p_data[3] = 1; /* length */
        p_data[4] = i_tcid;
        i_size = 5;
        break;

    case T_NEW_TC:
    case T_TC_ERROR:
        p_data[3] = 2; /* length */
        p_data[4] = i_tcid;
        p_data[5] = p_content[0];
        i_size = 6;
        break;

    case T_DATA_LAST:
    case T_DATA_MORE:
    {
        /* i_length <= MAX_TPDU_DATA */
        uint8_t *p = p_data + 3;
        p = SetLength( p, i_length + 1 );
        *p++ = i_tcid;

        if ( i_length )
            memcpy( p, p_content, i_length );
330
        i_size = i_length + (p - p_data);
331
        break;
332
    }
333 334 335 336 337

    default:
        break;
    }

338 339 340 341 342 343 344 345 346
    p_send->p_data = p_data;
    p_send->i_size = i_size;
    p_send->p_next = NULL;

    *p_slot->pp_send_last = p_send;
    p_slot->pp_send_last = &p_send->p_next;

    if ( !p_slot->b_expect_answer )
        return TPDUWrite( p_access, i_slot );
347 348 349 350 351 352 353 354

    return 0;
}


/*****************************************************************************
 * TPDURecv
 *****************************************************************************/
355
static int TPDURecv( access_t * p_access )
356
{
357 358 359
    ci_slot_t *p_slot;
    uint8_t i_tag, i_slot;
    uint8_t p_data[MAX_TPDU_SIZE];
360
    int i_size;
361
    bool b_last = false;
362

363
    do
364
    {
365
        i_size = read( i_ca_handle, p_data, MAX_TPDU_SIZE );
366
    }
367
    while ( i_size < 0 && errno == EINTR );
368

369
    if ( i_size < 5 )
370
    {
371 372 373
        msg_Err( p_access, "en50221: cannot read from CAM device (%d:%m)",
                 i_size );
        return -1;
374 375
    }

376
    Dump( false, p_data, i_size );
377

378 379
    i_slot = p_data[1] - 1;
    i_tag = p_data[2];
380

381
    if ( i_slot >= i_nb_slots )
382
    {
383 384
        msg_Warn( p_access, "en50221: TPDU is from an unknown slot %u",
                  i_slot );
385 386
        return -1;
    }
387
    p_slot = &p_slots[i_slot];
388

389 390 391 392 393 394
    p_slot->b_has_data = !!(p_data[i_size - 4] == T_SB
                             && p_data[i_size - 3] == 2
                             && (p_data[i_size - 1] & DATA_INDICATOR));
    p_slot->b_expect_answer = false;

    switch ( i_tag )
395
    {
396 397
    case T_CTC_REPLY:
        p_slot->b_active = true;
398
        ev_timer_stop(event_loop, &p_slot->init_watcher);
399 400
        msg_Dbg( p_access, "CI slot %d is active", i_slot );
        break;
401

402 403
    case T_SB:
        break;
404

405 406 407 408 409 410 411 412
    case T_DATA_LAST:
        b_last = true;
        /* intended pass-through */
    case T_DATA_MORE:
    {
        en50221_msg_t *p_recv;
        int i_session_size;
        uint8_t *p_session = GetLength( &p_data[3], &i_session_size );
413

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
        if ( i_session_size <= 1 )
            break;
        p_session++;
        i_session_size--;

        if ( p_slot->p_recv == NULL )
        {
            p_slot->p_recv = malloc( sizeof(en50221_msg_t) );
            p_slot->p_recv->p_data = NULL;
            p_slot->p_recv->i_size = 0;
        }

        p_recv = p_slot->p_recv;
        p_recv->p_data = realloc( p_recv->p_data,
                                  p_recv->i_size + i_session_size );
        memcpy( &p_recv->p_data[ p_recv->i_size ], p_session, i_session_size );
        p_recv->i_size += i_session_size;

        if ( b_last )
        {
            SPDUHandle( p_access, i_slot, p_recv->p_data, p_recv->i_size );
            free( p_recv->p_data );
            free( p_recv );
            p_slot->p_recv = NULL;
        }
        break;
    }

    default:
        msg_Warn( p_access, "en50221: unhandled R_TPDU tag %u slot %u", i_tag,
                  i_slot );
        break;
    }

    if ( !p_slot->b_expect_answer && p_slot->p_send != NULL )
        TPDUWrite( p_access, i_slot );
    if ( !p_slot->b_expect_answer && p_slot->i_pending_session_id != 0 )
        SessionOpenCb( p_access, i_slot );
    if ( !p_slot->b_expect_answer && p_slot->b_has_data )
        TPDUSend( p_access, i_slot, T_RCV, NULL, 0 );
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    return 0;
}


/*
 * Session layer
 */

#define ST_SESSION_NUMBER           0x90
#define ST_OPEN_SESSION_REQUEST     0x91
#define ST_OPEN_SESSION_RESPONSE    0x92
#define ST_CREATE_SESSION           0x93
#define ST_CREATE_SESSION_RESPONSE  0x94
#define ST_CLOSE_SESSION_REQUEST    0x95
#define ST_CLOSE_SESSION_RESPONSE   0x96

#define SS_OK             0x00
#define SS_NOT_ALLOCATED  0xF0

#define RI_RESOURCE_MANAGER            0x00010041
#define RI_APPLICATION_INFORMATION     0x00020041
#define RI_CONDITIONAL_ACCESS_SUPPORT  0x00030041
#define RI_HOST_CONTROL                0x00200041
#define RI_DATE_TIME                   0x00240041
#define RI_MMI                         0x00400041

static int ResourceIdToInt( uint8_t *p_data )
{
    return ((int)p_data[0] << 24) | ((int)p_data[1] << 16)
            | ((int)p_data[2] << 8) | p_data[3];
}

/*****************************************************************************
 * SPDUSend
 *****************************************************************************/
490 491
static int SPDUSend( access_t *p_access, int i_session_id,
                      uint8_t *p_data, int i_size )
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
{
    uint8_t *p_spdu = malloc( i_size + 4 );
    uint8_t *p = p_spdu;
    uint8_t i_slot = p_sessions[i_session_id - 1].i_slot;

    *p++ = ST_SESSION_NUMBER;
    *p++ = 0x02;
    *p++ = (i_session_id >> 8);
    *p++ = i_session_id & 0xff;

    memcpy( p, p_data, i_size );

    i_size += 4;
    p = p_spdu;

    while ( i_size > 0 )
    {
        if ( i_size > MAX_TPDU_DATA )
        {
            if ( TPDUSend( p_access, i_slot, T_DATA_MORE, p,
                           MAX_TPDU_DATA ) != 0 )
            {
                msg_Err( p_access, "couldn't send TPDU on session %d",
                         i_session_id );
                free( p_spdu );
                return -1;
            }
            p += MAX_TPDU_DATA;
            i_size -= MAX_TPDU_DATA;
        }
        else
        {
            if ( TPDUSend( p_access, i_slot, T_DATA_LAST, p, i_size )
                    != 0 )
            {
                msg_Err( p_access, "couldn't send TPDU on session %d",
                         i_session_id );
                free( p_spdu );
                return -1;
            }
            i_size = 0;
        }
    }

    free( p_spdu );
    return 0;
}

/*****************************************************************************
 * SessionOpen
 *****************************************************************************/
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
static void SessionOpenCb( access_t *p_access, uint8_t i_slot )
{
    ci_slot_t *p_slot = &p_slots[i_slot];
    int i_session_id = p_slot->i_pending_session_id;
    int i_resource_id = p_sessions[i_session_id - 1].i_resource_id;

    p_slot->i_pending_session_id = 0;

    switch ( i_resource_id )
    {
    case RI_RESOURCE_MANAGER:
        ResourceManagerOpen( p_access, i_session_id ); break;
    case RI_APPLICATION_INFORMATION:
        ApplicationInformationOpen( p_access, i_session_id ); break;
    case RI_CONDITIONAL_ACCESS_SUPPORT:
        ConditionalAccessOpen( p_access, i_session_id ); break;
    case RI_DATE_TIME:
        DateTimeOpen( p_access, i_session_id ); break;
    case RI_MMI:
        MMIOpen( p_access, i_session_id ); break;

    case RI_HOST_CONTROL:
    default:
        msg_Err( p_access, "unknown resource id (0x%x)", i_resource_id );
        p_sessions[i_session_id - 1].i_resource_id = 0;
    }
}

571 572 573
static void SessionOpen( access_t * p_access, uint8_t i_slot,
                         uint8_t *p_spdu, int i_size )
{
574
    ci_slot_t *p_slot = &p_slots[i_slot];
575 576 577 578 579 580 581 582 583 584
    int i_session_id;
    int i_resource_id = ResourceIdToInt( &p_spdu[2] );
    uint8_t p_response[16];
    int i_status = SS_NOT_ALLOCATED;

    for ( i_session_id = 1; i_session_id <= MAX_SESSIONS; i_session_id++ )
    {
        if ( !p_sessions[i_session_id - 1].i_resource_id )
            break;
    }
585
    if ( i_session_id > MAX_SESSIONS )
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    {
        msg_Err( p_access, "too many sessions !" );
        return;
    }
    p_sessions[i_session_id - 1].i_slot = i_slot;
    p_sessions[i_session_id - 1].i_resource_id = i_resource_id;
    p_sessions[i_session_id - 1].pf_close = NULL;
    p_sessions[i_session_id - 1].pf_manage = NULL;

    if ( i_resource_id == RI_RESOURCE_MANAGER
          || i_resource_id == RI_APPLICATION_INFORMATION
          || i_resource_id == RI_CONDITIONAL_ACCESS_SUPPORT
          || i_resource_id == RI_DATE_TIME
          || i_resource_id == RI_MMI )
    {
        i_status = SS_OK;
    }

    p_response[0] = ST_OPEN_SESSION_RESPONSE;
    p_response[1] = 0x7;
    p_response[2] = i_status;
    p_response[3] = p_spdu[2];
    p_response[4] = p_spdu[3];
    p_response[5] = p_spdu[4];
    p_response[6] = p_spdu[5];
    p_response[7] = i_session_id >> 8;
    p_response[8] = i_session_id & 0xff;

614
    if ( TPDUSend( p_access, i_slot, T_DATA_LAST, p_response, 9 ) != 0 )
615 616 617 618 619 620
    {
        msg_Err( p_access,
                 "SessionOpen: couldn't send TPDU on slot %d", i_slot );
        return;
    }

621 622 623 624
    if ( p_slot->i_pending_session_id != 0 )
        msg_Warn( p_access, "overwriting pending session %d",
                  p_slot->i_pending_session_id );
    p_slot->i_pending_session_id = i_session_id;
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
}

#if 0
/* unused code for the moment - commented out to keep gcc happy */
/*****************************************************************************
 * SessionCreate
 *****************************************************************************/
static void SessionCreate( access_t * p_access, int i_slot, int i_resource_id )
{
    uint8_t p_response[16];
    uint8_t i_tag;
    int i_session_id;

    for ( i_session_id = 1; i_session_id <= MAX_SESSIONS; i_session_id++ )
    {
        if ( !p_sessions[i_session_id - 1].i_resource_id )
            break;
    }
643
    if ( i_session_id > MAX_SESSIONS )
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    {
        msg_Err( p_access, "too many sessions !" );
        return;
    }
    p_sessions[i_session_id - 1].i_slot = i_slot;
    p_sessions[i_session_id - 1].i_resource_id = i_resource_id;
    p_sessions[i_session_id - 1].pf_close = NULL;
    p_sessions[i_session_id - 1].pf_manage = NULL;
    p_sessions[i_session_id - 1].p_sys = NULL;

    p_response[0] = ST_CREATE_SESSION;
    p_response[1] = 0x6;
    p_response[2] = i_resource_id >> 24;
    p_response[3] = (i_resource_id >> 16) & 0xff;
    p_response[4] = (i_resource_id >> 8) & 0xff;
    p_response[5] = i_resource_id & 0xff;
    p_response[6] = i_session_id >> 8;
    p_response[7] = i_session_id & 0xff;

    if ( TPDUSend( p_access, i_slot, T_DATA_LAST, p_response, 4 ) !=
            0 )
    {
        msg_Err( p_access,
                 "SessionCreate: couldn't send TPDU on slot %d", i_slot );
        return;
    }
}
#endif

/*****************************************************************************
 * SessionCreateResponse
 *****************************************************************************/
static void SessionCreateResponse( access_t * p_access, uint8_t i_slot,
                                   uint8_t *p_spdu, int i_size )
{
    int i_status = p_spdu[2];
    int i_resource_id = ResourceIdToInt( &p_spdu[3] );
    int i_session_id = ((int)p_spdu[7] << 8) | p_spdu[8];

    if ( i_status != SS_OK )
    {
        msg_Err( p_access, "SessionCreateResponse: failed to open session %d"
                 " resource=0x%x status=0x%x", i_session_id, i_resource_id,
                 i_status );
        p_sessions[i_session_id - 1].i_resource_id = 0;
        return;
    }

    switch ( i_resource_id )
    {
    case RI_RESOURCE_MANAGER:
        ResourceManagerOpen( p_access, i_session_id ); break;
    case RI_APPLICATION_INFORMATION:
        ApplicationInformationOpen( p_access, i_session_id ); break;
    case RI_CONDITIONAL_ACCESS_SUPPORT:
        ConditionalAccessOpen( p_access, i_session_id ); break;
    case RI_DATE_TIME:
        DateTimeOpen( p_access, i_session_id ); break;
    case RI_MMI:
        MMIOpen( p_access, i_session_id ); break;

    case RI_HOST_CONTROL:
    default:
        msg_Err( p_access, "unknown resource id (0x%x)", i_resource_id );
        p_sessions[i_session_id - 1].i_resource_id = 0;
    }
}

/*****************************************************************************
 * SessionSendClose
 *****************************************************************************/
static void SessionSendClose( access_t * p_access, int i_session_id )
{
    uint8_t p_response[16];
    uint8_t i_slot = p_sessions[i_session_id - 1].i_slot;

    p_response[0] = ST_CLOSE_SESSION_REQUEST;
    p_response[1] = 0x2;
    p_response[2] = i_session_id >> 8;
    p_response[3] = i_session_id & 0xff;

    if ( TPDUSend( p_access, i_slot, T_DATA_LAST, p_response, 4 ) !=
            0 )
    {
        msg_Err( p_access,
                 "SessionSendClose: couldn't send TPDU on slot %d", i_slot );
        return;
    }
}

/*****************************************************************************
 * SessionClose
 *****************************************************************************/
static void SessionClose( access_t * p_access, int i_session_id )
{
    uint8_t p_response[16];
    uint8_t i_slot = p_sessions[i_session_id - 1].i_slot;

    if ( p_sessions[i_session_id - 1].pf_close != NULL )
        p_sessions[i_session_id - 1].pf_close( p_access, i_session_id );
    p_sessions[i_session_id - 1].i_resource_id = 0;

    p_response[0] = ST_CLOSE_SESSION_RESPONSE;
    p_response[1] = 0x3;
    p_response[2] = SS_OK;
    p_response[3] = i_session_id >> 8;
    p_response[4] = i_session_id & 0xff;

    if ( TPDUSend( p_access, i_slot, T_DATA_LAST, p_response, 5 ) !=
            0 )
    {
        msg_Err( p_access,
                 "SessionClose: couldn't send TPDU on slot %d", i_slot );
        return;
    }
}

/*****************************************************************************
 * SPDUHandle
 *****************************************************************************/
static void SPDUHandle( access_t * p_access, uint8_t i_slot,
                        uint8_t *p_spdu, int i_size )
{
    int i_session_id;

    switch ( p_spdu[0] )
    {
    case ST_SESSION_NUMBER:
        if ( i_size <= 4 )
            return;
774 775 776 777 778
        i_session_id = (p_spdu[2] << 8) | p_spdu[3];
        if ( i_session_id <= MAX_SESSIONS
              && p_sessions[i_session_id - 1].pf_handle != NULL )
            p_sessions[i_session_id - 1].pf_handle( p_access, i_session_id,
                                                    p_spdu + 4, i_size - 4 );
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
        break;

    case ST_OPEN_SESSION_REQUEST:
        if ( i_size != 6 || p_spdu[1] != 0x4 )
            return;
        SessionOpen( p_access, i_slot, p_spdu, i_size );
        break;

    case ST_CREATE_SESSION_RESPONSE:
        if ( i_size != 9 || p_spdu[1] != 0x7 )
            return;
        SessionCreateResponse( p_access, i_slot, p_spdu, i_size );
        break;

    case ST_CLOSE_SESSION_REQUEST:
        if ( i_size != 4 || p_spdu[1] != 0x2 )
            return;
        i_session_id = ((int)p_spdu[2] << 8) | p_spdu[3];
        SessionClose( p_access, i_session_id );
        break;

    case ST_CLOSE_SESSION_RESPONSE:
        if ( i_size != 5 || p_spdu[1] != 0x3 )
            return;
        i_session_id = ((int)p_spdu[3] << 8) | p_spdu[4];
        if ( p_spdu[2] )
        {
            msg_Err( p_access, "closing a session which is not allocated (%d)",
                     i_session_id );
        }
        else
        {
            if ( p_sessions[i_session_id - 1].pf_close != NULL )
                p_sessions[i_session_id - 1].pf_close( p_access,
                                                              i_session_id );
            p_sessions[i_session_id - 1].i_resource_id = 0;
        }
        break;

    default:
        msg_Err( p_access, "unexpected tag in SPDUHandle (%x)", p_spdu[0] );
        break;
    }
}


/*
 * Application layer
 */

#define AOT_NONE                    0x000000
#define AOT_PROFILE_ENQ             0x9F8010
#define AOT_PROFILE                 0x9F8011
#define AOT_PROFILE_CHANGE          0x9F8012
#define AOT_APPLICATION_INFO_ENQ    0x9F8020
#define AOT_APPLICATION_INFO        0x9F8021
#define AOT_ENTER_MENU              0x9F8022
#define AOT_CA_INFO_ENQ             0x9F8030
#define AOT_CA_INFO                 0x9F8031
#define AOT_CA_PMT                  0x9F8032
#define AOT_CA_PMT_REPLY            0x9F8033
840
#define AOT_CA_UPDATE               0x9F8034
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
#define AOT_TUNE                    0x9F8400
#define AOT_REPLACE                 0x9F8401
#define AOT_CLEAR_REPLACE           0x9F8402
#define AOT_ASK_RELEASE             0x9F8403
#define AOT_DATE_TIME_ENQ           0x9F8440
#define AOT_DATE_TIME               0x9F8441
#define AOT_CLOSE_MMI               0x9F8800
#define AOT_DISPLAY_CONTROL         0x9F8801
#define AOT_DISPLAY_REPLY           0x9F8802
#define AOT_TEXT_LAST               0x9F8803
#define AOT_TEXT_MORE               0x9F8804
#define AOT_KEYPAD_CONTROL          0x9F8805
#define AOT_KEYPRESS                0x9F8806
#define AOT_ENQ                     0x9F8807
#define AOT_ANSW                    0x9F8808
#define AOT_MENU_LAST               0x9F8809
#define AOT_MENU_MORE               0x9F880A
#define AOT_MENU_ANSW               0x9F880B
#define AOT_LIST_LAST               0x9F880C
#define AOT_LIST_MORE               0x9F880D
#define AOT_SUBTITLE_SEGMENT_LAST   0x9F880E
#define AOT_SUBTITLE_SEGMENT_MORE   0x9F880F
#define AOT_DISPLAY_MESSAGE         0x9F8810
#define AOT_SCENE_END_MARK          0x9F8811
#define AOT_SCENE_DONE              0x9F8812
#define AOT_SCENE_CONTROL           0x9F8813
#define AOT_SUBTITLE_DOWNLOAD_LAST  0x9F8814
#define AOT_SUBTITLE_DOWNLOAD_MORE  0x9F8815
#define AOT_FLUSH_DOWNLOAD          0x9F8816
#define AOT_DOWNLOAD_REPLY          0x9F8817
#define AOT_COMMS_CMD               0x9F8C00
#define AOT_CONNECTION_DESCRIPTOR   0x9F8C01
#define AOT_COMMS_REPLY             0x9F8C02
#define AOT_COMMS_SEND_LAST         0x9F8C03
#define AOT_COMMS_SEND_MORE         0x9F8C04
#define AOT_COMMS_RCV_LAST          0x9F8C05
#define AOT_COMMS_RCV_MORE          0x9F8C06

/*****************************************************************************
 * APDUGetTag
 *****************************************************************************/
static int APDUGetTag( const uint8_t *p_apdu, int i_size )
{
    if ( i_size >= 3 )
    {
        int i, t = 0;
        for ( i = 0; i < 3; i++ )
            t = (t << 8) | *p_apdu++;
        return t;
    }

    return AOT_NONE;
}

/*****************************************************************************
 * APDUGetLength
 *****************************************************************************/
static uint8_t *APDUGetLength( uint8_t *p_apdu, int *pi_size )
{
    return GetLength( &p_apdu[3], pi_size );
}

/*****************************************************************************
 * APDUSend
 *****************************************************************************/
static int APDUSend( access_t * p_access, int i_session_id, int i_tag,
907
                      uint8_t *p_data, int i_size )
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
{
    uint8_t *p_apdu = malloc( i_size + 12 );
    uint8_t *p = p_apdu;
    ca_msg_t ca_msg;
    int i_ret;

    *p++ = (i_tag >> 16);
    *p++ = (i_tag >> 8) & 0xff;
    *p++ = i_tag & 0xff;
    p = SetLength( p, i_size );
    if ( i_size )
        memcpy( p, p_data, i_size );
    if ( i_ca_type == CA_CI_LINK )
    {
        i_ret = SPDUSend( p_access, i_session_id, p_apdu, i_size + p - p_apdu );
    }
    else
    {
        if ( i_size + p - p_apdu > 256 )
        {
            msg_Err( p_access, "CAM: apdu overflow" );
            i_ret = -1;
        }
        else
        {
            ca_msg.length = i_size + p - p_apdu;
            if ( i_size == 0 ) ca_msg.length=3;
            memcpy( ca_msg.msg, p_apdu, i_size + p - p_apdu );
            i_ret = ioctl(i_ca_handle, CA_SEND_MSG, &ca_msg );
            if ( i_ret < 0 )
            {
                msg_Err( p_access, "Error sending to CAM: %m" );
                i_ret = -1;
            }
        }
    }
    free( p_apdu );
    return i_ret;
}

/*
 * Resource Manager
 */

/*****************************************************************************
 * ResourceManagerHandle
 *****************************************************************************/
static void ResourceManagerHandle( access_t * p_access, int i_session_id,
                                   uint8_t *p_apdu, int i_size )
{
    int i_tag = APDUGetTag( p_apdu, i_size );

    switch ( i_tag )
    {
    case AOT_PROFILE_ENQ:
    {
        int resources[] = { htonl(RI_RESOURCE_MANAGER),
                            htonl(RI_APPLICATION_INFORMATION),
                            htonl(RI_CONDITIONAL_ACCESS_SUPPORT),
                            htonl(RI_DATE_TIME),
                            htonl(RI_MMI)
                          };
        APDUSend( p_access, i_session_id, AOT_PROFILE, (uint8_t*)resources,
                  sizeof(resources) );
        break;
    }
    case AOT_PROFILE:
        APDUSend( p_access, i_session_id, AOT_PROFILE_CHANGE, NULL, 0 );
        break;

    default:
        msg_Err( p_access, "unexpected tag in ResourceManagerHandle (0x%x)",
                 i_tag );
    }
}

/*****************************************************************************
 * ResourceManagerOpen
 *****************************************************************************/
static void ResourceManagerOpen( access_t * p_access, int i_session_id )
{

    msg_Dbg( p_access, "opening ResourceManager session (%d)", i_session_id );

    p_sessions[i_session_id - 1].pf_handle = ResourceManagerHandle;

    APDUSend( p_access, i_session_id, AOT_PROFILE_ENQ, NULL, 0 );
}

/*
 * Application Information
 */

/*****************************************************************************
 * ApplicationInformationEnterMenu
 *****************************************************************************/
static void ApplicationInformationEnterMenu( access_t * p_access,
                                             int i_session_id )
{
    int i_slot = p_sessions[i_session_id - 1].i_slot;

    msg_Dbg( p_access, "entering MMI menus on session %d", i_session_id );
    APDUSend( p_access, i_session_id, AOT_ENTER_MENU, NULL, 0 );
1011
    p_slots[i_slot].b_mmi_expected = true;
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
}

/*****************************************************************************
 * ApplicationInformationHandle
 *****************************************************************************/
static void ApplicationInformationHandle( access_t * p_access, int i_session_id,
                                          uint8_t *p_apdu, int i_size )
{
    int i_tag = APDUGetTag( p_apdu, i_size );

    switch ( i_tag )
    {
    case AOT_APPLICATION_INFO:
    {
        int i_type, i_manufacturer, i_code;
        int l = 0;
        uint8_t *d = APDUGetLength( p_apdu, &l );

        if ( l < 4 ) break;

        i_type = *d++;
        i_manufacturer = ((int)d[0] << 8) | d[1];
        d += 2;
        i_code = ((int)d[0] << 8) | d[1];
        d += 2;
        d = GetLength( d, &l );
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

        {
            char *psz_name = malloc(l + 1);
            memcpy( psz_name, d, l );
            psz_name[l] = '\0';
            msg_Info( p_access, "CAM: %s, %02X, %04X, %04X",
                      psz_name, i_type, i_manufacturer, i_code );
            switch (i_print_type)
            {
            case PRINT_XML:
                psz_name = dvb_string_xml_escape(psz_name);
1049 1050 1051 1052 1053 1054
                fprintf(print_fh, "<STATUS type=\"cam\" status=\"1\" cam_name=\"%s\" cam_type=\"%d\" cam_manufacturer=\"%d\" cam_product=\"%d\" />\n",
                        psz_name, i_type, i_manufacturer, i_code);
                break;
            case PRINT_TEXT:
                fprintf(print_fh, "CAM name: %s type: %d manufacturer: %d product: %d\n",
                        psz_name, i_type, i_manufacturer, i_code);
1055 1056
                break;
            default:
1057
                break;
1058 1059 1060
            }
            free(psz_name);
        }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        break;
    }
    default:
        msg_Err( p_access,
                 "unexpected tag in ApplicationInformationHandle (0x%x)",
                 i_tag );
    }
}

/*****************************************************************************
 * ApplicationInformationOpen
 *****************************************************************************/
static void ApplicationInformationOpen( access_t * p_access, int i_session_id )
{

    msg_Dbg( p_access, "opening ApplicationInformation session (%d)", i_session_id );

    p_sessions[i_session_id - 1].pf_handle = ApplicationInformationHandle;

    APDUSend( p_access, i_session_id, AOT_APPLICATION_INFO_ENQ, NULL, 0 );
}

/*
 * Conditional Access
 */

typedef struct
{
1089 1090
    int i_nb_system_ids;
    uint16_t *pi_system_ids;
1091 1092 1093 1094 1095

    int i_selected_programs;
    int b_high_level;
} system_ids_t;

1096
static bool CheckSystemID( system_ids_t *p_ids, uint16_t i_id )
1097
{
1098 1099
    int i;
    if( p_ids == NULL ) return false;
1100
    if( p_ids->b_high_level ) return true;
1101

1102
    for ( i = 0; i < p_ids->i_nb_system_ids; i++ )
1103
        if ( p_ids->pi_system_ids[i] == i_id )
1104
            return true;
1105

1106
    return false;
1107 1108 1109 1110 1111
}

/*****************************************************************************
 * CAPMTBuild
 *****************************************************************************/
1112
static bool HasCADescriptors( system_ids_t *p_ids, uint8_t *p_descs )
1113
{
1114 1115
    const uint8_t *p_desc;
    uint16_t j = 0;
1116

1117
    while ( (p_desc = descs_get_desc( p_descs, j )) != NULL )
1118
    {
1119 1120 1121 1122 1123 1124
        uint8_t i_tag = desc_get_tag( p_desc );
        j++;

        if ( i_tag == 0x9 && desc09_validate( p_desc )
              && CheckSystemID( p_ids, desc09_get_sysid( p_desc ) ) )
            return true;
1125 1126
    }

1127
    return false;
1128 1129
}

1130 1131
static void CopyCADescriptors( system_ids_t *p_ids, uint8_t i_cmd,
                               uint8_t *p_infos, uint8_t *p_descs )
1132
{
1133 1134
    const uint8_t *p_desc;
    uint16_t j = 0, k = 0;
1135

1136 1137 1138
    capmti_init( p_infos );
    capmti_set_length( p_infos, 0xfff );
    capmti_set_cmd( p_infos, i_cmd );
1139

1140
    while ( (p_desc = descs_get_desc( p_descs, j )) != NULL )
1141
    {
1142 1143
        uint8_t i_tag = desc_get_tag( p_desc );
        j++;
1144

1145 1146
        if ( i_tag == 0x9 && desc09_validate( p_desc )
              && CheckSystemID( p_ids, desc09_get_sysid( p_desc ) ) )
1147
        {
1148 1149 1150 1151
            uint8_t *p_info = capmti_get_info( p_infos, k );
            k++;
            memcpy( p_info, p_desc,
                    DESC_HEADER_SIZE + desc_get_length( p_desc ) );
1152 1153 1154
        }
    }

1155
    if ( k )
1156
    {
1157 1158
        uint8_t *p_info = capmti_get_info( p_infos, k );
        capmti_set_length( p_infos, p_info - p_infos - DESCS_HEADER_SIZE );
1159 1160
    }
    else
1161
        capmti_set_length( p_infos, 0 );
1162 1163 1164
}

static uint8_t *CAPMTBuild( access_t * p_access, int i_session_id,
1165
                            uint8_t *p_pmt, uint8_t i_list_mgt,
1166 1167 1168 1169
                            uint8_t i_cmd, int *pi_capmt_size )
{
    system_ids_t *p_ids =
        (system_ids_t *)p_sessions[i_session_id - 1].p_sys;
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    uint8_t *p_es;
    uint8_t *p_capmt, *p_capmt_n;
    uint16_t j, k;
    bool b_has_ca = HasCADescriptors( p_ids, pmt_get_descs( p_pmt ) );
    bool b_has_es = false;

    j = 0;
    while ( (p_es = pmt_get_es( p_pmt, j )) != NULL )
    {
        uint16_t i_pid = pmtn_get_pid( p_es );
        j++;

        if ( demux_PIDIsSelected( i_pid ) )
        {
            b_has_es = true;
            b_has_ca = b_has_ca
                        || HasCADescriptors( p_ids, pmtn_get_descs( p_es ) );
        }
    }
1189

1190
    if ( !b_has_es )
1191
    {
1192 1193
        *pi_capmt_size = 0;
        return NULL;
1194 1195
    }

1196
    if ( !b_has_ca )
1197 1198 1199
    {
        msg_Warn( p_access,
                  "no compatible scrambling system for SID %d on session %d",
1200
                  pmt_get_program( p_pmt ), i_session_id );
1201 1202 1203 1204
        *pi_capmt_size = 0;
        return NULL;
    }

1205 1206 1207 1208 1209
    p_capmt = capmt_allocate();
    capmt_init( p_capmt );
    capmt_set_listmanagement( p_capmt, i_list_mgt );
    capmt_set_program( p_capmt, pmt_get_program( p_pmt ) );
    capmt_set_version( p_capmt, psi_get_version( p_pmt ) );
1210

1211 1212
    CopyCADescriptors( p_ids, i_cmd, capmt_get_infos( p_capmt ),
                       pmt_get_descs( p_pmt ) );
1213

1214 1215
    j = 0; k = 0;
    while ( (p_es = pmt_get_es( p_pmt, j )) != NULL )
1216
    {
1217 1218 1219 1220
        uint16_t i_pid = pmtn_get_pid( p_es );
        j++;

        if ( !demux_PIDIsSelected( i_pid ) )
1221 1222
            continue;

1223 1224
        p_capmt_n = capmt_get_es( p_capmt, k );
        k++;
1225

1226 1227 1228
        capmtn_init( p_capmt_n );
        capmtn_set_streamtype( p_capmt_n, pmtn_get_streamtype( p_es ) );
        capmtn_set_pid( p_capmt_n, pmtn_get_pid( p_es ) );
1229

1230 1231
        CopyCADescriptors( p_ids, i_cmd, capmtn_get_infos( p_capmt_n ),
                           pmtn_get_descs( p_es ) );
1232 1233
    }

1234 1235 1236
    p_capmt_n = capmt_get_es( p_capmt, k );
    *pi_capmt_size = p_capmt_n - p_capmt;

1237 1238 1239 1240 1241 1242
    return p_capmt;
}

/*****************************************************************************
 * CAPMTFirst
 *****************************************************************************/
1243
static void CAPMTFirst( access_t * p_access, int i_session_id, uint8_t *p_pmt )
1244 1245 1246 1247 1248
{
    uint8_t *p_capmt;
    int i_capmt_size;

    msg_Dbg( p_access, "adding first CAPMT for SID %d on session %d",
1249
             pmt_get_program( p_pmt ), i_session_id );
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264

    p_capmt = CAPMTBuild( p_access, i_session_id, p_pmt,
                          0x3 /* only */, 0x1 /* ok_descrambling */,
                          &i_capmt_size );

    if ( i_capmt_size )
    {
        APDUSend( p_access, i_session_id, AOT_CA_PMT, p_capmt, i_capmt_size );
        free( p_capmt );
    }
}

/*****************************************************************************
 * CAPMTAdd
 *****************************************************************************/
1265
static void CAPMTAdd( access_t * p_access, int i_session_id, uint8_t *p_pmt )
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
{
    system_ids_t *p_ids =
        (system_ids_t *)p_sessions[i_session_id - 1].p_sys;
    uint8_t *p_capmt;
    int i_capmt_size;

    p_ids->i_selected_programs++;
    if( p_ids->i_selected_programs == 1 )
    {
        CAPMTFirst( p_access, i_session_id, p_pmt );
        return;
    }

    msg_Dbg( p_access, "adding CAPMT for SID %d on session %d",
1280
             pmt_get_program( p_pmt ), i_session_id );
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

    p_capmt = CAPMTBuild( p_access, i_session_id, p_pmt,
                          0x4 /* add */, 0x1 /* ok_descrambling */,
                          &i_capmt_size );

    if ( i_capmt_size )
    {
        APDUSend( p_access, i_session_id, AOT_CA_PMT, p_capmt, i_capmt_size );
        free( p_capmt );
    }
}

/*****************************************************************************
 * CAPMTUpdate
 *****************************************************************************/
1296
static void CAPMTUpdate( access_t * p_access, int i_session_id, uint8_t *p_pmt )
1297 1298 1299 1300 1301
{
    uint8_t *p_capmt;
    int i_capmt_size;

    msg_Dbg( p_access, "updating CAPMT for SID %d on session %d",
1302
             pmt_get_program( p_pmt ), i_session_id );
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

    p_capmt = CAPMTBuild( p_access, i_session_id, p_pmt,
                          0x5 /* update */, 0x1 /* ok_descrambling */,
                          &i_capmt_size );

    if ( i_capmt_size )
    {
        APDUSend( p_access, i_session_id, AOT_CA_PMT, p_capmt, i_capmt_size );
        free( p_capmt );
    }
}

/*****************************************************************************
 * CAPMTDelete
 *****************************************************************************/
1318
static void CAPMTDelete( access_t * p_access, int i_session_id, uint8_t *p_pmt )
1319 1320 1321 1322 1323 1324 1325 1326
{
    system_ids_t *p_ids =
        (system_ids_t *)p_sessions[i_session_id - 1].p_sys;
    uint8_t *p_capmt;
    int i_capmt_size;

    p_ids->i_selected_programs--;
    msg_Dbg( p_access, "deleting CAPMT for SID %d on session %d",
1327
             pmt_get_program( p_pmt ), i_session_id );
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358

    p_capmt = CAPMTBuild( p_access, i_session_id, p_pmt,
                          0x5 /* update */, 0x4 /* not selected */,
                          &i_capmt_size );

    if ( i_capmt_size )
    {
        APDUSend( p_access, i_session_id, AOT_CA_PMT, p_capmt, i_capmt_size );
        free( p_capmt );
    }
}

/*****************************************************************************
 * ConditionalAccessHandle
 *****************************************************************************/
static void ConditionalAccessHandle( access_t * p_access, int i_session_id,
                                     uint8_t *p_apdu, int i_size )
{
    system_ids_t *p_ids =
        (system_ids_t *)p_sessions[i_session_id - 1].p_sys;
    int i_tag = APDUGetTag( p_apdu, i_size );

    switch ( i_tag )
    {
    case AOT_CA_INFO:
    {
        int i;
        int l = 0;
        uint8_t *d = APDUGetLength( p_apdu, &l );
        msg_Dbg( p_access, "CA system IDs supported by the application :" );

1359 1360 1361 1362 1363 1364 1365
        if ( p_ids->i_nb_system_ids )
            free( p_ids->pi_system_ids );
        p_ids->i_nb_system_ids = l / 2;
        p_ids->pi_system_ids = malloc( p_ids->i_nb_system_ids
                                        * sizeof(uint16_t) );

        for ( i = 0; i < p_ids->i_nb_system_ids; i++ )
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
        {
            p_ids->pi_system_ids[i] = ((uint16_t)d[0] << 8) | d[1];
            d += 2;
            msg_Dbg( p_access, "- 0x%x", p_ids->pi_system_ids[i] );
        }

        demux_ResendCAPMTs();
        break;
    }

1376 1377 1378 1379 1380 1381
    case AOT_CA_UPDATE:
        /* http://www.cablelabs.com/specifications/OC-SP-HOSTPOD-IF-I08-011221.pdf */
    case AOT_CA_PMT_REPLY:
        /* We do not care */
        break;

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    default:
        msg_Err( p_access,
                 "unexpected tag in ConditionalAccessHandle (0x%x)",
                 i_tag );
    }
}

/*****************************************************************************
 * ConditionalAccessClose
 *****************************************************************************/
static void ConditionalAccessClose( access_t * p_access, int i_session_id )
{

    msg_Dbg( p_access, "closing ConditionalAccess session (%d)", i_session_id );

    free( p_sessions[i_session_id - 1].p_sys );
}

/*****************************************************************************
 * ConditionalAccessOpen
 *****************************************************************************/
static void ConditionalAccessOpen( access_t * p_access, int i_session_id )
{

    msg_Dbg( p_access, "opening ConditionalAccess session (%d)", i_session_id );

    p_sessions[i_session_id - 1].pf_handle = ConditionalAccessHandle;
    p_sessions[i_session_id - 1].pf_close = ConditionalAccessClose;
    p_sessions[i_session_id - 1].p_sys = malloc(sizeof(system_ids_t));
    memset( p_sessions[i_session_id - 1].p_sys, 0,
            sizeof(system_ids_t) );

    APDUSend( p_access, i_session_id, AOT_CA_INFO_ENQ, NULL, 0 );
}

/*
 * Date Time
 */

typedef struct
{
1423
    int i_session_id;
1424
    int i_interval;
1425
    struct ev_timer watcher;
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
} date_time_t;

/*****************************************************************************
 * DateTimeSend
 *****************************************************************************/
static void DateTimeSend( access_t * p_access, int i_session_id )
{
    date_time_t *p_date =
        (date_time_t *)p_sessions[i_session_id - 1].p_sys;

    time_t t = time(NULL);
    struct tm tm_gmt;
    struct tm tm_loc;

    if ( gmtime_r(&t, &tm_gmt) && localtime_r(&t, &tm_loc) )
    {
        int Y = tm_gmt.tm_year;
        int M = tm_gmt.tm_mon + 1;
        int D = tm_gmt.tm_mday;
        int L = (M == 1 || M == 2) ? 1 : 0;
        int MJD = 14956 + D + (int)((Y - L) * 365.25)
                    + (int)((M + 1 + L * 12) * 30.6001);
        uint8_t p_response[7];

#define DEC2BCD(d) (((d / 10) << 4) + (d % 10))

        p_response[0] = htons(MJD) >> 8;
        p_response[1] = htons(MJD) & 0xff;
        p_response[2] = DEC2BCD(tm_gmt.tm_hour);
        p_response[3] = DEC2BCD(tm_gmt.tm_min);
        p_response[4] = DEC2BCD(tm_gmt.tm_sec);
        p_response[5] = htons(tm_loc.tm_gmtoff / 60) >> 8;
        p_response[6] = htons(tm_loc.tm_gmtoff / 60) & 0xff;

        APDUSend( p_access, i_session_id, AOT_DATE_TIME, p_response, 7 );

1462
        ev_timer_again(event_loop, &p_date->watcher);
1463 1464 1465
    }
}

1466 1467 1468 1469 1470 1471
static void _DateTimeSend(struct ev_loop *loop, struct ev_timer *w, int revents)
{
    date_time_t *p_date = container_of(w, date_time_t, watcher);
    DateTimeSend( NULL, p_date->i_session_id );
}

1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
/*****************************************************************************
 * DateTimeHandle
 *****************************************************************************/
static void DateTimeHandle( access_t * p_access, int i_session_id,
                            uint8_t *p_apdu, int i_size )
{
    date_time_t *p_date =
        (date_time_t *)p_sessions[i_session_id - 1].p_sys;

    int i_tag = APDUGetTag( p_apdu, i_size );

    switch ( i_tag )
    {
    case AOT_DATE_TIME_ENQ:
    {
        int l;
        const uint8_t *d = APDUGetLength( p_apdu, &l );

        if ( l > 0 )
        {
            p_date->i_interval = *d;
            msg_Dbg( p_access, "DateTimeHandle : interval set to %d",
                     p_date->i_interval );
        }
        else
            p_date->i_interval = 0;

1499 1500 1501
        ev_timer_stop(event_loop, &p_date->watcher);
        ev_timer_set(&p_date->watcher, p_date->i_interval,
                     p_date->i_interval);
1502 1503 1504 1505 1506 1507 1508 1509 1510
        DateTimeSend( p_access, i_session_id );
        break;
    }
    default:
        msg_Err( p_access, "unexpected tag in DateTimeHandle (0x%x)", i_tag );
    }
}

/*****************************************************************************
1511
 * DateTimeClose
1512
 *****************************************************************************/
1513
static void DateTimeClose( access_t * p_access, int i_session_id )
1514 1515 1516
{
    date_time_t *p_date =
        (date_time_t *)p_sessions[i_session_id - 1].p_sys;
1517
    ev_timer_stop(event_loop, &p_date->watcher);
1518 1519 1520

    msg_Dbg( p_access, "closing DateTime session (%d)", i_session_id );

1521
    free( p_date );
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
}

/*****************************************************************************
 * DateTimeOpen
 *****************************************************************************/
static void DateTimeOpen( access_t * p_access, int i_session_id )
{
    msg_Dbg( p_access, "opening DateTime session (%d)", i_session_id );

    p_sessions[i_session_id - 1].pf_handle = DateTimeHandle;
1532
    p_sessions[i_session_id - 1].pf_manage = NULL;
1533 1534 1535 1536
    p_sessions[i_session_id - 1].pf_close = DateTimeClose;
    p_sessions[i_session_id - 1].p_sys = malloc(sizeof(date_time_t));
    memset( p_sessions[i_session_id - 1].p_sys, 0, sizeof(date_time_t) );

1537 1538 1539 1540 1541
    date_time_t *p_date =
        (date_time_t *)p_sessions[i_session_id - 1].p_sys;
    p_date->i_session_id = i_session_id;
    ev_timer_init(&p_date->watcher, _DateTimeSend, 0, 0);

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    DateTimeSend( p_access, i_session_id );
}

/*
 * MMI
 */

/* Display Control Commands */

#define DCC_SET_MMI_MODE                          0x01
#define DCC_DISPLAY_CHARACTER_TABLE_LIST          0x02
#define DCC_INPUT_CHARACTER_TABLE_LIST            0x03
#define DCC_OVERLAY_GRAPHICS_CHARACTERISTICS      0x04
#define DCC_FULL_SCREEN_GRAPHICS_CHARACTERISTICS  0x05

/* MMI Modes */

#define MM_HIGH_LEVEL                      0x01
#define MM_LOW_LEVEL_OVERLAY_GRAPHICS      0x02
#define MM_LOW_LEVEL_FULL_SCREEN_GRAPHICS  0x03

/* Display Reply IDs */

#define DRI_MMI_MODE_ACK                              0x01
#define DRI_LIST_DISPLAY_CHARACTER_TABLES             0x02
#define DRI_LIST_INPUT_CHARACTER_TABLES               0x03
#define DRI_LIST_GRAPHIC_OVERLAY_CHARACTERISTICS      0x04
#define DRI_LIST_FULL_SCREEN_GRAPHIC_CHARACTERISTICS  0x05
#define DRI_UNKNOWN_DISPLAY_CONTROL_CMD               0xF0
#define DRI_UNKNOWN_MMI_MODE                          0xF1
#define DRI_UNKNOWN_CHARACTER_TABLE                   0xF2

/* Enquiry Flags */

#define EF_BLIND  0x01

/* Answer IDs */

#define AI_CANCEL  0x00
#define AI_ANSWER  0x01

typedef struct
{
    en50221_mmi_object_t last_object;
} mmi_t;

static inline void en50221_MMIFree( en50221_mmi_object_t *p_object )
{
    int i;

    switch ( p_object->i_object_type )
    {
    case EN50221_MMI_ENQ:
        free( p_object->u.enq.psz_text );
        break;

    case EN50221_MMI_ANSW:
        if ( p_object->u.answ.b_ok )
        {
            free( p_object->u.answ.psz_answ );
        }
        break;

    case EN50221_MMI_MENU:
    case EN50221_MMI_LIST:
        free( p_object->u.menu.psz_title );
        free( p_object->u.menu.psz_subtitle );
        free( p_object->u.menu.psz_bottom );
        for ( i = 0; i < p_object->u.menu.i_choices; i++ )
        {
            free( p_object->u.menu.ppsz_choices[i] );
        }
        free( p_object->u.menu.ppsz_choices );
        break;

    default:
        break;
    }
}

/*****************************************************************************
 * MMISendObject
 *****************************************************************************/
static void MMISendObject( access_t *p_access, int i_session_id,
                           en50221_mmi_object_t *p_object )
{
    int i_slot = p_sessions[i_session_id - 1].i_slot;
    uint8_t *p_data;
    int i_size, i_tag;

    switch ( p_object->i_object_type )
    {
    case EN50221_MMI_ANSW:
        i_tag = AOT_ANSW;
        i_size = 1 + strlen( p_object->u.answ.psz_answ );
        p_data = malloc( i_size );
1638
        p_data[0] = (p_object->u.answ.b_ok == true) ? 0x1 : 0x0;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
        strncpy( (char *)&p_data[1], p_object->u.answ.psz_answ, i_size - 1 );
        break;

    case EN50221_MMI_MENU_ANSW:
        i_tag = AOT_MENU_ANSW;
        i_size = 1;
        p_data = malloc( i_size );
        p_data[0] = p_object->u.menu_answ.i_choice;
        break;

    default:
        msg_Err( p_access, "unknown MMI object %d", p_object->i_object_type );
        return;
    }

    APDUSend( p_access, i_session_id, i_tag, p_data, i_size );
    free( p_data );

1657
    p_slots[i_slot].b_mmi_expected = true;
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
}

/*****************************************************************************
 * MMISendClose
 *****************************************************************************/
static void MMISendClose( access_t *p_access, int i_session_id )
{
    int i_slot = p_sessions[i_session_id - 1].i_slot;

    APDUSend( p_access, i_session_id, AOT_CLOSE_MMI, NULL, 0 );

1669
    p_slots[i_slot].b_mmi_expected = true;
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
}

/*****************************************************************************
 * MMIDisplayReply
 *****************************************************************************/
static void MMIDisplayReply( access_t *p_access, int i_session_id )
{
    uint8_t p_response[2];

    p_response[0] = DRI_MMI_MODE_ACK;
    p_response[1] = MM_HIGH_LEVEL;

    APDUSend( p_access, i_session_id, AOT_DISPLAY_REPLY, p_response, 2 );

    msg_Dbg( p_access, "sending DisplayReply on session (%d)", i_session_id );
}

/*****************************************************************************
 * MMIGetText
 *****************************************************************************/
static char *MMIGetText( access_t *p_access, uint8_t **pp_apdu, int *pi_size )
{
    int i_tag = APDUGetTag( *pp_apdu, *pi_size );
    int l;
    uint8_t *d;

    if ( i_tag != AOT_TEXT_LAST )
    {
        msg_Err( p_access, "unexpected text tag: %06x", i_tag );
        *pi_size = 0;
        return strdup( "" );
    }

    d = APDUGetLength( *pp_apdu, &l );

    *pp_apdu += l + 4;
    *pi_size -= l + 4;

1708
    return dvb_string_get( d, l, demux_Iconv, p_access );
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
}

/*****************************************************************************
 * MMIHandleEnq
 *****************************************************************************/
static void MMIHandleEnq( access_t *p_access, int i_session_id,
                          uint8_t *p_apdu, int i_size )
{
    mmi_t *p_mmi = (mmi_t *)p_sessions[i_session_id - 1].p_sys;
    int i_slot = p_sessions[i_session_id - 1].i_slot;
    int l;
    uint8_t *d = APDUGetLength( p_apdu, &l );

    en50221_MMIFree( &p_mmi->last_object );
    p_mmi->last_object.i_object_type = EN50221_MMI_ENQ;
1724
    p_mmi->last_object.u.enq.b_blind = (*d & 0x1) ? true : false;
1725 1726 1727 1728 1729 1730 1731
    d += 2; /* skip answer_text_length because it is not mandatory */
    l -= 2;
    p_mmi->last_object.u.enq.psz_text = malloc( l + 1 );
    strncpy( p_mmi->last_object.u.enq.psz_text, (char *)d, l );
    p_mmi->last_object.u.enq.psz_text[l] = '\0';

    msg_Dbg( p_access, "MMI enq: %s%s", p_mmi->last_object.u.enq.psz_text,
1732
             p_mmi->last_object.u.enq.b_blind == true ? " (blind)" : "" );
1733 1734 1735

    p_slots[i_slot].b_mmi_expected = false;
    p_slots[i_slot].b_mmi_undisplayed = true;
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
}

/*****************************************************************************
 * MMIHandleMenu
 *****************************************************************************/
static void MMIHandleMenu( access_t *p_access, int i_session_id, int i_tag,
                           uint8_t *p_apdu, int i_size )
{
    mmi_t *p_mmi = (mmi_t *)p_sessions[i_session_id - 1].p_sys;
    int i_slot = p_sessions[i_session_id - 1].i_slot;
    int l;
    uint8_t *d = APDUGetLength( p_apdu, &l );

    en50221_MMIFree( &p_mmi->last_object );
    p_mmi->last_object.i_object_type = (i_tag == AOT_MENU_LAST) ?
                                       EN50221_MMI_MENU : EN50221_MMI_LIST;
    p_mmi->last_object.u.menu.i_choices = 0;
    p_mmi->last_object.u.menu.ppsz_choices = NULL;

    if ( l > 0 )
    {
        l--; d++; /* choice_nb */

#define GET_FIELD( x )                                                      \
        if ( l > 0 )                                                        \
        {                                                                   \
            p_mmi->last_object.u.menu.psz_##x                               \
                            = MMIGetText( p_access, &d, &l );               \
            msg_Dbg( p_access, "MMI " STRINGIFY( x ) ": %s",                \
                     p_mmi->last_object.u.menu.psz_##x );                   \
        }

        GET_FIELD( title );
        GET_FIELD( subtitle );
        GET_FIELD( bottom );
#undef GET_FIELD

        while ( l > 0 )
        {
            char *psz_text = MMIGetText( p_access, &d, &l );
            TAB_APPEND( p_mmi->last_object.u.menu.i_choices,
                        p_mmi->last_object.u.menu.ppsz_choices,
                        psz_text );
            msg_Dbg( p_access, "MMI choice: %s", psz_text );
        }
    }
1782 1783 1784

    p_slots[i_slot].b_mmi_expected = false;
    p_slots[i_slot].b_mmi_undisplayed = true;
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
}

/*****************************************************************************
 * MMIHandle
 *****************************************************************************/
static void MMIHandle( access_t *p_access, int i_session_id,
                       uint8_t *p_apdu, int i_size )
{
    int i_tag = APDUGetTag( p_apdu, i_size );

    switch ( i_tag )
    {
    case AOT_DISPLAY_CONTROL:
    {
        int l;
        uint8_t *d = APDUGetLength( p_apdu, &l );

        if ( l > 0 )
        {
            switch ( *d )
            {
            case DCC_SET_MMI_MODE:
                if ( l == 2 && d[1] == MM_HIGH_LEVEL )
                    MMIDisplayReply( p_access, i_session_id );
                else
                    msg_Err( p_access, "unsupported MMI mode %02x", d[1] );
                break;

            default:
                msg_Err( p_access, "unsupported display control command %02x",
                         *d );
                break;
            }
        }
        break;
    }

    case AOT_ENQ:
        MMIHandleEnq( p_access, i_session_id, p_apdu, i_size );
        break;

    case AOT_LIST_LAST:
    case AOT_MENU_LAST:
        MMIHandleMenu( p_access, i_session_id, i_tag, p_apdu, i_size );
        break;

    case AOT_CLOSE_MMI:
        SessionSendClose( p_access, i_session_id );
        break;

    default:
        msg_Err( p_access, "unexpected tag in MMIHandle (0x%x)", i_tag );
    }
}

/*****************************************************************************
 * MMIClose
 *****************************************************************************/
static void MMIClose( access_t *p_access, int i_session_id )
{
    int i_slot = p_sessions[i_session_id - 1].i_slot;
    mmi_t *p_mmi = (mmi_t *)p_sessions[i_session_id - 1].p_sys;

    en50221_MMIFree( &p_mmi->last_object );
    free( p_sessions[i_session_id - 1].p_sys );

    msg_Dbg( p_access, "closing MMI session (%d)", i_session_id );
1852 1853 1854

    p_slots[i_slot].b_mmi_expected = false;
    p_slots[i_slot].b_mmi_undisplayed = true;
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
}

/*****************************************************************************
 * MMIOpen
 *****************************************************************************/
static void MMIOpen( access_t *p_access, int i_session_id )
{
    mmi_t *p_mmi;

    msg_Dbg( p_access, "opening MMI session (%d)", i_session_id );

    p_sessions[i_session_id - 1].pf_handle = MMIHandle;
    p_sessions[i_session_id - 1].pf_close = MMIClose;
    p_sessions[i_session_id - 1].p_sys = malloc(sizeof(mmi_t));
    p_mmi = (mmi_t *)p_sessions[i_session_id - 1].p_sys;
    p_mmi->last_object.i_object_type = EN50221_MMI_NONE;
}


/*
 * Hardware handling
 */

/*****************************************************************************
 * InitSlot: Open the transport layer
 *****************************************************************************/
1881
static void InitSlot( access_t * p_access, int i_slot )
1882
{
1883
    if ( TPDUSend( p_access, i_slot, T_CREATE_TC, NULL, 0 ) != 0 )
1884 1885 1886 1887 1888 1889 1890 1891 1892
        msg_Err( p_access, "en50221_Init: couldn't send TPDU on slot %d",
                 i_slot );
}

/*****************************************************************************
 * ResetSlot
 *****************************************************************************/
static void ResetSlot( int i_slot )
{
1893
    ci_slot_t *p_slot = &p_slots[i_slot];
1894 1895
    int i_session_id;

1896 1897 1898
    switch (i_print_type)
    {
    case PRINT_XML:
1899 1900 1901 1902
        fprintf(print_fh, "<STATUS type=\"cam\" status=\"0\" />\n");
        break;
    case PRINT_TEXT:
        fprintf(print_fh, "CAM none\n");
1903 1904 1905 1906 1907
        break;
    default:
        break;
    }

1908 1909
    if ( ioctl( i_ca_handle, CA_RESET, 1 << i_slot ) != 0 )
        msg_Err( NULL, "en50221_Poll: couldn't reset slot %d", i_slot );
1910
    p_slot->b_active = false;
1911 1912 1913
    ev_timer_init(&p_slot->init_watcher, ResetSlotCb,
                  CAM_INIT_TIMEOUT / 1000000., 0);
    ev_timer_start(event_loop, &p_slot->init_watcher);
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    p_slot->b_expect_answer = false;
    p_slot->b_mmi_expected = false;
    p_slot->b_mmi_undisplayed = false;
    if ( p_slot->p_recv != NULL )
    {
        free( p_slot->p_recv->p_data );
        free( p_slot->p_recv );
    }
    p_slot->p_recv = NULL;
    while ( p_slot->p_send != NULL )
    {
        en50221_msg_t *p_next = p_slot->p_send->p_next;
        free( p_slot->p_send->p_data );
        free( p_slot->p_send );
        p_slot->p_send = p_next;
    }
    p_slot->pp_send_last = &p_slot->p_send;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

    /* Close all sessions for this slot. */
    for ( i_session_id = 1; i_session_id <= MAX_SESSIONS; i_session_id++ )
    {
        if ( p_sessions[i_session_id - 1].i_resource_id
              && p_sessions[i_session_id - 1].i_slot == i_slot )
        {
            if ( p_sessions[i_session_id - 1].pf_close != NULL )
            {
                p_sessions[i_session_id - 1].pf_close( NULL, i_session_id );
            }
            p_sessions[i_session_id - 1].i_resource_id = 0;
        }
    }
}

1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
static void ResetSlotCb(struct ev_loop *loop, struct ev_timer *w, int revents)
{
    ci_slot_t *p_slot = container_of(w, ci_slot_t, init_watcher);
    int i_slot = p_slot - &p_slots[0];

    if ( p_slot->b_active || !p_slot->b_expect_answer )
        return;

    msg_Warn( NULL, "no answer from CAM, resetting slot %d",
              i_slot );
    switch (i_print_type) {
    case PRINT_XML:
        fprintf(print_fh,
                "<EVENT type=\"reset\" cause=\"cam_mute\" />\n");
        break;
    case PRINT_TEXT:
       fprintf(print_fh, "reset cause: cam_mute\n");
       break;
    default:
       break;
    }

    ResetSlot( i_slot );
}

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

/*
 * External entry points
 */

/*****************************************************************************
 * en50221_Init : Initialize the CAM for en50221
 *****************************************************************************/
void en50221_Init( void )
{
    char psz_tmp[128];
    ca_caps_t caps;

    memset( &caps, 0, sizeof( ca_caps_t ));

1987
    sprintf( psz_tmp, "/dev/dvb/adapter%d/ca%d", i_adapter, i_canum );
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
    if( (i_ca_handle = open(psz_tmp, O_RDWR | O_NONBLOCK)) < 0 )
    {
        msg_Warn( NULL, "failed opening CAM device %s (%s)",
                  psz_tmp, strerror(errno) );
        i_ca_handle = 0;
        return;
    }

    if ( ioctl( i_ca_handle, CA_GET_CAP, &caps ) != 0 )
    {
        msg_Err( NULL, "failed getting CAM capabilities (%s)",
                 strerror(errno) );
        close( i_ca_handle );
        i_ca_handle = 0;
        return;
    }

    /* Output CA capabilities */
    msg_Dbg( NULL, "CA interface with %d %s", caps.slot_num,
        caps.slot_num == 1 ? "slot" : "slots" );
    if ( caps.slot_type & CA_CI )
        msg_Dbg( NULL, "  CI high level interface type" );
    if ( caps.slot_type & CA_CI_LINK )
        msg_Dbg( NULL, "  CI link layer level interface type" );
    if ( caps.slot_type & CA_CI_PHYS )
        msg_Dbg( NULL, "  CI physical layer level interface type (not supported) " );
    if ( caps.slot_type & CA_DESCR )
        msg_Dbg( NULL, "  built-in descrambler detected" );
    if ( caps.slot_type & CA_SC )
        msg_Dbg( NULL, "  simple smart card interface" );

    msg_Dbg( NULL, "  %d available %s", caps.descr_num,
        caps.descr_num == 1 ? "descrambler (key)" : "descramblers (keys)" );
    if ( caps.descr_type & CA_ECD )
        msg_Dbg( NULL, "  ECD scrambling system supported" );
    if ( caps.descr_type & CA_NDS )
        msg_Dbg( NULL, "  NDS scrambling system supported" );
    if ( caps.descr_type & CA_DSS )
        msg_Dbg( NULL, "  DSS scrambling system supported" );

    if ( caps.slot_num == 0 )
    {
        msg_Err( NULL, "CAM module with no slots" );
        close( i_ca_handle );
        i_ca_handle = 0;
        return;
    }

    if( caps.slot_type & CA_CI_LINK )
        i_ca_type = CA_CI_LINK;
    else if( caps.slot_type & CA_CI )
        i_ca_type = CA_CI;
    else
    {
        msg_Err( NULL, "Incompatible CAM interface" );
        close( i_ca_handle );
        i_ca_handle = 0;
        return;
    }

    i_nb_slots = caps.slot_num;
    memset( p_sessions, 0, sizeof(en50221_session_t) * MAX_SESSIONS );

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
    if( i_ca_type & CA_CI_LINK )
    {
        ev_io_init(&cam_watcher, en50221_Read, i_ca_handle, EV_READ);
        ev_io_start(event_loop, &cam_watcher);

        ev_timer_init(&slot_watcher, en50221_Poll, CA_POLL_PERIOD / 1000000.,
                      CA_POLL_PERIOD / 1000000.);
        ev_timer_start(event_loop, &slot_watcher);
    }

2061 2062 2063 2064 2065 2066 2067 2068
    en50221_Reset();
}

/*****************************************************************************
 * en50221_Reset : Reset the CAM for en50221
 *****************************************************************************/
void en50221_Reset( void )
{
2069
    memset( p_slots, 0, sizeof(ci_slot_t) * MAX_CI_SLOTS );
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125

    if( i_ca_type & CA_CI_LINK )
    {
        int i_slot;
        for ( i_slot = 0; i_slot < i_nb_slots; i_slot++ )
            ResetSlot( i_slot );
    }
    else
    {
        struct ca_slot_info info;
        system_ids_t *p_ids;
        ca_msg_t ca_msg;
        info.num = 0;

        /* We don't reset the CAM in that case because it's done by the
         * ASIC. */
        if ( ioctl( i_ca_handle, CA_GET_SLOT_INFO, &info ) < 0 )
        {
            msg_Err( NULL, "en50221_Init: couldn't get slot info" );
            close( i_ca_handle );
            i_ca_handle = 0;
            return;
        }
        if( info.flags == 0 )
        {
            msg_Err( NULL, "en50221_Init: no CAM inserted" );
            close( i_ca_handle );
            i_ca_handle = 0;
            return;
        }

        /* Allocate a dummy sessions */
        p_sessions[0].i_resource_id = RI_CONDITIONAL_ACCESS_SUPPORT;
        p_sessions[0].pf_close = ConditionalAccessClose;
        if ( p_sessions[0].p_sys == NULL )
            p_sessions[0].p_sys = malloc(sizeof(system_ids_t));
        memset( p_sessions[0].p_sys, 0, sizeof(system_ids_t) );
        p_ids = (system_ids_t *)p_sessions[0].p_sys;
        p_ids->b_high_level = 1;

        /* Get application info to find out which cam we are using and make
           sure everything is ready to play */
        ca_msg.length=3;
        ca_msg.msg[0] = ( AOT_APPLICATION_INFO & 0xFF0000 ) >> 16;
        ca_msg.msg[1] = ( AOT_APPLICATION_INFO & 0x00FF00 ) >> 8;
        ca_msg.msg[2] = ( AOT_APPLICATION_INFO & 0x0000FF ) >> 0;
        memset( &ca_msg.msg[3], 0, 253 );
        APDUSend( NULL, 1, AOT_APPLICATION_INFO_ENQ, NULL, 0 );
        if ( ioctl( i_ca_handle, CA_GET_MSG, &ca_msg ) < 0 )
        {
            msg_Err( NULL, "en50221_Init: failed getting message" );
            close( i_ca_handle );
            i_ca_handle = 0;
            return;
        }

2126
#ifdef HLCI_WAIT_CAM_READY
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
        while( ca_msg.msg[8] == 0xff && ca_msg.msg[9] == 0xff )
        {
            msleep(1);
            msg_Dbg( NULL, "CAM: please wait" );
            APDUSend( NULL, 1, AOT_APPLICATION_INFO_ENQ, NULL, 0 );
            ca_msg.length=3;
            ca_msg.msg[0] = ( AOT_APPLICATION_INFO & 0xFF0000 ) >> 16;
            ca_msg.msg[1] = ( AOT_APPLICATION_INFO & 0x00FF00 ) >> 8;
            ca_msg.msg[2] = ( AOT_APPLICATION_INFO & 0x0000FF ) >> 0;
            memset( &ca_msg.msg[3], 0, 253 );
            if ( ioctl( i_ca_handle, CA_GET_MSG, &ca_msg ) < 0 )
            {
                msg_Err( NULL, "en50221_Init: failed getting message" );
                close( i_ca_handle );
                i_ca_handle = 0;
                return;
            }
            msg_Dbg( NULL, "en50221_Init: Got length: %d, tag: 0x%x", ca_msg.length, APDUGetTag( ca_msg.msg, ca_msg.length ) );
        }
#else
        if( ca_msg.msg[8] == 0xff && ca_msg.msg[9] == 0xff )
        {
            msg_Err( NULL, "CAM returns garbage as application info!" );
            close( i_ca_handle );
            i_ca_handle = 0;
            return;
        }
#endif
        msg_Dbg( NULL, "found CAM %s using id 0x%x", &ca_msg.msg[12],
                 (ca_msg.msg[8]<<8)|ca_msg.msg[9] );
    }
}

/*****************************************************************************
2161 2162
 * en50221_Read : Read the CAM for a TPDU
 *****************************************************************************/
2163
static void en50221_Read(struct ev_loop *loop, struct ev_io *w, int revents)
2164 2165
{
    TPDURecv( NULL );
2166 2167

    ev_timer_again(event_loop, &slot_watcher);
2168 2169 2170 2171
}

/*****************************************************************************
 * en50221_Poll : Send a poll TPDU to the CAM
2172
 *****************************************************************************/
2173
static void en50221_Poll(struct ev_loop *loop, struct ev_timer *w, int revents)
2174 2175 2176 2177
{
    int i_slot;
    int i_session_id;

2178
    /* Check module status */
2179