libdvdcss.c 24.5 KB
Newer Older
1
/* libdvdcss.c: DVD reading library.
Sam Hocevar's avatar
 
Sam Hocevar committed
2
 *
3
 * Authors: Stéphane Borel <stef@via.ecp.fr>
4
 *          Sam Hocevar <sam@zoy.org>
5
 *          Håkan Hjort <d95hjort@dtek.chalmers.se>
Sam Hocevar's avatar
 
Sam Hocevar committed
6
 *
7
 * Copyright (C) 1998-2008 VideoLAN
8
 *
9
 * libdvdcss is free software; you can redistribute it and/or modify
Sam Hocevar's avatar
 
Sam Hocevar committed
10
11
12
 * 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.
13
 *
14
 * libdvdcss is distributed in the hope that it will be useful,
Sam Hocevar's avatar
 
Sam Hocevar committed
15
16
17
18
 * 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.
 *
Diego Biurrun's avatar
Diego Biurrun committed
19
 * You should have received a copy of the GNU General Public License along
20
 * with libdvdcss; if not, write to the Free Software Foundation, Inc.,
Diego Biurrun's avatar
Diego Biurrun committed
21
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
23
 */

24
/**
25
26
27
28
29
30
31
 * \mainpage libdvdcss developer documentation
 *
 * \section intro Introduction
 *
 * \e libdvdcss is a simple library designed for accessing DVDs like a block
 * device without having to bother about the decryption. The important features
 * are:
32
 * \li portability: Currently supported platforms are GNU/Linux, FreeBSD,
33
 *     NetBSD, OpenBSD, Haiku, Mac OS X, Solaris, QNX, OS/2, and Windows
34
 *     NT 4.0 SP4 (with IE 5.0) or later.
35
 * \li adaptability: Unlike most similar projects, libdvdcss does not require
36
37
 *     the region of your drive to be set and will try its best to read from
 *     the disc even in the case of a region mismatch.
38
 * \li simplicity: A DVD player can be built around the \e libdvdcss API using
39
40
 *     no more than 4 or 5 library calls.
 *
41
 * \e libdvdcss is free software, released under the GNU General Public License.
42
43
44
45
46
47
48
49
50
51
 * This ensures that \e libdvdcss remains free and used only with free
 * software.
 *
 * \section api The libdvdcss API
 *
 * The complete \e libdvdcss programming interface is documented in the
 * dvdcss.h file.
 *
 * \section env Environment variables
 *
52
 * Some environment variables can be used to change the behavior of
53
54
55
 * \e libdvdcss without having to modify the program which uses it. These
 * variables are:
 *
56
 * \li \b DVDCSS_VERBOSE: Sets the verbosity level.
57
58
59
60
 *     - \c 0 outputs no messages at all.
 *     - \c 1 outputs error messages to stderr.
 *     - \c 2 outputs error messages and debug messages to stderr.
 *
61
 * \li \b DVDCSS_METHOD: Sets the authentication and decryption method
62
63
64
65
66
67
68
69
70
71
72
 *     that \e libdvdcss will use to read scrambled discs. Can be one
 *     of \c title, \c key or \c disc.
 *     - \c key is the default method. \e libdvdcss will use a set of
 *       calculated player keys to try and get the disc key. This can fail
 *       if the drive does not recognize any of the player keys.
 *     - \c disc is a fallback method when \c key has failed. Instead of
 *       using player keys, \e libdvdcss will crack the disc key using
 *       a brute force algorithm. This process is CPU intensive and requires
 *       64 MB of memory to store temporary data.
 *     - \c title is the fallback when all other methods have failed. It does
 *       not rely on a key exchange with the DVD drive, but rather uses a
73
 *       crypto attack to guess the title key. In rare cases this may fail
74
 *       because there is not enough encrypted data on the disc to perform
75
 *       a statistical attack, but on the other hand it is the only way to
76
77
78
 *       decrypt a DVD stored on a hard disc, or a DVD with the wrong region
 *       on an RPC2 drive.
 *
79
 * \li \b DVDCSS_RAW_DEVICE: Specify the raw device to use. Exact usage will
80
81
82
83
 *     depend on your operating system, the Linux utility to set up raw devices
 *     is \c raw(8) for instance. Please note that on most operating systems,
 *     using a raw device requires highly aligned buffers: Linux requires a
 *     2048 bytes alignment (which is the size of a DVD sector).
84
 *
85
 * \li \b DVDCSS_CACHE: Specify a directory in which to cache title key
86
87
88
 *     values. This will speed up descrambling of DVDs which are in the
 *     cache. The DVDCSS_CACHE directory is created if it does not exist,
 *     and a subdirectory is created named after the DVD's title or
89
90
91
92
 *     manufacturing date. If DVDCSS_CACHE is not set or is empty, \e libdvdcss
 *     will use the default value which is "${HOME}/.dvdcss/" under Unix and
 *     "C:\Documents and Settings\$USER\Application Data\dvdcss\" under Win32.
 *     The special value "off" disables caching.
93
 */
Sam Hocevar's avatar
 
Sam Hocevar committed
94

95
/*
Sam Hocevar's avatar
 
Sam Hocevar committed
96
 * Preamble
97
 */
Sam Hocevar's avatar
 
Sam Hocevar committed
98
99
100
101
102
103
104
#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
105
106
107
#ifdef HAVE_SYS_PARAM_H
#   include <sys/param.h>
#endif
108
109
110
#ifdef HAVE_PWD_H
#   include <pwd.h>
#endif
Sam Hocevar's avatar
 
Sam Hocevar committed
111
#include <fcntl.h>
112
#include <errno.h>
Sam Hocevar's avatar
 
Sam Hocevar committed
113
114
115
116
117

#ifdef HAVE_UNISTD_H
#   include <unistd.h>
#endif

Christophe Massiot's avatar
Christophe Massiot committed
118
#ifdef HAVE_LIMITS_H
119
120
121
#   include <limits.h>
#endif

122
123
124
125
#if defined(_WIN32_IE) && _WIN32_IE >= 0x500
#   include <shlobj.h>
#endif

Sam Hocevar's avatar
   
Sam Hocevar committed
126
#include "dvdcss/dvdcss.h"
Sam Hocevar's avatar
 
Sam Hocevar committed
127
128
129
130
131

#include "common.h"
#include "css.h"
#include "libdvdcss.h"
#include "ioctl.h"
132
#include "device.h"
Sam Hocevar's avatar
 
Sam Hocevar committed
133

134
#ifdef HAVE_BROKEN_MKDIR
135
#include <direct.h>
136
137
138
#define mkdir(a, b) _mkdir(a)
#endif

139
140
141
142
143
144
145
146
147

#define STRING_KEY_SIZE (KEY_SIZE * 2)
#define INTERESTING_SECTOR 16
#define DISC_TITLE_OFFSET  40
#define DISC_TITLE_LENGTH  32
#define MANUFACTURING_DATE_OFFSET 813
#define MANUFACTURING_DATE_LENGTH  16


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
static void set_verbosity( dvdcss_t dvdcss )
{
    const char *psz_verbose = getenv( "DVDCSS_VERBOSE" );

    dvdcss->b_debug  = 0;
    dvdcss->b_errors = 0;

    if( psz_verbose != NULL )
    {
        int i = atoi( psz_verbose );

        if( i >= 2 )
            dvdcss->b_debug  = 1;
        if( i >= 1 )
            dvdcss->b_errors = 1;
    }
}

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
static int set_access_method( dvdcss_t dvdcss )
{
    const char *psz_method = getenv( "DVDCSS_METHOD" );

    if( !psz_method )
        return 0;

    if( !strncmp( psz_method, "key", 4 ) )
    {
        dvdcss->i_method = DVDCSS_METHOD_KEY;
    }
    else if( !strncmp( psz_method, "disc", 5 ) )
    {
        dvdcss->i_method = DVDCSS_METHOD_DISC;
    }
    else if( !strncmp( psz_method, "title", 5 ) )
    {
        dvdcss->i_method = DVDCSS_METHOD_TITLE;
    }
    else
    {
        print_error( dvdcss, "unknown decrypt method, please choose "
                     "from 'title', 'key' or 'disc'" );
        return -1;
    }
    return 0;
}

194
static char *set_cache_directory( dvdcss_t dvdcss )
Sam Hocevar's avatar
 
Sam Hocevar committed
195
{
196
    char *psz_cache = getenv( "DVDCSS_CACHE" );
Sam Hocevar's avatar
 
Sam Hocevar committed
197

198
199
200
201
202
    if( psz_cache && !strcmp( psz_cache, "off" ) )
    {
        return NULL;
    }

203
204
    if( psz_cache == NULL || psz_cache[0] == '\0' )
    {
205
#if defined(_WIN32_IE) && _WIN32_IE >= 0x500
206
        char psz_home[PATH_MAX];
207
208
209

        /* Cache our keys in
         * C:\Documents and Settings\$USER\Application Data\dvdcss\ */
210
211
        if (SHGetFolderPathA (NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE,
                              NULL, SHGFP_TYPE_CURRENT, psz_home ) == S_OK)
212
        {
213
214
215
            snprintf( dvdcss->psz_cachefile, PATH_MAX, "%s\\dvdcss", psz_home );
            dvdcss->psz_cachefile[PATH_MAX - 1] = '\0';
            psz_cache = dvdcss->psz_cachefile;
216
217
218
        }
#else
        char *psz_home = NULL;
219
#ifdef HAVE_PWD_H
220
221
222
223
224
225
226
227
        struct passwd *p_pwd;

        /* Try looking in password file for home dir. */
        p_pwd = getpwuid(getuid());
        if( p_pwd )
        {
            psz_home = p_pwd->pw_dir;
        }
228
#endif /* HAVE_PWD_H */
229
230
231
232
233
234
235
236
237

        if( psz_home == NULL )
        {
            psz_home = getenv( "HOME" );
        }

        /* Cache our keys in ${HOME}/.dvdcss/ */
        if( psz_home )
        {
KO Myung-Hun's avatar
KO Myung-Hun committed
238
239
            int home_pos = 0;

240
#ifdef __OS2__
KO Myung-Hun's avatar
KO Myung-Hun committed
241
242
            if( *psz_home == '/' || *psz_home == '\\')
            {
243
                const char *psz_unixroot = getenv("UNIXROOT");
KO Myung-Hun's avatar
KO Myung-Hun committed
244
245
246
247
248
249

                if( psz_unixroot &&
                    psz_unixroot[0] &&
                    psz_unixroot[1] == ':'  &&
                    psz_unixroot[2] == '\0')
                {
250
                    strcpy( dvdcss->psz_cachefile, psz_unixroot );
KO Myung-Hun's avatar
KO Myung-Hun committed
251
252
253
                    home_pos = 2;
                }
            }
254
#endif /* __OS2__ */
255
            snprintf( dvdcss->psz_cachefile + home_pos, PATH_MAX - home_pos,
KO Myung-Hun's avatar
KO Myung-Hun committed
256
                      "%s/.dvdcss", psz_home );
257
258
            dvdcss->psz_cachefile[PATH_MAX - 1] = '\0';
            psz_cache = dvdcss->psz_cachefile;
259
        }
260
#endif /* ! defined(_WIN32_IE) && _WIN32_IE >= 0x500 */
261
262
    }

263
    /* Sanity check psz_cache value. */
264
265
    if( psz_cache != NULL )
    {
266
        if( psz_cache[0] == '\0' )
267
        {
268
            return NULL;
269
        }
270
271
272
        /* Check that there is enough space for the cache directory path and the
         * block filename. The +1 are path separators and terminating null byte. */
        else if( strlen( psz_cache ) + 1 + DISC_TITLE_LENGTH + 1 +
273
274
                 MANUFACTURING_DATE_LENGTH + 1 + STRING_KEY_SIZE + 1 +
                 CACHE_FILENAME_LENGTH + 1 > PATH_MAX )
275
        {
276
            print_error( dvdcss, "cache directory name is too long" );
277
            return NULL;
278
279
        }
    }
280
281
282
283
284
285
286
287
288
289
290
291
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
330
331
    return psz_cache;
}

/**
 * \brief Open a DVD device or directory and return a dvdcss instance.
 *
 * \param psz_target a string containing the target name, for instance
 *        "/dev/hdc" or "E:"
 * \return a handle to a dvdcss instance or NULL on error.
 *
 * Initialize the \e libdvdcss library, open the requested DVD device or
 * directory, and return a handle to be used for all subsequent \e libdvdcss
 * calls. \e libdvdcss checks whether ioctls can be performed on the disc,
 * and when possible, the disc key is retrieved.
 */
LIBDVDCSS_EXPORT dvdcss_t dvdcss_open ( const char *psz_target )
{
    int i_ret;

    const char *psz_cache;
#ifdef DVDCSS_RAW_OPEN
    const char *psz_raw_device = getenv( "DVDCSS_RAW_DEVICE" );
#endif

    /* Allocate the library structure. */
    dvdcss_t dvdcss = malloc( sizeof( *dvdcss ) );
    if( dvdcss == NULL )
    {
        return NULL;
    }

    /* Initialize structure with default values. */
#ifdef DVDCSS_RAW_OPEN
    dvdcss->i_raw_fd = -1;
#endif
    dvdcss->p_titles = NULL;
    dvdcss->psz_device = strdup( psz_target );
    dvdcss->psz_error = "no error";
    dvdcss->i_method = DVDCSS_METHOD_KEY;
    dvdcss->psz_cachefile[0] = '\0';

    /* Set library verbosity from DVDCSS_VERBOSE environment variable. */
    set_verbosity( dvdcss );

    /* Set DVD access method from DVDCSS_METHOD environment variable. */
    if( set_access_method( dvdcss ) < 0 )
    {
        goto error;
    }

    /* Set CSS key cache directory. */
    psz_cache = set_cache_directory( dvdcss );
332

333
    /* Open device. */
334
335
    dvdcss_check_device( dvdcss );
    i_ret = dvdcss_open_device( dvdcss );
Sam Hocevar's avatar
 
Sam Hocevar committed
336
337
    if( i_ret < 0 )
    {
338
        goto error;
Sam Hocevar's avatar
 
Sam Hocevar committed
339
    }
340

341
    dvdcss->b_scrambled = 1; /* Assume the worst */
342
    dvdcss->b_ioctls = dvdcss_use_ioctls( dvdcss );
Sam Hocevar's avatar
 
Sam Hocevar committed
343

344
    if( dvdcss->b_ioctls )
Sam Hocevar's avatar
 
Sam Hocevar committed
345
    {
346
        i_ret = dvdcss_test( dvdcss );
347

348
        if( i_ret == -3 )
349
        {
350
351
352
            print_debug( dvdcss, "scrambled disc on a region-free RPC-II "
                                 "drive: possible failure, but continuing "
                                 "anyway" );
353
354
        }
        else if( i_ret < 0 )
Sam Hocevar's avatar
Sam Hocevar committed
355
356
        {
            /* Disable the CSS ioctls and hope that it works? */
357
358
            print_debug( dvdcss,
                         "could not check whether the disc was scrambled" );
Sam Hocevar's avatar
Sam Hocevar committed
359
360
361
362
            dvdcss->b_ioctls = 0;
        }
        else
        {
363
364
            print_debug( dvdcss, i_ret ? "disc is scrambled"
                                       : "disc is unscrambled" );
Sam Hocevar's avatar
Sam Hocevar committed
365
366
            dvdcss->b_scrambled = i_ret;
        }
Sam Hocevar's avatar
 
Sam Hocevar committed
367
368
    }

369
    memset( dvdcss->css.p_disc_key, 0, KEY_SIZE );
Sam Hocevar's avatar
 
Sam Hocevar committed
370
    /* If disc is CSS protected and the ioctls work, authenticate the drive */
371
    if( dvdcss->b_scrambled && dvdcss->b_ioctls )
Sam Hocevar's avatar
 
Sam Hocevar committed
372
    {
373
        i_ret = dvdcss_disckey( dvdcss );
Sam Hocevar's avatar
 
Sam Hocevar committed
374
375
376

        if( i_ret < 0 )
        {
377
            print_debug( dvdcss, "could not get disc key" );
Sam Hocevar's avatar
 
Sam Hocevar committed
378
379
380
        }
    }

Sam Hocevar's avatar
Sam Hocevar committed
381
382
383
    /* If the cache is enabled, write the cache directory tag */
    if( psz_cache )
    {
384
385
        static const char psz_tag[] =
            "Signature: 8a477f597d28d172789f06886806bc55\r\n"
Sam Hocevar's avatar
Sam Hocevar committed
386
387
388
            "# This file is a cache directory tag created by libdvdcss.\r\n"
            "# For information about cache directory tags, see:\r\n"
            "#   http://www.brynosaurus.com/cachedir/\r\n";
389
        char psz_tagfile[PATH_MAX + 1 + 12 + 1];
Sam Hocevar's avatar
Sam Hocevar committed
390
391
        int i_fd;

392
393
394
395
396
397
398
        i_ret = mkdir( psz_cache, 0755 );
        if( i_ret < 0 && errno != EEXIST )
        {
            print_error( dvdcss, "failed creating cache directory" );
            goto nocache;
        }

Sam Hocevar's avatar
Sam Hocevar committed
399
        sprintf( psz_tagfile, "%s/CACHEDIR.TAG", psz_cache );
Sam Hocevar's avatar
Sam Hocevar committed
400
        i_fd = open( psz_tagfile, O_RDWR|O_CREAT, 0644 );
Sam Hocevar's avatar
Sam Hocevar committed
401
402
        if( i_fd >= 0 )
        {
403
404
            ssize_t len = strlen(psz_tag);
            if( write( i_fd, psz_tag, len ) < len )
405
406
407
408
            {
                print_error( dvdcss,
                             "Error writing cache directory tag, continuing..\n" );
            }
Sam Hocevar's avatar
Sam Hocevar committed
409
410
411
412
            close( i_fd );
        }
    }

413
414
415
    /* If the cache is enabled, extract a unique disc ID */
    if( psz_cache )
    {
416
        uint8_t p_sector[DVDCSS_BLOCK_SIZE];
417
        char psz_key[STRING_KEY_SIZE + 1];
Ivan Kalvachev's avatar
   
Ivan Kalvachev committed
418
419
        char *psz_title;
        uint8_t *psz_serial;
420
421
        int i;

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
        /* We read sector 0. If it starts with 0x000001ba (BE), we are
         * reading a VOB file, and we should not cache anything. */

        i_ret = dvdcss->pf_seek( dvdcss, 0 );
        if( i_ret != 0 )
        {
            goto nocache;
        }

        i_ret = dvdcss->pf_read( dvdcss, p_sector, 1 );
        if( i_ret != 1 )
        {
            goto nocache;
        }

        if( p_sector[0] == 0x00 && p_sector[1] == 0x00
             && p_sector[2] == 0x01 && p_sector[3] == 0xba )
        {
            goto nocache;
        }

443
444
445
446
        /* The data we are looking for is at sector 16 (32768 bytes):
         *  - offset 40: disc title (32 uppercase chars)
         *  - offset 813: manufacturing date + serial no (16 digits) */

447
448
        i_ret = dvdcss->pf_seek( dvdcss, INTERESTING_SECTOR );
        if( i_ret != INTERESTING_SECTOR )
449
450
451
452
453
454
455
456
457
458
459
        {
            goto nocache;
        }

        i_ret = dvdcss->pf_read( dvdcss, p_sector, 1 );
        if( i_ret != 1 )
        {
            goto nocache;
        }

        /* Get the disc title */
460
461
        psz_title = (char *)p_sector + DISC_TITLE_OFFSET;
        psz_title[DISC_TITLE_LENGTH] = '\0';
462

463
        for( i = 0; i < DISC_TITLE_LENGTH; i++ )
464
        {
Michael Roitzsch's avatar
   
Michael Roitzsch committed
465
            if( psz_title[i] <= ' ' )
466
            {
Michael Roitzsch's avatar
   
Michael Roitzsch committed
467
                psz_title[i] = '\0';
468
469
                break;
            }
Michael Roitzsch's avatar
   
Michael Roitzsch committed
470
            else if( psz_title[i] == '/' || psz_title[i] == '\\' )
471
            {
Michael Roitzsch's avatar
   
Michael Roitzsch committed
472
                psz_title[i] = '-';
473
474
475
            }
        }

Michael Roitzsch's avatar
   
Michael Roitzsch committed
476
        /* Get the date + serial */
477
478
        psz_serial = p_sector + MANUFACTURING_DATE_OFFSET;
        psz_serial[MANUFACTURING_DATE_LENGTH] = '\0';
479

Michael Roitzsch's avatar
   
Michael Roitzsch committed
480
        /* Check that all characters are digits, otherwise convert. */
481
        for( i = 0 ; i < MANUFACTURING_DATE_LENGTH ; i++ )
Michael Roitzsch's avatar
   
Michael Roitzsch committed
482
483
        {
            if( psz_serial[i] < '0' || psz_serial[i] > '9' )
484
            {
485
                char psz_tmp[MANUFACTURING_DATE_LENGTH + 1];
Sam Hocevar's avatar
Sam Hocevar committed
486
487
                sprintf( psz_tmp,
                         "%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x",
Michael Roitzsch's avatar
   
Michael Roitzsch committed
488
489
490
                         psz_serial[0], psz_serial[1], psz_serial[2],
                         psz_serial[3], psz_serial[4], psz_serial[5],
                         psz_serial[6], psz_serial[7] );
491
                memcpy( psz_serial, psz_tmp, MANUFACTURING_DATE_LENGTH );
Michael Roitzsch's avatar
   
Michael Roitzsch committed
492
                break;
493
494
495
            }
        }

496
497
        /* Get disk key, since some discs have the same title, manufacturing
         * date and serial number, but different keys. */
Sam Hocevar's avatar
Sam Hocevar committed
498
499
500
501
        if( dvdcss->b_scrambled )
        {
             for( i = 0; i < KEY_SIZE; i++ )
             {
502
                 sprintf( &psz_key[i * 2], "%.2x", dvdcss->css.p_disc_key[i] );
Sam Hocevar's avatar
Sam Hocevar committed
503
             }
504
             psz_key[STRING_KEY_SIZE] = '\0';
Sam Hocevar's avatar
Sam Hocevar committed
505
506
507
508
509
510
        }
        else
        {
             psz_key[0] = 0;
        }

511
        /* We have a disc name or ID, we can create the cache subdirectory. */
512
        i = sprintf( dvdcss->psz_cachefile, "%s/%s-%s-%s",
513
                     psz_cache, psz_title, psz_serial, psz_key );
514
515
516
        i_ret = mkdir( dvdcss->psz_cachefile, 0755 );
        if( i_ret < 0 && errno != EEXIST )
        {
517
            print_error( dvdcss, "failed creating cache subdirectory" );
518
519
520
            dvdcss->psz_cachefile[0] = '\0';
            goto nocache;
        }
Christopher Richards's avatar
   
Christopher Richards committed
521
        i += sprintf( dvdcss->psz_cachefile + i, "/");
522
523
524
525

        /* Pointer to the filename we will use. */
        dvdcss->psz_block = dvdcss->psz_cachefile + i;

526
527
        print_debug( dvdcss, "using CSS key cache dir: %s",
                             dvdcss->psz_cachefile );
528
529
530
    }
    nocache:

531
#ifdef DVDCSS_RAW_OPEN
Michael Roitzsch's avatar
   
Michael Roitzsch committed
532
533
    if( psz_raw_device != NULL )
    {
534
        dvdcss_raw_open( dvdcss, psz_raw_device );
Michael Roitzsch's avatar
   
Michael Roitzsch committed
535
    }
536
#endif /* DVDCSS_RAW_OPEN */
Michael Roitzsch's avatar
   
Michael Roitzsch committed
537

538
    /* Seek to the beginning, just for safety. */
539
540
    dvdcss->pf_seek( dvdcss, 0 );

Sam Hocevar's avatar
 
Sam Hocevar committed
541
    return dvdcss;
542
543
544
545
546

error:
    free( dvdcss->psz_device );
    free( dvdcss );
    return NULL;
Sam Hocevar's avatar
 
Sam Hocevar committed
547
548
}

549
/**
550
 * \brief Return a string containing the last error that occurred in the
551
552
 *        given \e libdvdcss instance.
 *
553
554
 * \param dvdcss a \e libdvdcss instance
 * \return a NULL-terminated string containing the last error message.
555
 *
556
557
 * Return a string with the last error message produced by \e libdvdcss.
 * Useful to conveniently format error messages in external applications.
558
 */
559
LIBDVDCSS_EXPORT char * dvdcss_error ( dvdcss_t dvdcss )
Sam Hocevar's avatar
 
Sam Hocevar committed
560
561
562
563
{
    return dvdcss->psz_error;
}

564
565
566
/**
 * \brief Seek in the disc and change the current key if requested.
 *
567
568
 * \param dvdcss a \e libdvdcss instance
 * \param i_blocks an absolute block offset to seek to
569
 * \param i_flags #DVDCSS_NOFLAGS, optionally ORed with one of #DVDCSS_SEEK_KEY
570
571
 *        or #DVDCSS_SEEK_MPEG
 * \return the new position in blocks or a negative value in case an error
572
573
574
575
576
577
578
 *         happened.
 *
 * This function seeks to the requested position, in logical blocks.
 *
 * You typically set \p i_flags to #DVDCSS_NOFLAGS when seeking in a .IFO.
 *
 * If #DVDCSS_SEEK_MPEG is specified in \p i_flags and if \e libdvdcss finds it
579
 * reasonable to do so (i.e., if the dvdcss method is not "title"), the current
580
 * title key will be checked and a new one will be calculated if necessary.
581
 * This flag is typically used when reading data from a .VOB file.
582
 *
583
 * If #DVDCSS_SEEK_KEY is specified, the title key will always be checked,
584
 * even with the "title" method. This flag is typically used when seeking
585
586
 * in a new title.
 */
587
LIBDVDCSS_EXPORT int dvdcss_seek ( dvdcss_t dvdcss, int i_blocks, int i_flags )
Sam Hocevar's avatar
 
Sam Hocevar committed
588
589
590
{
    /* title cracking method is too slow to be used at each seek */
    if( ( ( i_flags & DVDCSS_SEEK_MPEG )
591
             && ( dvdcss->i_method != DVDCSS_METHOD_TITLE ) )
Sam Hocevar's avatar
 
Sam Hocevar committed
592
593
594
       || ( i_flags & DVDCSS_SEEK_KEY ) )
    {
        /* check the title key */
595
        if( dvdcss_title( dvdcss, i_blocks ) )
Sam Hocevar's avatar
 
Sam Hocevar committed
596
597
598
599
600
        {
            return -1;
        }
    }

601
    return dvdcss->pf_seek( dvdcss, i_blocks );
Sam Hocevar's avatar
 
Sam Hocevar committed
602
603
}

604
605
606
/**
 * \brief Read from the disc and decrypt data if requested.
 *
607
608
609
610
611
 * \param dvdcss a \e libdvdcss instance
 * \param p_buffer a buffer that will contain the data read from the disc
 * \param i_blocks the amount of blocks to read
 * \param i_flags #DVDCSS_NOFLAGS, optionally ORed with #DVDCSS_READ_DECRYPT
 * \return the amount of blocks read or a negative value in case an
612
613
 *         error happened.
 *
614
 * Read \p i_blocks logical blocks from the DVD.
615
616
617
618
619
620
621
 *
 * You typically set \p i_flags to #DVDCSS_NOFLAGS when reading data from a
 * .IFO file on the DVD.
 *
 * If #DVDCSS_READ_DECRYPT is specified in \p i_flags, dvdcss_read() will
 * automatically decrypt scrambled sectors. This flag is typically used when
 * reading data from a .VOB file on the DVD. It has no effect on unscrambled
622
 * discs or unscrambled sectors and can be safely used on those.
623
624
 *
 * \warning dvdcss_read() expects to be able to write \p i_blocks *
625
 *          #DVDCSS_BLOCK_SIZE bytes into \p p_buffer.
626
 */
627
LIBDVDCSS_EXPORT int dvdcss_read ( dvdcss_t dvdcss, void *p_buffer,
628
629
                                          int i_blocks,
                                          int i_flags )
Sam Hocevar's avatar
 
Sam Hocevar committed
630
{
631
    uint8_t *_p_buffer = p_buffer;
Sam Hocevar's avatar
 
Sam Hocevar committed
632
633
    int i_ret, i_index;

634
    i_ret = dvdcss->pf_read( dvdcss, _p_buffer, i_blocks );
Sam Hocevar's avatar
 
Sam Hocevar committed
635
636

    if( i_ret <= 0
637
         || !dvdcss->b_scrambled
Sam Hocevar's avatar
 
Sam Hocevar committed
638
639
640
641
642
         || !(i_flags & DVDCSS_READ_DECRYPT) )
    {
        return i_ret;
    }

643
    if( ! memcmp( dvdcss->css.p_title_key, "\0\0\0\0\0", 5 ) )
Sam Hocevar's avatar
 
Sam Hocevar committed
644
    {
645
        /* For what we believe is an unencrypted title,
Sam Hocevar's avatar
Sam Hocevar committed
646
         * check that there are no encrypted blocks */
Sam Hocevar's avatar
 
Sam Hocevar committed
647
648
        for( i_index = i_ret; i_index; i_index-- )
        {
649
            if( _p_buffer[0x14] & 0x30 )
Sam Hocevar's avatar
 
Sam Hocevar committed
650
            {
651
                print_error( dvdcss, "no key but found encrypted block" );
Sam Hocevar's avatar
 
Sam Hocevar committed
652
653
                /* Only return the initial range of unscrambled blocks? */
                /* or fail completely? return 0; */
Sam Hocevar's avatar
Sam Hocevar committed
654
                break;
Sam Hocevar's avatar
 
Sam Hocevar committed
655
            }
656
            _p_buffer = _p_buffer + DVDCSS_BLOCK_SIZE;
Sam Hocevar's avatar
 
Sam Hocevar committed
657
658
        }
    }
659
    else
Sam Hocevar's avatar
 
Sam Hocevar committed
660
    {
661
662
        /* Decrypt the blocks we managed to read */
        for( i_index = i_ret; i_index; i_index-- )
Sam Hocevar's avatar
Sam Hocevar committed
663
        {
664
665
666
            dvdcss_unscramble( dvdcss->css.p_title_key, _p_buffer );
            _p_buffer[0x14] &= 0x8f;
            _p_buffer = _p_buffer + DVDCSS_BLOCK_SIZE;
Sam Hocevar's avatar
Sam Hocevar committed
667
        }
Sam Hocevar's avatar
 
Sam Hocevar committed
668
    }
669

Sam Hocevar's avatar
 
Sam Hocevar committed
670
671
672
    return i_ret;
}

673
/**
674
 * \brief Read data from the disc into multiple buffers and decrypt data if
675
676
 *        requested.
 *
677
 * \param dvdcss a \e libdvdcss instance
678
 * \param p_iovec a pointer to an array of iovec structures that will contain
679
680
681
682
 *        the data read from the disc
 * \param i_blocks the amount of blocks to read
 * \param i_flags #DVDCSS_NOFLAGS, optionally ORed with #DVDCSS_READ_DECRYPT
 * \return the amount of blocks read or a negative value in case an
683
684
 *         error happened.
 *
685
 * Read \p i_blocks logical blocks from the DVD and write them
686
687
688
689
690
691
692
693
 * to an array of iovec structures.
 *
 * You typically set \p i_flags to #DVDCSS_NOFLAGS when reading data from a
 * .IFO file on the DVD.
 *
 * If #DVDCSS_READ_DECRYPT is specified in \p i_flags, dvdcss_readv() will
 * automatically decrypt scrambled sectors. This flag is typically used when
 * reading data from a .VOB file on the DVD. It has no effect on unscrambled
694
 * discs or unscrambled sectors and can be safely used on those.
695
696
 *
 * \warning dvdcss_readv() expects to be able to write \p i_blocks *
697
 *          #DVDCSS_BLOCK_SIZE bytes into the buffers pointed by \p p_iovec.
698
699
700
 *          Moreover, all iov_len members of the iovec structures should be
 *          multiples of #DVDCSS_BLOCK_SIZE.
 */
701
LIBDVDCSS_EXPORT int dvdcss_readv ( dvdcss_t dvdcss, void *p_iovec,
702
703
                                           int i_blocks,
                                           int i_flags )
Sam Hocevar's avatar
 
Sam Hocevar committed
704
{
705
    struct iovec *_p_iovec = p_iovec;
Sam Hocevar's avatar
 
Sam Hocevar committed
706
707
708
709
    int i_ret, i_index;
    void *iov_base;
    size_t iov_len;

710
    i_ret = dvdcss->pf_readv( dvdcss, _p_iovec, i_blocks );
Sam Hocevar's avatar
 
Sam Hocevar committed
711
712

    if( i_ret <= 0
713
         || !dvdcss->b_scrambled
Sam Hocevar's avatar
 
Sam Hocevar committed
714
715
716
717
718
719
         || !(i_flags & DVDCSS_READ_DECRYPT) )
    {
        return i_ret;
    }

    /* Initialize loop for decryption */
720
721
    iov_base = _p_iovec->iov_base;
    iov_len = _p_iovec->iov_len;
Sam Hocevar's avatar
 
Sam Hocevar committed
722
723
724
725
726
727
728
729
730
731
732
733

    /* Decrypt the blocks we managed to read */
    for( i_index = i_ret; i_index; i_index-- )
    {
        /* Check that iov_len is a multiple of 2048 */
        if( iov_len & 0x7ff )
        {
            return -1;
        }

        while( iov_len == 0 )
        {
734
735
736
            _p_iovec++;
            iov_base = _p_iovec->iov_base;
            iov_len = _p_iovec->iov_len;
Sam Hocevar's avatar
 
Sam Hocevar committed
737
738
        }

739
        dvdcss_unscramble( dvdcss->css.p_title_key, iov_base );
740
        ((uint8_t*)iov_base)[0x14] &= 0x8f;
Sam Hocevar's avatar
 
Sam Hocevar committed
741

742
        iov_base = (uint8_t*)iov_base + DVDCSS_BLOCK_SIZE;
743
        iov_len -= DVDCSS_BLOCK_SIZE;
Sam Hocevar's avatar
 
Sam Hocevar committed
744
745
746
747
748
    }

    return i_ret;
}

749
/**
750
 * \brief Clean up library state and structures.
751
 *
752
 * \param dvdcss a \e libdvdcss instance
753
754
 * \return zero in case of success, a negative value otherwise.
 *
755
756
 * Close the DVD device and free all the memory allocated by \e libdvdcss.
 * On return, the #dvdcss_t is invalidated and may not be used again.
757
 */
758
LIBDVDCSS_EXPORT int dvdcss_close ( dvdcss_t dvdcss )
Sam Hocevar's avatar
 
Sam Hocevar committed
759
760
761
762
763
764
765
766
767
768
769
770
771
{
    dvd_title_t *p_title;
    int i_ret;

    /* Free our list of keys */
    p_title = dvdcss->p_titles;
    while( p_title )
    {
        dvd_title_t *p_tmptitle = p_title->p_next;
        free( p_title );
        p_title = p_tmptitle;
    }

772
    i_ret = dvdcss_close_device( dvdcss );
Sam Hocevar's avatar
 
Sam Hocevar committed
773
774
775
776
777
778

    if( i_ret < 0 )
    {
        return i_ret;
    }

779
    free( dvdcss->psz_device );
Sam Hocevar's avatar
 
Sam Hocevar committed
780
781
782
783
784
    free( dvdcss );

    return 0;
}

785
/**
786
 * \brief Detect whether or not a DVD is scrambled
787
788
789
790
791
792
793
794
 *
 * \param dvdcss a \e libdvdcss instance.
 * \return 1 if the DVD is scrambled, 0 otherwise.
 */
LIBDVDCSS_EXPORT int dvdcss_is_scrambled ( dvdcss_t dvdcss )
{
    return dvdcss->b_scrambled;
}