1 /* libdvdcss.c: DVD reading library.
3 * Authors: Stéphane Borel <stef@via.ecp.fr>
4 * Sam Hocevar <sam@zoy.org>
5 * Håkan Hjort <d95hjort@dtek.chalmers.se>
7 * Copyright (C) 1998-2008 VideoLAN
10 * This library is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this library; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * \mainpage libdvdcss developer documentation
28 * \section intro Introduction
30 * \e libdvdcss is a simple library designed for accessing DVDs like a block
31 * device without having to bother about the decryption. The important features
33 * \li portability: currently supported platforms are GNU/Linux, FreeBSD,
34 * NetBSD, OpenBSD, BSD/OS, BeOS, Windows 95/98, Windows NT/2000, MacOS X,
35 * Solaris, HP-UX and OS/2.
36 * \li adaptability: unlike most similar projects, libdvdcss doesn't require
37 * the region of your drive to be set and will try its best to read from
38 * the disc even in the case of a region mismatch.
39 * \li simplicity: a DVD player can be built around the \e libdvdcss API using
40 * no more than 4 or 5 library calls.
42 * \e libdvdcss is free software, released under the General Public License.
43 * This ensures that \e libdvdcss remains free and used only with free
46 * \section api The libdvdcss API
48 * The complete \e libdvdcss programming interface is documented in the
51 * \section env Environment variables
53 * Some environment variables can be used to change the behaviour of
54 * \e libdvdcss without having to modify the program which uses it. These
57 * \li \b DVDCSS_VERBOSE: sets the verbosity level.
58 * - \c 0 outputs no messages at all.
59 * - \c 1 outputs error messages to stderr.
60 * - \c 2 outputs error messages and debug messages to stderr.
62 * \li \b DVDCSS_METHOD: sets the authentication and decryption method
63 * that \e libdvdcss will use to read scrambled discs. Can be one
64 * of \c title, \c key or \c disc.
65 * - \c key is the default method. \e libdvdcss will use a set of
66 * calculated player keys to try and get the disc key. This can fail
67 * if the drive does not recognize any of the player keys.
68 * - \c disc is a fallback method when \c key has failed. Instead of
69 * using player keys, \e libdvdcss will crack the disc key using
70 * a brute force algorithm. This process is CPU intensive and requires
71 * 64 MB of memory to store temporary data.
72 * - \c title is the fallback when all other methods have failed. It does
73 * not rely on a key exchange with the DVD drive, but rather uses a
74 * crypto attack to guess the title key. On rare cases this may fail
75 * because there is not enough encrypted data on the disc to perform
76 * a statistical attack, but in the other hand it is the only way to
77 * decrypt a DVD stored on a hard disc, or a DVD with the wrong region
80 * \li \b DVDCSS_RAW_DEVICE: specify the raw device to use. Exact usage will
81 * depend on your operating system, the Linux utility to set up raw devices
82 * is \c raw(8) for instance. Please note that on most operating systems,
83 * using a raw device requires highly aligned buffers: Linux requires a
84 * 2048 bytes alignment (which is the size of a DVD sector).
86 * \li \b DVDCSS_CACHE: specify a directory in which to store title key
87 * values. This will speed up descrambling of DVDs which are in the
88 * cache. The DVDCSS_CACHE directory is created if it does not exist,
89 * and a subdirectory is created named after the DVD's title or
90 * manufacturing date. If DVDCSS_CACHE is not set or is empty, \e libdvdcss
91 * will use the default value which is "${HOME}/.dvdcss/" under Unix and
92 * "C:\Documents and Settings\$USER\Application Data\dvdcss\" under Win32.
93 * The special value "off" disables caching.
104 #include <sys/types.h>
105 #include <sys/stat.h>
106 #ifdef HAVE_SYS_PARAM_H
107 # include <sys/param.h>
127 #include "dvdcss/dvdcss.h"
131 #include "libdvdcss.h"
136 * \brief Symbol for version checks.
138 * The name of this symbol contains the library major number, which makes it
139 * easy to check which \e libdvdcss development headers are installed on the
140 * system with tools such as autoconf.
142 * The variable itself contains the exact version number of the library,
143 * which can be useful for specific feature needs.
145 char * dvdcss_interface_2
= VERSION
;
148 * \brief Open a DVD device or directory and return a dvdcss instance.
150 * \param psz_target a string containing the target name, for instance
151 * "/dev/hdc" or "E:".
152 * \return a handle to a dvdcss instance or NULL on error.
154 * Initialize the \e libdvdcss library and open the requested DVD device or
155 * directory. \e libdvdcss checks whether ioctls can be performed on the disc,
156 * and when possible, the disc key is retrieved.
158 * dvdcss_open() returns a handle to be used for all subsequent \e libdvdcss
159 * calls. If an error occurred, NULL is returned.
161 LIBDVDCSS_EXPORT dvdcss_t
dvdcss_open ( char *psz_target
)
163 char psz_buffer
[PATH_MAX
];
166 char *psz_method
= getenv( "DVDCSS_METHOD" );
167 char *psz_verbose
= getenv( "DVDCSS_VERBOSE" );
168 char *psz_cache
= getenv( "DVDCSS_CACHE" );
169 #if !defined(WIN32) && !defined(SYS_OS2)
170 char *psz_raw_device
= getenv( "DVDCSS_RAW_DEVICE" );
176 * Allocate the library structure
178 dvdcss
= malloc( sizeof( struct dvdcss_s
) );
185 * Initialize structure with default values
187 #if !defined(WIN32) && !defined(SYS_OS2)
188 dvdcss
->i_raw_fd
= -1;
190 dvdcss
->p_titles
= NULL
;
191 dvdcss
->psz_device
= (char *)strdup( psz_target
);
192 dvdcss
->psz_error
= "no error";
193 dvdcss
->i_method
= DVDCSS_METHOD_KEY
;
194 dvdcss
->psz_cachefile
[0] = '\0';
196 dvdcss
->b_errors
= 0;
199 * Find verbosity from DVDCSS_VERBOSE environment variable
201 if( psz_verbose
!= NULL
)
203 int i
= atoi( psz_verbose
);
205 if( i
>= 2 ) dvdcss
->b_debug
= i
;
206 if( i
>= 1 ) dvdcss
->b_errors
= 1;
210 * Find method from DVDCSS_METHOD environment variable
212 if( psz_method
!= NULL
)
214 if( !strncmp( psz_method
, "key", 4 ) )
216 dvdcss
->i_method
= DVDCSS_METHOD_KEY
;
218 else if( !strncmp( psz_method
, "disc", 5 ) )
220 dvdcss
->i_method
= DVDCSS_METHOD_DISC
;
222 else if( !strncmp( psz_method
, "title", 5 ) )
224 dvdcss
->i_method
= DVDCSS_METHOD_TITLE
;
228 print_error( dvdcss
, "unknown decrypt method, please choose "
229 "from 'title', 'key' or 'disc'" );
230 free( dvdcss
->psz_device
);
237 * If DVDCSS_CACHE was not set, try to guess a default value
239 if( psz_cache
== NULL
|| psz_cache
[0] == '\0' )
242 typedef HRESULT( WINAPI
*SHGETFOLDERPATH
)
243 ( HWND
, int, HANDLE
, DWORD
, LPTSTR
);
245 # define CSIDL_FLAG_CREATE 0x8000
246 # define CSIDL_APPDATA 0x1A
247 # define SHGFP_TYPE_CURRENT 0
249 char psz_home
[MAX_PATH
];
251 SHGETFOLDERPATH p_getpath
;
255 /* Load the shfolder dll to retrieve SHGetFolderPath */
256 p_dll
= LoadLibrary( "shfolder.dll" );
259 p_getpath
= (void*)GetProcAddress( p_dll
, "SHGetFolderPathA" );
262 /* Get the "Application Data" folder for the current user */
263 if( p_getpath( NULL
, CSIDL_APPDATA
| CSIDL_FLAG_CREATE
,
264 NULL
, SHGFP_TYPE_CURRENT
, psz_home
) == S_OK
)
266 FreeLibrary( p_dll
);
273 FreeLibrary( p_dll
);
277 * C:\Documents and Settings\$USER\Application Data\dvdcss\ */
280 snprintf( psz_buffer
, PATH_MAX
, "%s/dvdcss", psz_home
);
281 psz_buffer
[PATH_MAX
-1] = '\0';
282 psz_cache
= psz_buffer
;
285 char *psz_home
= NULL
;
287 struct passwd
*p_pwd
;
289 /* Try looking in password file for home dir. */
290 p_pwd
= getpwuid(getuid());
293 psz_home
= p_pwd
->pw_dir
;
297 if( psz_home
== NULL
)
299 psz_home
= getenv( "HOME" );
301 if( psz_home
== NULL
)
303 psz_home
= getenv( "USERPROFILE" );
306 /* Cache our keys in ${HOME}/.dvdcss/ */
312 if( *psz_home
== '/' || *psz_home
== '\\')
314 char *psz_unixroot
= getenv("UNIXROOT");
318 psz_unixroot
[1] == ':' &&
319 psz_unixroot
[2] == '\0')
321 strcpy( psz_buffer
, psz_unixroot
);
326 snprintf( psz_buffer
+ home_pos
, PATH_MAX
- home_pos
,
327 "%s/.dvdcss", psz_home
);
328 psz_buffer
[PATH_MAX
-1] = '\0';
329 psz_cache
= psz_buffer
;
335 * Find cache dir from the DVDCSS_CACHE environment variable
337 if( psz_cache
!= NULL
)
339 if( psz_cache
[0] == '\0' || !strcmp( psz_cache
, "off" ) )
343 /* Check that we can add the ID directory and the block filename */
344 else if( strlen( psz_cache
) + 1 + 32 + 1 + (KEY_SIZE
* 2) + 10 + 1
347 print_error( dvdcss
, "cache directory name is too long" );
355 _dvdcss_check( dvdcss
);
356 i_ret
= _dvdcss_open( dvdcss
);
359 free( dvdcss
->psz_device
);
364 dvdcss
->b_scrambled
= 1; /* Assume the worst */
365 dvdcss
->b_ioctls
= _dvdcss_use_ioctls( dvdcss
);
367 if( dvdcss
->b_ioctls
)
369 _dvdcss_test( dvdcss
);
372 /* If disc is CSS protected and the ioctls work, authenticate the drive */
373 if( dvdcss
->b_scrambled
&& dvdcss
->b_ioctls
)
375 i_ret
= _dvdcss_disckey( dvdcss
);
379 print_debug( dvdcss
, "could not get disc key" );
384 memset( dvdcss
->css
.p_disc_key
, 0, KEY_SIZE
);
387 /* If the cache is enabled, write the cache directory tag */
390 char *psz_tag
= "Signature: 8a477f597d28d172789f06886806bc55\r\n"
391 "# This file is a cache directory tag created by libdvdcss.\r\n"
392 "# For information about cache directory tags, see:\r\n"
393 "# http://www.brynosaurus.com/cachedir/\r\n";
394 char psz_tagfile
[PATH_MAX
+ 1 + 12 + 1];
397 sprintf( psz_tagfile
, "%s/CACHEDIR.TAG", psz_cache
);
398 i_fd
= open( psz_tagfile
, O_RDWR
|O_CREAT
, 0644 );
401 write( i_fd
, psz_tag
, strlen(psz_tag
) );
406 /* If the cache is enabled, extract a unique disc ID */
409 uint8_t p_sector
[DVDCSS_BLOCK_SIZE
];
410 char psz_key
[1 + KEY_SIZE
* 2 + 1];
415 /* We read sector 0. If it starts with 0x000001ba (BE), we are
416 * reading a VOB file, and we should not cache anything. */
418 i_ret
= dvdcss
->pf_seek( dvdcss
, 0 );
424 i_ret
= dvdcss
->pf_read( dvdcss
, p_sector
, 1 );
430 if( p_sector
[0] == 0x00 && p_sector
[1] == 0x00
431 && p_sector
[2] == 0x01 && p_sector
[3] == 0xba )
436 /* The data we are looking for is at sector 16 (32768 bytes):
437 * - offset 40: disc title (32 uppercase chars)
438 * - offset 813: manufacturing date + serial no (16 digits) */
440 i_ret
= dvdcss
->pf_seek( dvdcss
, 16 );
446 i_ret
= dvdcss
->pf_read( dvdcss
, p_sector
, 1 );
452 /* Get the disc title */
453 psz_title
= (char *)p_sector
+ 40;
454 psz_title
[32] = '\0';
456 for( i
= 0 ; i
< 32 ; i
++ )
458 if( psz_title
[i
] <= ' ' )
463 else if( psz_title
[i
] == '/' || psz_title
[i
] == '\\' )
469 /* Get the date + serial */
470 psz_serial
= p_sector
+ 813;
471 psz_serial
[16] = '\0';
473 /* Check that all characters are digits, otherwise convert. */
474 for( i
= 0 ; i
< 16 ; i
++ )
476 if( psz_serial
[i
] < '0' || psz_serial
[i
] > '9' )
478 char psz_tmp
[16 + 1];
480 "%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x",
481 psz_serial
[0], psz_serial
[1], psz_serial
[2],
482 psz_serial
[3], psz_serial
[4], psz_serial
[5],
483 psz_serial
[6], psz_serial
[7] );
484 memcpy( psz_serial
, psz_tmp
, 16 );
489 /* Get disk key, since some discs have got same title, manufacturing
490 * date and serial number, but different keys */
491 if( dvdcss
->b_scrambled
)
494 for( i
= 0; i
< KEY_SIZE
; i
++ )
496 sprintf( &psz_key
[1+i
*2], "%.2x", dvdcss
->css
.p_disc_key
[i
] );
498 psz_key
[1 + KEY_SIZE
* 2] = '\0';
505 /* We have a disc name or ID, we can create the cache dir */
506 i
= sprintf( dvdcss
->psz_cachefile
, "%s", psz_cache
);
507 #if !defined( WIN32 ) || defined( SYS_CYGWIN )
508 i_ret
= mkdir( dvdcss
->psz_cachefile
, 0755 );
510 i_ret
= mkdir( dvdcss
->psz_cachefile
);
512 if( i_ret
< 0 && errno
!= EEXIST
)
514 print_error( dvdcss
, "failed creating cache directory" );
515 dvdcss
->psz_cachefile
[0] = '\0';
519 i
+= sprintf( dvdcss
->psz_cachefile
+ i
, "/%s-%s%s", psz_title
,
520 psz_serial
, psz_key
);
521 #if !defined( WIN32 ) || defined( SYS_CYGWIN )
522 i_ret
= mkdir( dvdcss
->psz_cachefile
, 0755 );
524 i_ret
= mkdir( dvdcss
->psz_cachefile
);
526 if( i_ret
< 0 && errno
!= EEXIST
)
528 print_error( dvdcss
, "failed creating cache subdirectory" );
529 dvdcss
->psz_cachefile
[0] = '\0';
532 i
+= sprintf( dvdcss
->psz_cachefile
+ i
, "/");
534 /* Pointer to the filename we will use. */
535 dvdcss
->psz_block
= dvdcss
->psz_cachefile
+ i
;
537 print_debug( dvdcss
, "using CSS key cache dir: %s",
538 dvdcss
->psz_cachefile
);
542 #if !defined(WIN32) && !defined(SYS_OS2)
543 if( psz_raw_device
!= NULL
)
545 _dvdcss_raw_open( dvdcss
, psz_raw_device
);
549 /* Seek at the beginning, just for safety. */
550 dvdcss
->pf_seek( dvdcss
, 0 );
556 * \brief Return a string containing the latest error that occurred in the
557 * given \e libdvdcss instance.
559 * \param dvdcss a \e libdvdcss instance.
560 * \return a null-terminated string containing the latest error message.
562 * This function returns a constant string containing the latest error that
563 * occurred in \e libdvdcss. It can be used to format error messages at your
564 * convenience in your application.
566 LIBDVDCSS_EXPORT
char * dvdcss_error ( dvdcss_t dvdcss
)
568 return dvdcss
->psz_error
;
572 * \brief Seek in the disc and change the current key if requested.
574 * \param dvdcss a \e libdvdcss instance.
575 * \param i_blocks an absolute block offset to seek to.
576 * \param i_flags #DVDCSS_NOFLAGS, optionally ored with one of #DVDCSS_SEEK_KEY
577 * or #DVDCSS_SEEK_MPEG.
578 * \return the new position in blocks, or a negative value in case an error
581 * This function seeks to the requested position, in logical blocks.
583 * You typically set \p i_flags to #DVDCSS_NOFLAGS when seeking in a .IFO.
585 * If #DVDCSS_SEEK_MPEG is specified in \p i_flags and if \e libdvdcss finds it
586 * reasonable to do so (ie, if the dvdcss method is not "title"), the current
587 * title key will be checked and a new one will be calculated if necessary.
588 * This flag is typically used when reading data from a VOB.
590 * If #DVDCSS_SEEK_KEY is specified, the title key will be always checked,
591 * even with the "title" method. This is equivalent to using the now
592 * deprecated dvdcss_title() call. This flag is typically used when seeking
595 LIBDVDCSS_EXPORT
int dvdcss_seek ( dvdcss_t dvdcss
, int i_blocks
, int i_flags
)
597 /* title cracking method is too slow to be used at each seek */
598 if( ( ( i_flags
& DVDCSS_SEEK_MPEG
)
599 && ( dvdcss
->i_method
!= DVDCSS_METHOD_TITLE
) )
600 || ( i_flags
& DVDCSS_SEEK_KEY
) )
602 /* check the title key */
603 if( _dvdcss_title( dvdcss
, i_blocks
) )
609 return dvdcss
->pf_seek( dvdcss
, i_blocks
);
613 * \brief Read from the disc and decrypt data if requested.
615 * \param dvdcss a \e libdvdcss instance.
616 * \param p_buffer a buffer that will contain the data read from the disc.
617 * \param i_blocks the amount of blocks to read.
618 * \param i_flags #DVDCSS_NOFLAGS, optionally ored with #DVDCSS_READ_DECRYPT.
619 * \return the amount of blocks read, or a negative value in case an
622 * This function reads \p i_blocks logical blocks from the DVD.
624 * You typically set \p i_flags to #DVDCSS_NOFLAGS when reading data from a
625 * .IFO file on the DVD.
627 * If #DVDCSS_READ_DECRYPT is specified in \p i_flags, dvdcss_read() will
628 * automatically decrypt scrambled sectors. This flag is typically used when
629 * reading data from a .VOB file on the DVD. It has no effect on unscrambled
630 * discs or unscrambled sectors, and can be safely used on those.
632 * \warning dvdcss_read() expects to be able to write \p i_blocks *
633 * #DVDCSS_BLOCK_SIZE bytes in \p p_buffer.
635 LIBDVDCSS_EXPORT
int dvdcss_read ( dvdcss_t dvdcss
, void *p_buffer
,
641 i_ret
= dvdcss
->pf_read( dvdcss
, p_buffer
, i_blocks
);
644 || !dvdcss
->b_scrambled
645 || !(i_flags
& DVDCSS_READ_DECRYPT
) )
650 if( ! memcmp( dvdcss
->css
.p_title_key
, "\0\0\0\0\0", 5 ) )
652 /* For what we believe is an unencrypted title,
653 * check that there are no encrypted blocks */
654 for( i_index
= i_ret
; i_index
; i_index
-- )
656 if( ((uint8_t*)p_buffer
)[0x14] & 0x30 )
658 print_error( dvdcss
, "no key but found encrypted block" );
659 /* Only return the initial range of unscrambled blocks? */
660 /* or fail completely? return 0; */
663 p_buffer
= (void *) ((uint8_t *)p_buffer
+ DVDCSS_BLOCK_SIZE
);
668 /* Decrypt the blocks we managed to read */
669 for( i_index
= i_ret
; i_index
; i_index
-- )
671 _dvdcss_unscramble( dvdcss
->css
.p_title_key
, p_buffer
);
672 ((uint8_t*)p_buffer
)[0x14] &= 0x8f;
673 p_buffer
= (void *) ((uint8_t *)p_buffer
+ DVDCSS_BLOCK_SIZE
);
681 * \brief Read from the disc into multiple buffers and decrypt data if
684 * \param dvdcss a \e libdvdcss instance.
685 * \param p_iovec a pointer to an array of iovec structures that will contain
686 * the data read from the disc.
687 * \param i_blocks the amount of blocks to read.
688 * \param i_flags #DVDCSS_NOFLAGS, optionally ored with #DVDCSS_READ_DECRYPT.
689 * \return the amount of blocks read, or a negative value in case an
692 * This function reads \p i_blocks logical blocks from the DVD and writes them
693 * to an array of iovec structures.
695 * You typically set \p i_flags to #DVDCSS_NOFLAGS when reading data from a
696 * .IFO file on the DVD.
698 * If #DVDCSS_READ_DECRYPT is specified in \p i_flags, dvdcss_readv() will
699 * automatically decrypt scrambled sectors. This flag is typically used when
700 * reading data from a .VOB file on the DVD. It has no effect on unscrambled
701 * discs or unscrambled sectors, and can be safely used on those.
703 * \warning dvdcss_readv() expects to be able to write \p i_blocks *
704 * #DVDCSS_BLOCK_SIZE bytes in the buffers pointed by \p p_iovec.
705 * Moreover, all iov_len members of the iovec structures should be
706 * multiples of #DVDCSS_BLOCK_SIZE.
708 LIBDVDCSS_EXPORT
int dvdcss_readv ( dvdcss_t dvdcss
, void *p_iovec
,
712 struct iovec
*_p_iovec
= (struct iovec
*)p_iovec
;
717 i_ret
= dvdcss
->pf_readv( dvdcss
, _p_iovec
, i_blocks
);
720 || !dvdcss
->b_scrambled
721 || !(i_flags
& DVDCSS_READ_DECRYPT
) )
726 /* Initialize loop for decryption */
727 iov_base
= _p_iovec
->iov_base
;
728 iov_len
= _p_iovec
->iov_len
;
730 /* Decrypt the blocks we managed to read */
731 for( i_index
= i_ret
; i_index
; i_index
-- )
733 /* Check that iov_len is a multiple of 2048 */
734 if( iov_len
& 0x7ff )
739 while( iov_len
== 0 )
742 iov_base
= _p_iovec
->iov_base
;
743 iov_len
= _p_iovec
->iov_len
;
746 _dvdcss_unscramble( dvdcss
->css
.p_title_key
, iov_base
);
747 ((uint8_t*)iov_base
)[0x14] &= 0x8f;
749 iov_base
= (void *) ((uint8_t*)iov_base
+ DVDCSS_BLOCK_SIZE
);
750 iov_len
-= DVDCSS_BLOCK_SIZE
;
757 * \brief Close the DVD and clean up the library.
759 * \param dvdcss a \e libdvdcss instance.
760 * \return zero in case of success, a negative value otherwise.
762 * This function closes the DVD device and frees all the memory allocated
763 * by \e libdvdcss. On return, the #dvdcss_t is invalidated and may not be
766 LIBDVDCSS_EXPORT
int dvdcss_close ( dvdcss_t dvdcss
)
768 dvd_title_t
*p_title
;
771 /* Free our list of keys */
772 p_title
= dvdcss
->p_titles
;
775 dvd_title_t
*p_tmptitle
= p_title
->p_next
;
777 p_title
= p_tmptitle
;
780 i_ret
= _dvdcss_close( dvdcss
);
787 free( dvdcss
->psz_device
);
794 * Deprecated. See dvdcss_seek().
797 LIBDVDCSS_EXPORT
int dvdcss_title ( dvdcss_t dvdcss
, int i_block
)
799 return _dvdcss_title( dvdcss
, i_block
);
803 * \brief Return 1 if the DVD is scrambled, 0 otherwise.
805 * \param dvdcss a \e libdvdcss instance.
806 * \return 1 if the DVD is scrambled, 0 otherwise.
808 * This function returns whether the DVD is scrambled.
810 LIBDVDCSS_EXPORT
int dvdcss_is_scrambled ( dvdcss_t dvdcss
)
812 return dvdcss
->b_scrambled
;