├── .gitignore ├── README-gdmenu.txt ├── README.md ├── data ├── 1ST_READ.BIN └── ip.bin ├── dc-card-maker.sh ├── ini └── GDEMU.ini ├── licenses ├── LICENSE-dc-card-maker-script ├── LICENSE-gditools └── LICENSE-iso9660 └── tools ├── gditools.py └── iso9660.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Various build artifacts and temporary files 2 | *.pyc 3 | LIST.INI* 4 | gdmenu.cdi 5 | gdmenu.iso 6 | 7 | # binary tools 8 | tools/cdi4dc 9 | tools/cdirip 10 | -------------------------------------------------------------------------------- /README-gdmenu.txt: -------------------------------------------------------------------------------- 1 |  _____ _____ 2 | / ____| __ \ 3 | | | __| | | |_ __ ___ ___ _ __ _ _ 4 | | | |_ | | | | '_ ` _ \ / _ \ '_ \| | | | 5 | | |__| | |__| | | | | | | __/ | | | |_| | 6 | \_____|_____/|_| |_| |_|\___|_| |_|\__,_| 7 | ============================================ 8 | Version : v0.6.0 9 | Date : August 24, 2016 10 | Author : neuroacid 11 | Contact : n3uroacid(at)gmail.com 12 | 13 | 14 | What's new in this version? 15 | ============================================ 16 | - Improved the overall responsiveness and browsing speed. 17 | - Implemented support for japanese_cake's custom bootROM v1.032 in the bootloader. 18 | - Implemented analog stick support for page scrolling and menu highlighting. 19 | - Implemented faster page scrolling using the left and right analog triggers. 20 | - Added an options menu to toggle the various patches on/off. 21 | - Added a system information menu with GDEMU firmware version and other specifics. 22 | - Added CodeBreaker disc image detection and prompt to select a game to load with it. 23 | - On-the-fly patching of CodeBreaker for it to read and boot disc images in MIL-CD format. 24 | - On-the-fly patching of CodeBreaker to make it compatible with japanese_cake's bootROM v1.032. 25 | - Other minor changes and fixes. 26 | 27 | 28 | About this software 29 | ============================================ 30 | GDmenu is an homebrew for the Sega Dreamcast to be used with the GDEMU ODE and to make its operation easier. 31 | For more information on the GDEMU ODE visit the following page: https://gdemu.wordpress.com/about 32 | 33 | The purpose of the software is to generate a list of games on the SD card and show it in an easy to use menu 34 | making it simple to select the game you want to play. Additionally it also includes some nice extra features. 35 | 36 | 37 | How to install 38 | ============================================ 39 | GDmenu software is very easy to set-up, the only requirement for correct operation is having the appropriate 40 | firmware update installed on your GDEMU. In case you are unsure which update version you might have currently 41 | just follow the steps below and after booting it will warn you if a firmware update is necessary. 42 | Get it from https://gdemu.wordpress.com/firmware/updating-gdemu and follow the instructions on that page. 43 | 44 | Follow these simple steps to set it up: 45 | - Upon extracting the GDmenu zip archive, copy the file GDEMU.ini and folder 01 to the root of your SD card. 46 | - In case folder 01 already exists in the root of the SD card remember to move the contents elsewhere first. 47 | - Eject the SD card from your reader, insert in your GDEMU SD slot and power-on your Dreamcast. 48 | - After booting the software, a loading screen will appear while the games list is being generated. 49 | - Finally, if everything went according to plan the menu is displayed, listing all the games on the SD card. 50 | 51 | 52 | How to use 53 | ============================================ 54 | - Up/Down on the D-pad or analog stick to browse through the list of games or highlight options. 55 | - (A) button to confirm/accept the highlighted selection be it to start a game or change settings. 56 | - (B) button to cancel selection or return from a menu. 57 | - (X) button to bring up the menu for selecting various options or view hardware information. 58 | - (Y) button to exit from the GDmenu software back to the BIOS system menu. 59 | 60 | 61 | Features 62 | ============================================ 63 | Region Free: 64 | - Boot games from any region without any additional hardware modifications! (see note *1) 65 | 66 | Force VGA: 67 | - Play games in VGA video mode which would otherwise need the VGA flag to be patched! (see note *2) 68 | 69 | In-Game Reset: 70 | - Reset your console without getting up for a manual reset, simply by holding A+B+X+Y+START on the controller 71 | while sitting at the game's main menu! 72 | 73 | Boot intro animation skip: 74 | - Toggle off the BIOS boot intro animation for a quicker boot time into your games! (see note *3) 75 | 76 | SEGA license screen skip: 77 | - Toggle off the SEGA license screen for a quicker boot time into your games! (see note *3) 78 | 79 | CodeBreaker detection: 80 | - Detects the CodeBreaker disc image and prompts you to select a game to load with it, no need to stand up to 81 | change disc images whenever you want to use cheat codes with your games! (see note *4) 82 | 83 | 84 | Notes 85 | ============================================ 86 | Note *1: 87 | - This skips the regional checks performed by the BIOS during boot (similar to what a region free BIOS does). 88 | However some games themselves can have additional protections but fortunately this also patches the console 89 | region to match the game, so as far as the game is concerned your console is always the appropriate region. 90 | For the system region patching to work properly, it is imperative that you do not make any modifications to 91 | the game's IP.BIN region flags, as patching the system region relies on those being in their original state. 92 | 93 | Note *2: 94 | - This skips the VGA flag check performed by the BIOS during boot, which in turn allows games that have proper 95 | VGA output support (but no VGA flag set in the AIP), to boot correctly while avoiding the following message 96 | from being shown: "This game doesn't support the AV cable currently connected..." 97 | However a small percentage of games lack the support the VGA video mode which means that in those cases this 98 | makes no difference and the game's binary has to be directly patched on case by case basis. 99 | 100 | Note *3: 101 | - At the moment, due to what seems to be problem specific to the GDEMU, most disc images in the MIL-CD format 102 | won't boot when skipping the BIOS boot intro animation. So for now, while the problem is being investigated 103 | toggling boot intro and Sega license off only has an effect on .GDI disc images (full GD-ROM dumps). 104 | 105 | Note *4: 106 | - For this to work correctly, the right version of the CodeBreaker has to be detected which means that some of 107 | the information present in its IP.BIN should match what is shown in the GDmenu info pane. 108 | So while in the menu with its entry highlighted the pane on the right should match the following information 109 | "DISC " 110 | "DATE 2000/06/27" 111 | "VERSION V1.000" 112 | Additionally the binary has to be called PELICAN.BIN and have the md5 hash: cc0b1e71a61587b0213fd5424b14eb22 113 | 114 | For the optimal usage of the software, it is essential to copy the GDEMU.ini file to the root of your SD card. 115 | So it should contain at least the following three lines inside: 116 | open_time = 150 117 | detect_time = 150 118 | reset_goto = 1 119 | 120 | First two lines guarantee quicker browsing speeds, especially when loading the cover images, the third line is 121 | necessary to return to the GDmenu after a reset (by pressing A+B+X+Y+START while in-game). 122 | 123 | 124 | Changelog 125 | ============================================ 126 | v0.5.2 (14/07/2015): 127 | - Implemented region free and VGA flag check patches for bootROM v1.004. 128 | 129 | v0.5.1 (14/06/2015): 130 | - Fixed an issue with the video mode on PAL systems when using RGB/Composite. 131 | 132 | v0.5.0 (01/06/2015): 133 | - Updated the internal bootloader. 134 | - Added region check patch (ignore checking of region flags). 135 | - Added VGA flag check patch (ignore checking of VGA flag). 136 | - Added in-game reset patch (reset back to GDmenu by holding A+B+X+Y+START while in-game). 137 | 138 | v0.4.0 (08/02/2015): 139 | - Increased games list maximum size to 999. 140 | - Fixed list scrolling de-sync issue that could happen on slower speed SD cards. 141 | - Removed wrap around from first to last game on the list (not supported anymore by firmware). 142 | 143 | v0.3.0 (17/10/2014): 144 | - Overall re-design and improvements to the menu GUI. 145 | - Now shows additional information about the selected disc image on the right. 146 | - Now displays the '0GDTEX.PVR' texture (cover image) when present on the disc. 147 | - Fixed a problem where disc images with a high number of tracks could cause a de-sync in the list. 148 | - Added workaround for disc images with no title on 'IP0000.BIN', parse volume descriptor instead. 149 | 150 | v0.2.0 (15/09/2014): 151 | - Now supports sending Up/Down inputs to the GDEMU via emulation API. 152 | - Now automatically parses and loads the list of games on the SD card upon booting. 153 | - Removed the VMU save/load functions as they are no longer useful. 154 | - Removed multi-list browsing as it's no longer necessary. 155 | - Added initial support to load the list of games from a .ini file. 156 | - Improved menu GUI with better font and rendering. 157 | - Other minor bug-fixes. 158 | 159 | v0.0.1 (23/08/2014): 160 | - Initial public release. 161 | 162 | 163 | Special Thanks 164 | ============================================ 165 | In no particular order: 166 | - Deunan for creating the GDEMU and the great work so far supporting it with firmware updates. 167 | 168 | - Dan Potter & Company for starting the KallistiOS project among all other contributions to get the Dreamcast 169 | homebrew scene started. 170 | 171 | - Marcus Comstedt for all his past contributions to the scene and in particular for the wealth of information 172 | about the Dreamcast hardware that is available to this day on his site. 173 | 174 | - Lawrence Sebald for being always very helpful and maintain the KallistiOS alive. 175 | 176 | - drk|Raziel & Company for creating the NullDC emulator which to this day is still a very helpful tool and in 177 | particular the debugger which is invaluable. 178 | 179 | - Lars Olsson for all the great work reversing the bootROM and hardware registers. 180 | 181 | - Japanese_cake for his cool custom bootROM which thanks to a very clever use of the beta bootstrap opens up 182 | a lot of possibilities for the future. 183 | 184 | - Nightbreed for the exhaustive work of testing the software to make sure everything works as intended. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Dreamcast GDMenu maker script for Linux 2 | ======================================= 3 | 4 | The `dc-card-maker.sh` is a simple bash script that allows to prepare an SD 5 | memory card to be used with GDEMU optical drive emulator for the Sega Dreamcast 6 | console and the GDMenu homebrew. The script extracts games from zip archives, 7 | puts them on an SD card in appropriately named directories and generates a 8 | GDMenu disc image with a pre-generated list of menu entries, which avoids 9 | scanning the SD card every time GDMenu is launched. 10 | 11 | **This script comes with no warranty of any kind, use at your own risk.** Read 12 | the "Usage" section carefully to understand what the script does before using 13 | it. I did my best to make the script safe and not cause any data loss *when 14 | used as intended*. That being said, **backup data on your SD card before using 15 | this script**. If anything goes wrong the script should terminate without 16 | causing any data loss, but potentially leaving mess in the target directory. 17 | This mess is recoverable but will require some scripting on your side (or a lot 18 | of manual work). 19 | 20 | 21 | Requirements 22 | ============ 23 | 24 | * `genisoimage` 25 | * `hexdump` 26 | * `sed` 27 | * `unzip` 28 | * `cdi4dc` 29 | * `cdirip` 30 | * Python 3 (to run `gditools.py` and `iso9660.py` in `tools/` directory) 31 | 32 | Script tests presence of `genisoimage`, `cdi4dc`, `cdirip`, and `unzip` at 33 | start. `sed` and `hexdump` should be available by default on all Linux 34 | distributions. 35 | 36 | 37 | A note on `cdi4dc` and `cdirip` 38 | ------------------------------- 39 | 40 | `cdi4dc` and `cdirip` usually don't come in distribution repositories and you 41 | likely need to build them from sources. Grab the [sources for 42 | `cdi4dc`](https://github.com/Kazade/img4dc) and [sources for 43 | `cdirip`](https://github.com/jozip/cdirip), compile them, and place the compiled 44 | binaries in the tools directory. If you already have these programs on your 45 | system you can either add a symlink to them in the `tools/` directory or edit 46 | the script to remove the `./tools/cdi4dc` and `./tools/cdirip` checks at the 47 | beginning and then use the system copies of `cdi4dc` and `cdirip` towards the 48 | end of the script. 49 | 50 | 51 | Usage 52 | ===== 53 | 54 | The `dc-card-maker.sh` script has to be invoked with three arguments 55 | 56 | ``` 57 | ./dc-card-maker.sh game_list.txt source_dir target_dir 58 | ``` 59 | 60 | where: 61 | 62 | * `game_list.txt` is a text file that contains a list of zip archives with 63 | games to place on the SD card, one archive per line. Games will be added to 64 | GDMenu in the order specified in the file, so you can arrange the order to 65 | your liking. The easiest way to generate the file for the first time is to 66 | have a single directory that contains the archives (see next bullet) and 67 | list its contents to a file (`ls source_dir > game_list.txt`). After each 68 | run the script places a copy of `game_list.txt` in the `target_dir` - this 69 | file can be later used to create an updated list when adding new games to 70 | the card. **IMPORTANT:** don't point this first argument to 71 | `target_dir/game_list.txt`. This will result in the script trying to read 72 | the file and at the same time deleting it and writing to it. This is a bad 73 | idea. Instead, copy the `target_dir/game_list.txt` somewhere and pass that 74 | copy as the first argument. 75 | 76 | * `source_dir` is a directory that contains ZIP archives specified in 77 | `game_list.txt` above. The script was designed with TOSEC archives in mind, 78 | but it should work with any archive that contains a GDI or CDI disc image, 79 | provided the files are **not placed in a subdirectory inside the archive**. 80 | The exact name of `*.gdi`/`*cdi` file is unimportant - the script takes care 81 | to rename it appropriately. 82 | 83 | * `target_dir` is the destination directory where the script will place the 84 | extracted games and the generated GDMenu image. This directory should be 85 | the root of you SD card, but you can also use a directory on your disk and 86 | only later copy the generated directories to an SD card. (I use this 87 | approach since having the target directory on an SSD is much faster - if 88 | anything goes wrong rerunning the script takes a lot less time.) Each game 89 | image is placed in a numbered directory ([as required by 90 | GDEMU](https://gdemu.wordpress.com/details/gdemu-details/)), with directory 91 | `01/` being reserved for the GDMenu image. Each game subdirectory, in 92 | addition to the GDI/CDI image, contains `archive.txt` file with the name of 93 | a ZIP archive from which the game was extracted. It is important that 94 | `archive.txt` files remain unchanged - otherwise updating the card will not 95 | work correctly. 96 | 97 | When using `dc-card-maker.sh` script for the first time use an empty 98 | `target_dir`. Once populated by the script the target directory can be further 99 | updated, allowing to add, remove, and reorder games without the need to extract 100 | and copy game archives again. All you need to do is update the list of games in 101 | `game_list.txt` file supplied as the first parameter to the script. You can add 102 | new archives to the list, as well as reorder and delete existing ones. If the 103 | game image is already present in the target directory it will be used, with no 104 | additional copying being done. Newly added games will be extracted from the 105 | archives and added to the target directory. 106 | 107 | **IMPORTANT** When updating the card all numbered directories are temporarily 108 | renamed to end with an underscore (`01` becomes `01_`, and so on). They are 109 | then renamed back, possibly with different names if the games were reordered or 110 | new games were added earlier in the list. Games that were removed from the list 111 | in `game_list.txt` are left in these temporary subdirectories. These 112 | directories are reported to the user when the script ends. At the very least 113 | the list will contain `01_` with a backup copy of previous GDMenu image. (Note 114 | that by now that image is probably outdated anyway if the list of games has been 115 | modified.) It is user's responsibility to remove these backup directories. The 116 | script will refuse to run if the target directory contains directories ending 117 | with an underscore. This is all done to minimise the risk of data loss due to 118 | user mistakes. 119 | 120 | 121 | Custom menu entry names 122 | ----------------------- 123 | 124 | On its first run the script extracts game names from the GDI/CDI images. 125 | Extracted name is placed in a `name.txt` file inside the game's directory on the 126 | SD card. You can edit these `name.txt` files to provide custom names to display 127 | in GDMenu. For example, you might want to change all names to be displayed 128 | using lowercase letters, but keep the first letter of each word capitalized. 129 | Here's an incantation that does that: 130 | 131 | ``` 132 | find target_dir -name "name.txt" -exec sed -i -e "s/[A-Z]/\L&/g; s/\b\(.\)/\u\1/g" {} \; 133 | ``` 134 | 135 | Once you edited `name.txt` files to your liking run the script again with the 136 | same parameters to generate an updated GDMenu image with new names. 137 | 138 | 139 | Contributing guidelines 140 | ======================= 141 | 142 | * make a ticket, ensure that your contribution is desired and will be accepted 143 | * update the documentation if needed 144 | * no tabs, spaces only 145 | * no trailing whitespaces 146 | * newline at end-of-file 147 | * send PRs or just fork the project and do whatever you want (well, whatever 148 | the license permits) 149 | 150 | 151 | Bundled software, credits, and licenses 152 | ======================================= 153 | 154 | `dc-card-maker.sh` is distributed under the terms of GPL2 license - see 155 | `licenses/LICENSE-dc-card-maker-script` file. 156 | 157 | This repo also contains the following additional software and data files created 158 | by other people: 159 | 160 | * `tools/iso9660.py` was written by Barney Gale and is distributed under the 161 | terms of MIT license. See `licenses/LICENSE-iso9660`. Original repository: 162 | . Ported to Python 3 by HaydenKow: 163 | 164 | 165 | * `tools/gditools.py` is taken from `gditools` library written by FamilyGuy, 166 | and is distributed under the terms of GPL3 license. See 167 | `licenses/LICENSE-gditools` file. Original repository: 168 | . Ported to Python 3 by 169 | HaydenKow: 170 | 171 | * `data/1ST_READ.BIN` contains a binary image of GDMenu written by neuroacid. 172 | Exact license unknown, but this binary has been released to the public by 173 | the author and is freely distributed on the internet. See 174 | `README-gdmenu.txt` for details. 175 | 176 | * `data/ip.bin` and `GDEMU.ini` are taken from GDEMU_SD written by MadSheep. 177 | 178 | 179 | Further reading 180 | =============== 181 | 182 | * [Structure of `ip.bin`](https://mc.pp.se/dc/ip0000.bin.html) 183 | * [GDEMU details](https://gdemu.wordpress.com/details/gdemu-details/) 184 | * [GDEMU operation](https://gdemu.wordpress.com/operation/gdemu-operation/) 185 | -------------------------------------------------------------------------------- /data/1ST_READ.BIN: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jstolarek/dc-card-maker-script/0f060c1c0e88626eecd6f2a5668f63fde75bf386/data/1ST_READ.BIN -------------------------------------------------------------------------------- /data/ip.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jstolarek/dc-card-maker-script/0f060c1c0e88626eecd6f2a5668f63fde75bf386/data/ip.bin -------------------------------------------------------------------------------- /dc-card-maker.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Dreamcast GDMenu maker script for Linux. Usage: 4 | # 5 | # dc-card-maker.sh game_list.txt source_dir target_dir 6 | # 7 | # See README.md for detailed instructions 8 | # 9 | # Copyright (C) 2020 Jan Stolarek 10 | # 11 | # This program is free software; you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation; either version 2 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License along 22 | # with this program; if not, write to the Free Software Foundation, Inc., 23 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 24 | 25 | # For error printing in red 26 | STARTRED="\e[31m" 27 | ENDRED="\e[0m" 28 | 29 | # Check for required commands 30 | command -v genisoimage >/dev/null 2>&1 || { 31 | echo -e "$STARTRED""This script requires genisoimage to be present in the system. Aborting script""$ENDRED" >&2 32 | exit 5 33 | } 34 | 35 | command -v ./tools/cdi4dc >/dev/null 2>&1 || { 36 | echo -e "$STARTRED""This script requires cdi4dc to be present in tools/ directory""$ENDRED" >&2 37 | echo -e "$STARTRED""See README for details. Aborting script""$ENDRED" >&2 38 | exit 6 39 | } 40 | 41 | command -v ./tools/cdirip >/dev/null 2>&1 || { 42 | echo -e "$STARTRED""This script requires cdirip to be present in tools/ directory""$ENDRED" >&2 43 | echo -e "$STARTRED""See README for details. Aborting script""$ENDRED" >&2 44 | exit 6 45 | } 46 | 47 | command -v unzip >/dev/null 2>&1 || { 48 | echo -e "$STARTRED""This script requires unzip to be present in the system. Aborting script""$ENDRED" >&2 49 | exit 7 50 | } 51 | 52 | # Process command line args 53 | if [ "$#" != 3 ]; then 54 | echo "Dreamcast SD card maker script (version 1.2.1)" 55 | echo "" 56 | echo "Usage: dc-card-maker.sh game_list.txt source_dir target_dir" 57 | exit 1; 58 | fi 59 | 60 | INPUT_FILE=$1 61 | SOURCE_DIR=$2 62 | TARGET_DIR=$3 63 | OUTPUT_FILE=$3/game_list.txt 64 | GDMENU_INI=ini/LIST.INI 65 | ARCHIVE_FILE=archive.txt 66 | NAME_FILE=name.txt # collides (coincides?) with MadSheep's Windows SD card maker 67 | 68 | # Basic sanity checks 69 | if [[ ! -f $INPUT_FILE ]]; then 70 | echo "Input file does not exist : $1" >&2 71 | exit 2; 72 | fi 73 | 74 | if [[ ! -d $SOURCE_DIR ]]; then 75 | echo "Source directory does not exist : $2" >&2 76 | exit 3; 77 | fi 78 | 79 | if [[ ! -d $TARGET_DIR ]]; then 80 | echo "Target directory does not exist : $3" >&2 81 | exit 4; 82 | fi 83 | 84 | # If there are any directories with names consisting of digits only and ending 85 | # with an underscore it means there are leftovers from previous script run. 86 | # Abort the script to avoid problems and potential data loss. 87 | LEFTOVER_DIRS=`find $TARGET_DIR -regextype sed -regex "$TARGET_DIR/*[0-9][0-9]*_"` 88 | if [[ ! -z $LEFTOVER_DIRS ]]; then 89 | echo -e "$STARTRED""Following directories from previous session found:""$ENDRED" >&2 90 | for DIR in $LEFTOVER_DIRS; do 91 | echo "$DIR" >&2 92 | done 93 | echo -e "$STARTRED""Aborting script. Remove these directories and run the script again""$ENDRED" >&2 94 | exit 95 | fi 96 | 97 | # If there are gdemu directories present in the destination derictory append 98 | # underscore to their names. 99 | TARGET_DIRS=`find $TARGET_DIR -regextype sed -regex "$TARGET_DIR/*[0-9][0-9]*"` 100 | if [[ ! -z $TARGET_DIRS ]]; then 101 | echo "Renaming target directories to avoid name clashes" 102 | for EXISTING_TARGET_DIR in $TARGET_DIRS; do 103 | echo "Renaming $EXISTING_TARGET_DIR to $EXISTING_TARGET_DIR""_" 104 | mv "$EXISTING_TARGET_DIR" "$EXISTING_TARGET_DIR"_ 105 | done 106 | # Treat gdmenu directory specialy 107 | if [[ -d "$TARGET_DIR/01_" ]]; then 108 | mv "$TARGET_DIR/01_" "$TARGET_DIR/gdmenu_old" 109 | fi 110 | fi 111 | 112 | # Initialize GDMenu ini file. 113 | if [[ -e $GDMENU_INI ]]; then 114 | echo "$GDMENU_INI exists, backing up as ${GDMENU_INI}.bak" 115 | mv "$GDMENU_INI" "$GDMENU_INI"".bak" 116 | fi 117 | # Values here are hardcoded since we know what the ip.bin contains. If ip.bin 118 | # ever gets updated these lines need to be updated accordingly 119 | echo "[GDMENU]" >> $GDMENU_INI 120 | echo "01.name=GDMenu" >> $GDMENU_INI 121 | echo "01.disc=1/1" >> $GDMENU_INI 122 | echo "01.vga=1" >> $GDMENU_INI 123 | echo "01.region=JUE" >> $GDMENU_INI 124 | echo "01.version=V0.6.0" >> $GDMENU_INI 125 | echo "01.date=20160812" >> $GDMENU_INI 126 | echo "" >> $GDMENU_INI 127 | 128 | # Initialize output game list file. 129 | if [[ -e $OUTPUT_FILE ]]; then 130 | echo "$OUTPUT_FILE exists, backing up as ${OUTPUT_FILE}.bak" 131 | mv "$OUTPUT_FILE" "$OUTPUT_FILE"".bak" 132 | fi 133 | 134 | # Temporary directory for extracting zip archives 135 | TMP_UNZIP_DIR=`mktemp -d -t dc-card-maker-XXXXX` 136 | echo "Created temporary directory for extracting archives: $TMP_UNZIP_DIR" 137 | 138 | # Directory 01 reserved for GDMenu, start game directories with 02 139 | INDEX=2 140 | 141 | 142 | while read GAME; do 143 | echo "Processing game \"$GAME\"" 144 | 145 | # Ensure that names of directories 1-9 start with a 0 146 | if [[ $INDEX -lt 10 ]]; then 147 | DIR_NAME=$(printf "%02d" $INDEX) 148 | else 149 | DIR_NAME="$INDEX" 150 | fi 151 | 152 | # Attempt to locate the game subdirectory in the target directory. If it's 153 | # already there just restore the game by renaming the temporary directory, 154 | # don't attempt to extract the game from an archive 155 | GAME_FOUND=false 156 | for EXISTING_GAME_DIR in `find $TARGET_DIR -regextype sed -regex "$TARGET_DIR/*[0-9][0-9]*_"`; do 157 | if [[ "$GAME" == "`cat $EXISTING_GAME_DIR/$ARCHIVE_FILE`" ]]; then 158 | echo "Game \"$GAME\" located in target directory, placing it in directory \"$DIR_NAME\"" 159 | mv "$EXISTING_GAME_DIR" "$TARGET_DIR/$DIR_NAME" 160 | (( INDEX++ )) 161 | echo "$GAME" >> "$OUTPUT_FILE" 162 | GAME_FOUND=true 163 | break # if game found don't iterate over remaining directories 164 | fi 165 | done 166 | 167 | # If game not found in target directory extract it from a zip archive 168 | if [[ $GAME_FOUND == false ]]; then 169 | GAME_ARCHIVE="$SOURCE_DIR/$GAME" 170 | GAME_TARGET_DIR="$TARGET_DIR/$DIR_NAME" 171 | GAME_TMP_DIR="$TMP_UNZIP_DIR/$DIR_NAME" 172 | 173 | # Missing archives are not considered fatal, just skip the game 174 | if [[ ! -f "$GAME_ARCHIVE" ]]; then 175 | echo -e "$STARTRED""Game archive not found: \"$GAME_ARCHIVE\", skipping""$ENDRED" 176 | break 177 | fi 178 | 179 | echo "Extracting archive $GAME_ARCHIVE to temporary directory $GAME_TMP_DIR" 180 | unzip "$GAME_ARCHIVE" -d "$GAME_TMP_DIR" 181 | 182 | # Extracting errors are fatal - maybe we have no space left on the 183 | # device? Abort the script instead of wreaking havoc 184 | if [[ $? -ne 0 ]]; then 185 | echo -e "$STARTRED""Error extracting archive: $GAME_ARCHIVE""$ENDRED" >&2 186 | echo -e "$STARTRED""Aborting script""$ENDRED" >&2 187 | exit; 188 | fi 189 | 190 | # Determine whether we are dealing with GDI or CDI image. 191 | DISC_FILE=`find "$GAME_TMP_DIR" -type f -name *.gdi | head -n 1` 192 | if [[ ! -z $DISC_FILE ]]; then 193 | TYPE="gdi" 194 | else 195 | DISC_FILE=`find "$GAME_TMP_DIR" -type f -name *.cdi | head -n 1` 196 | TYPE="cdi" 197 | fi 198 | 199 | # If we didn't find a GDI or CDI image inside the extracted archive we 200 | # skip it. This isn't perfect since the error message might get lost in 201 | # the output noise, leading to perception that everything went fine when 202 | # it actually didn't. But aborting the script in the middle of 203 | # execution can potentially cause mess so skipping seems like a better 204 | # solution. 205 | if [[ -z $DISC_FILE ]]; then 206 | echo -e "$STARTRED""Couldn't find any GDI or CDI file in $GAME_ARCHIVE""$ENDRED" >&2 207 | echo -e "$STARTRED""Skipping""$ENDRED" >&2 208 | break 209 | fi 210 | 211 | DISC_FILE=`basename "$DISC_FILE"` 212 | # Rename the gdi/cdi file to disc.gdi/disc.cdi, move the extracted game 213 | # to target directory, add the game to the game list 214 | echo "Writing $ARCHIVE_FILE" 215 | echo "$GAME" > "$GAME_TMP_DIR/$ARCHIVE_FILE" 216 | if [[ ! -e "$GAME_TMP_DIR/disc.$TYPE" ]]; then 217 | echo "Renaming disc file \"$DISC_FILE\" to \"disc.$TYPE\"" 218 | mv "$GAME_TMP_DIR/$DISC_FILE" "$GAME_TMP_DIR/disc.$TYPE" 219 | fi 220 | # If moving files goes wrong abort immediately - we might be out of 221 | # space on the SD card 222 | echo "Moving game from temporary directory to target directory" 223 | mv "$GAME_TMP_DIR" "$TARGET_DIR" || exit 224 | (( INDEX++ )) 225 | echo "Adding \"$GAME\" to $OUTPUT_FILE" 226 | echo "Game \"$GAME\" has been placed in directory \"$DIR_NAME\"" 227 | echo "$GAME" >> "$OUTPUT_FILE" 228 | else 229 | # If a game was already extracted just determine whether we are dealing 230 | # with GDI or CDI image. 231 | if [[ ! -z `find "$TARGET_DIR/$DIR_NAME" -type f -name *.gdi | head -n 1` ]]; then 232 | TYPE="gdi" 233 | else 234 | TYPE="cdi" 235 | fi 236 | fi 237 | 238 | # Now that the image files are in the target directory we need to extract 239 | # information required to create a GDMenu entry for the game. For GDI files 240 | # this information is stored in an ip.bin file inside a GDI image. See 241 | # https://mc.pp.se/dc/ip0000.bin.html for more information. For CDI files 242 | # this information is stored in first 16 sectors of the last data track. To 243 | # read this information we need to extract the CDI file to a /tmp directory 244 | # in order to get access to data tracks. 245 | if [[ $TYPE == "gdi" ]]; then 246 | ./tools/gditools.py -i "$TARGET_DIR/$DIR_NAME/disc.gdi" -b ip.bin 247 | METADATA_FILE="$TARGET_DIR/$DIR_NAME/ip.bin" 248 | else 249 | TMP_DIR=`mktemp -d -t dc-card-maker-XXXXX` 250 | ./tools/cdirip "$TARGET_DIR/$DIR_NAME/disc.cdi" $TMP_DIR 251 | # Note: this is potentially fragile, assumes data tracks have *.iso 252 | # extension 253 | METADATA_FILE=`find $TMP_DIR -type f -name *.iso | sort | tail -n 1` 254 | fi 255 | 256 | # Get the metadata 257 | if [[ -e "$TARGET_DIR/$DIR_NAME/$NAME_FILE" ]]; then 258 | NAME_INFO=`cat $TARGET_DIR/$DIR_NAME/$NAME_FILE | head -n 1` 259 | else 260 | NAME_INFO=`hexdump -v -e '"%c"' -s0x80 -n 128 $METADATA_FILE | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//'` 261 | echo "$NAME_INFO" > "$TARGET_DIR/$DIR_NAME/$NAME_FILE" 262 | fi 263 | DISC_INFO=`hexdump -v -e '"%c"' -s0x2B -n 3 $METADATA_FILE` 264 | VGA_INFO=`hexdump -v -e '"%c"' -s0x3D -n 1 $METADATA_FILE` 265 | REGION_INFO=`hexdump -v -e '"%c"' -s0x30 -n 8 $METADATA_FILE | sed 's/[[:blank:]]*//g'` 266 | VERSION_INFO=`hexdump -v -e '"%c"' -s0x4A -n 6 $METADATA_FILE` 267 | DATE_INFO=`hexdump -v -e '"%c"' -s0x50 -n 8 $METADATA_FILE` 268 | 269 | # Remove metadata files 270 | rm "$METADATA_FILE" 271 | if [[ $TYPE == "cdi" ]]; then 272 | rm -rf $TMP_DIR 273 | fi 274 | 275 | # Write menu entry data to INI file 276 | echo "$DIR_NAME.name=$NAME_INFO" >> $GDMENU_INI 277 | echo "$DIR_NAME.disc=$DISC_INFO" >> $GDMENU_INI 278 | echo "$DIR_NAME.vga=$VGA_INFO" >> $GDMENU_INI 279 | echo "$DIR_NAME.region=$REGION_INFO" >> $GDMENU_INI 280 | echo "$DIR_NAME.version=$VERSION_INFO" >> $GDMENU_INI 281 | echo "$DIR_NAME.date=$DATE_INFO" >> $GDMENU_INI 282 | echo "" >> $GDMENU_INI 283 | 284 | done < "$INPUT_FILE" 285 | 286 | # Build GDMenu cdi image and put it in 01 directory 287 | echo "Building GDMenu disc image" 288 | genisoimage -C 0,11702 -V GDMENU -G data/ip.bin -r -J -l -input-charset iso8859-1 -o gdmenu.iso data/1ST_READ.BIN $GDMENU_INI 289 | ./tools/cdi4dc gdmenu.iso gdmenu.cdi 290 | rm gdmenu.iso 291 | mkdir "$TARGET_DIR/01" 292 | mv gdmenu.cdi "$TARGET_DIR/01" 293 | 294 | # Copy default GDMenu configuration 295 | echo "Copying GDEMU configuration" 296 | cp ini/GDEMU.ini "$TARGET_DIR" 297 | 298 | # Restore backup copy of GDMenu 299 | if [[ -d "$TARGET_DIR/gdmenu_old" ]]; then 300 | mv "$TARGET_DIR/gdmenu_old" "$TARGET_DIR/01_" 301 | fi 302 | 303 | # Remove temporary direcotry 304 | rmdir "$TMP_UNZIP_DIR" 305 | 306 | # Report any leftover dirs to the user. Re-running the script won't be possible 307 | # if these exist. 308 | LEFTOVER_DIRS=`find $TARGET_DIR -regextype sed -regex "$TARGET_DIR/*[0-9][0-9]*_"` 309 | if [[ ! -z $LEFTOVER_DIRS ]]; then 310 | echo -e "$STARTRED""Following directories at target directory contain old games""$ENDRED" 311 | for DIR in $LEFTOVER_DIRS; do 312 | echo -e "$STARTRED"$DIR"$ENDRED" 313 | done 314 | echo -e "$STARTRED""Delete or move them to a different location.""$ENDRED" 315 | fi 316 | -------------------------------------------------------------------------------- /ini/GDEMU.ini: -------------------------------------------------------------------------------- 1 | open_time = 150 2 | detect_time = 150 3 | reset_goto = 1 -------------------------------------------------------------------------------- /licenses/LICENSE-dc-card-maker-script: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /licenses/LICENSE-gditools: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /licenses/LICENSE-iso9660: -------------------------------------------------------------------------------- 1 | Copyright (C) 2013-2014 Barnaby Gale 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to 5 | deal in the Software without restriction, including without limitation the 6 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 | sell copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies of the Software and its documentation and acknowledgment shall be 12 | given in the documentation and software packages that this Software was 13 | used. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /tools/gditools.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | gditools, a python library to extract files, sorttxt.txt and 6 | bootsector (ip.bin) from SEGA Gigabyte Disc (GD-ROM) dumps. 7 | 8 | FamilyGuy 2014-2015 9 | 10 | 11 | gditools.py and provided examples are licensed under the GNU 12 | General Public License (version 3), a copy of which is provided 13 | in the licences folder: GNU_GPL_v3.txt 14 | 15 | 16 | Original iso9660.py by Barney Gale : github.com/barneygale/iso9660 17 | iso9660.py is licensed under a BSD license, a copy of which is 18 | provided in the licences folder: iso9660_licente.txt 19 | """ 20 | import traceback 21 | import os 22 | import sys 23 | import shutil 24 | import getopt 25 | from copy import deepcopy 26 | from iso9660 import ISO9660 as _ISO9660_orig 27 | from struct import unpack 28 | from datetime import datetime 29 | from io import BytesIO, FileIO 30 | 31 | 32 | # TODO TODO TODO 33 | # 34 | # - Uniformize how we create unexisting paths exists 35 | # (files/sort/bootsector/outputpath) 36 | # 37 | # - Test extensively, find bugs and fix them? 38 | # 39 | # TODO TODO TODO 40 | 41 | class GDIException(Exception): 42 | pass 43 | 44 | 45 | class ISO9660(_ISO9660_orig): 46 | """ 47 | Modification to iso9660.py to easily handle GDI files 48 | 49 | """ 50 | 51 | # Overriding Functions of original class in this section 52 | 53 | def __init__(self, gdi, *args, **kwargs): 54 | # We obviously override the init to add support for our modifications 55 | self._gdi = gdi 56 | if not gdi: 57 | print("No gdi file provided") 58 | raise GDIException("No gdi file provided") 59 | return 60 | 61 | self._dict1 = [i for i in gdi if i['lba'] 62 | == 45000][0] # That's ugly but it works 63 | self._dirname = os.path.dirname(self._dict1['filename']) 64 | self._dict2 = None 65 | if len(gdi) > self._dict1['tnum']: 66 | self._dict2 = gdi[-1] 67 | 68 | self._last_read_toc_sector = 0 # Last read TOC sector *SO FAR* 69 | 70 | self._gdifile = AppendedFiles(self._dict1, self._dict2) 71 | 72 | _ISO9660_orig.__init__(self, 'url') # So url doesn't starts with http 73 | 74 | if 'verbose' in kwargs: 75 | self._verbose = kwargs.pop('verbose') 76 | else: 77 | self._verbose = False 78 | 79 | # Overriding this function allows to parse AppendedFiles as isos 80 | 81 | def _get_sector_file(self, sector, length): 82 | # A big performance improvement versus re-opening the file for each 83 | # read as in the original ISO9660 implementation. 84 | self._gdifile.seek(sector*2048) 85 | self._buff = BytesIO(self._gdifile.read(length)) 86 | 87 | def _unpack_record(self, read=0): 88 | tmp = _ISO9660_orig._unpack_record(self, read) 89 | pointer = self._gdifile.tell() 90 | # Where are we in sectors? 91 | current_pointer_pos = pointer//2048 92 | # If we're not at the exact beginning of a sector, we add one. 93 | if pointer % 2048: 94 | current_pointer_pos += 1 95 | 96 | if current_pointer_pos > self._last_read_toc_sector: 97 | self._last_read_toc_sector = current_pointer_pos 98 | 99 | return tmp 100 | 101 | ### NEW FUNCTIONS FOLLOW ### 102 | 103 | def get_record(self, path): 104 | path = path.upper().strip('/').split('/') 105 | path, filename = path[:-1], path[-1] 106 | 107 | if len(path) == 0: 108 | parent_dir = self._root 109 | else: 110 | parent_dir = self._dir_record_by_root(path) 111 | 112 | f = self._search_dir_children(parent_dir, filename) 113 | return f 114 | 115 | def gen_records(self, get_files=True): 116 | gen = self._tree_nodes_records(self._root) 117 | for i in gen: 118 | if get_files: 119 | yield i 120 | elif i['flags'] == 2: 121 | yield i 122 | 123 | def _tree_nodes_records(self, node): 124 | def spacer(s): return dict( 125 | list({j: s[j] for j in [i for i in s if i != 'name']}.items()), 126 | name="%s/%s" % (node['name'].lstrip('\x00\x01'), 127 | s['name'])) 128 | for c in list(self._unpack_dir_children(node)): 129 | yield spacer(c) 130 | if c['flags'] & 2: 131 | for d in self._tree_nodes_records(c): 132 | yield spacer(d) 133 | 134 | def get_pvd(self): 135 | return self._pvd 136 | 137 | def get_volume_label(self): 138 | return self.get_pvd()['volume_identifier'] 139 | 140 | def print_files(self): 141 | for i in self.tree(): 142 | print(i) 143 | 144 | def get_bootsector(self, lba=45000): 145 | self._get_sector(lba, 16*2048) 146 | return self._unpack_raw(16*2048) 147 | 148 | def get_file_by_record(self, filerec): 149 | self._gdifile.seek(filerec['ex_loc']*2048) 150 | return self._gdifile.read(filerec['ex_len']) 151 | 152 | def get_file(self, filename): 153 | return self.get_file_by_record(self.get_record(filename)) 154 | 155 | def get_sorttxt(self, crit='ex_loc', prefix='data', dummy='0.0', spacer=1): 156 | """ 157 | prefix : Folder that will be created in the pwd. 158 | Default: 'data' 159 | 160 | dummy : Name of the dummy file to be put in the sorttxt 161 | Set to False not to use a dummy file 162 | Default: '0.0' 163 | 164 | crit : (criterion) can be any file record entry 165 | Default: 'ex_loc' (LBA) 166 | 167 | If the first letter of crit is uppercase, order is reversed 168 | 169 | e.g. 170 | 171 | 'ex_loc' or 'EX_LOC' -> Sorted by LBA value. 172 | 'name' or 'NAME' -> Sorted by file name. 173 | 'ex_len' or 'EX_LEN' -> Sorted by file size. 174 | 175 | 176 | Note: First file in sorttxt represents the last one on disc. 177 | 178 | e.g. 179 | 180 | - A sorttxt representing the file order of the source iso: 181 | self.get_sorted(crit='ex_loc') 182 | 183 | - A sorttxt with BIGGEST files at the outer part of disc: 184 | self.get_sorted(crit='ex_len') 185 | 186 | - A sorttxt with SMALLEST files at the outer part of disc: 187 | self.get_sorted(criterion='EX_LEN') 188 | """ 189 | return self._sorttxt_from_records(self._sorted_records(crit=crit), 190 | prefix=prefix, dummy=dummy, spacer=spacer) 191 | 192 | def _sorted_records(self, crit='ex_loc', nodirs=True): 193 | file_records = [i for i in self.gen_records()] 194 | if nodirs: 195 | for i in self.gen_records(get_files=False): 196 | file_records.pop(file_records.index(i)) # Strips directories 197 | reverse = crit[0].islower() 198 | crit = crit.lower() 199 | ordered_records = sorted(file_records, key=lambda k: k[crit], 200 | reverse=reverse) 201 | return ordered_records 202 | 203 | def _sorttxt_from_records(self, records, prefix='data', dummy='0.0', spacer=1): 204 | spacer = int(spacer) 205 | sorttxt = '' 206 | newline = '{prefix}{filename} {importance}\r\n' 207 | for i, f in enumerate(records): 208 | sorttxt += newline.format(prefix=prefix, filename=f['name'], 209 | importance=spacer*(i+1)) 210 | if dummy: 211 | if not dummy[0] == '/': 212 | dummy = '/' + dummy 213 | sorttxt += newline.format(prefix=prefix, filename=dummy, 214 | importance=spacer*(len(records)+1)) 215 | return sorttxt 216 | 217 | def dump_sorttxt(self, filename='sorttxt.txt', **kwargs): 218 | if not filename[0] == '/': # Paths rel. to gdi folder unless full paths 219 | filename = self._dirname + '/' + filename 220 | 221 | path = os.path.dirname(filename) 222 | if not os.path.exists(path): 223 | # Creates required dirs, including empty ones 224 | os.makedirs(path) 225 | if self._verbose: 226 | message = 'Created directory: {}' 227 | UpdateLine(message.format(path)) 228 | 229 | with open(filename, 'wb') as f: 230 | if self._verbose: 231 | print(f'Dumping sorttxt to {filename}') 232 | f.write(self.get_sorttxt(**kwargs)) 233 | 234 | def dump_bootsector(self, filename='ip.bin', **kwargs): 235 | if not filename[0] == '/': # Paths rel. to gdi folder unless full paths 236 | filename = self._dirname + '/' + filename 237 | 238 | path = os.path.dirname(filename) 239 | if not os.path.exists(path): 240 | # Creates required dirs, including empty ones 241 | os.makedirs(path) 242 | if self._verbose: 243 | message = 'Created directory: {}' 244 | UpdateLine(message.format(path)) 245 | 246 | with open(filename, 'wb') as f: 247 | if self._verbose: 248 | print(f'Dumping bootsector to {filename}') 249 | f.write(self.get_bootsector(**kwargs)) 250 | 251 | def dump_file_by_record(self, rec, target='.', keep_timestamp=True, 252 | filename=None): 253 | """ 254 | rec: Record of a file in the filesystem 255 | target: Directory target to dump file into 256 | keep_timestamp: Uses timestamp in fs for dumped file 257 | filename: *None* -> Uses name in fs, else it overrides filename 258 | """ 259 | if not target[-1] == '/': 260 | target += '/' 261 | # User provided filename overrides records's subfolders & name 262 | if filename: 263 | filename = target + filename.strip('/') 264 | else: 265 | filename = target + rec['name'].strip('/') 266 | 267 | if rec['flags'] == 2: 268 | # So os.path.isdirname yields right value for dir records 269 | filename += '/' 270 | 271 | path = os.path.dirname(filename) 272 | if not os.path.exists(path): 273 | # Creates required dirs, including empty ones 274 | os.makedirs(path) 275 | if self._verbose: 276 | message = 'Created directory: {}' 277 | UpdateLine(message.format(path)) 278 | 279 | if rec['flags'] != 2: # If rec doesn't represents a directory 280 | message = 'Dumping {} to {} ({}, {})' 281 | if self._verbose: 282 | UpdateLine(message.format(rec['name'].split('/')[-1], 283 | filename, rec['ex_loc'], 284 | rec['ex_len'])) 285 | with open(filename, 'wb') as f: 286 | # Using buffered copy to speed up things, hopefully 287 | # Potentially beneficial on Windows mainly 288 | self._gdifile.seek(rec['ex_loc']*2048) 289 | _copy_buffered(self._gdifile, f, length=rec['ex_len']) 290 | 291 | if keep_timestamp: 292 | os.utime(filename, (self._get_timestamp_by_record(rec),)*2) 293 | 294 | def dump_file(self, name, **kwargs): 295 | self.dump_file_by_record(self.get_record(name), **kwargs) 296 | if self._verbose: 297 | UpdateLine('\n') 298 | 299 | def dump_all_files(self, target='data', **kwargs): 300 | # target has a default value not to accidentally fill dev folder 301 | # Sorting according to LBA to avoid too much skipping on HDDs 302 | 303 | if not target[0] == '/': # Paths rel. to gdi folder unless full paths 304 | target = self._dirname + '/' + target 305 | try: 306 | for i in self._sorted_records(crit='EX_LOC', nodirs=False): 307 | self.dump_file_by_record(i, target=target, **kwargs) 308 | 309 | if self._verbose: 310 | UpdateLine('All files were dumped successfully.') 311 | UpdateLine('\n') 312 | 313 | except Exception as e: 314 | print(e) 315 | print(traceback.format_exc()) 316 | if self._verbose: 317 | UpdateLine('There was an error dumping all files.') 318 | 319 | def get_time_by_record(self, rec): 320 | tmp = datetime.fromtimestamp(self._get_timestamp_by_record(rec)) 321 | return tmp.strftime('%Y-%m-%d %H:%M:%S (localtime)') 322 | 323 | def get_time(self, filename): 324 | return self.get_time_by_record(self.get_record(filename)) 325 | 326 | def _get_timestamp_by_record(self, rec): 327 | #date = list(rec['datetime']) 328 | #date[0] += 1900 329 | date = [1999, 9, 9, 23, 59, 59] 330 | t_timestamp = self._datetime_to_timestamp(date) 331 | tmp = datetime.fromtimestamp(t_timestamp) 332 | return t_timestamp 333 | 334 | def _datetime_to_timestamp(self, t): 335 | epoch = datetime(1970, 1, 1) 336 | timez = t.pop(-1) * 15 * 60 337 | # timez: Offset from GMT in 15 min intervals converted to secs 338 | T = (datetime(*t)-epoch).total_seconds() 339 | return T - timez 340 | 341 | def get_last_toc_sector(self): 342 | # Parsing the whole TOC to find the last accessed sector. 343 | tmp = map(None, self.tree(), self.tree(get_files=False)) 344 | return self._last_read_toc_sector 345 | 346 | def get_first_file_sector(self): 347 | # Some FS include DA tracks in their FS, it should be ignored here 348 | i = -1 349 | lba = self._sorted_records()[i]['ex_loc'] 350 | while lba < self._gdi[-1]['lba']: 351 | i -= 1 352 | lba = self._sorted_records()[i]['ex_loc'] 353 | return lba 354 | 355 | def shrink_blank_check(self): 356 | gdifile = self._gdifile 357 | begin = self.get_last_toc_sector() 358 | end = self.get_first_file_sector() 359 | 360 | length = end-begin 361 | readsize = 512 # Sectors 512 -> 1 MiB at a time 362 | sectref = "\x00"*2048 363 | readref = readsize*sectref 364 | nz_sect = [begin, ] # Non-zero sectors between *begin* and *end* 365 | 366 | for i in range(length//readsize): 367 | # Make sure we're at right offset 368 | gdifile.seek((begin+i*readsize)*2048) 369 | if not readref == gdifile.read(readsize*2048): 370 | gdifile.seek(-1*readsize*2048, 1) # Rewind 371 | for j in range(readsize): 372 | if not sectref == gdifile.read(2048): 373 | nz_sect.append(begin+i*readsize+j) # Current sector 374 | 375 | for i in range(length % readsize): 376 | # Make sure we're at right offset 377 | gdifile.seek((begin+length//readsize*readsize+i)*2048) 378 | if not sectref == gdifile.read(2048): 379 | nz_sect.append(begin+i*readsize+j) # Current sector 380 | 381 | nz_sect.append(end) # Previously found end is non-zero 382 | 383 | # Finding the largest zero-filled gap 384 | gaps = [j-i for i, j in zip(nz_sect[:-1], nz_sect[1:])] 385 | gidx = gaps.index(max(gaps)) 386 | 387 | # Setting new begin/end to the largest zero-filled gap 388 | begin = nz_sect[gidx] # gidx+1 is first zero since gdix is non-zero, 389 | end = nz_sect[gidx+1] # 390 | 391 | return begin, end 392 | 393 | def __enter__(self): 394 | return self 395 | 396 | def __exit__(self, type=None, value=None, traceback=None): 397 | self._gdifile.__exit__() 398 | 399 | 400 | class GDIfile(ISO9660): 401 | """ 402 | Returns a class that represents a gdi dump of a GD-ROM. 403 | It should be initiated with a string pointing to a gdi file. 404 | 405 | Boolean kwarg *verbose* enables printing infos on what's going on. 406 | 407 | e.g. 408 | gdi = gdifile('disc.gdi') 409 | gdi.dump_all_files() 410 | """ 411 | 412 | def __init__(self, filename, **kwargs): # Isn't OO programming wonderful? 413 | verbose = kwargs['verbose'] if 'verbose' in kwargs else False 414 | ISO9660.__init__(self, parse_gdi(filename, verbose=verbose), **kwargs) 415 | self._gdi_filename = filename 416 | 417 | def __enter__(self): 418 | return self 419 | 420 | def __exit__(self, type=None, value=None, traceback=None): 421 | self._gdifile.__exit__() 422 | 423 | 424 | class CdImage(FileIO): 425 | """ 426 | Class that allows opening a 2352, 2336 or 2048 bytes/sector data cd track 427 | as a 2048 bytes/sector one. 428 | """ 429 | 430 | def __init__(self, filename, mode='auto', manualRawOffset=0, *args, **kwargs): 431 | 432 | if mode == 'auto': 433 | if filename[-4:] == '.iso': 434 | mode = 2048 435 | elif filename[-4:] == '.bin': 436 | mode = 2352 437 | 438 | elif not mode in [2048, 2352, 2336]: 439 | raise ValueError('Argument mode should be either 2048 or 2352') 440 | self.__mode = mode 441 | 442 | if mode == 2352: 443 | self._sectorOffset: int = 16 444 | self._skipToNext: int = 304 445 | 446 | elif mode == 2336: 447 | self._sectorOffset: int = 8 448 | self._skipToNext: int = 288 449 | 450 | self.__manualRawOffset: int = manualRawOffset 451 | 452 | if (len(args) > 0) and (args[0] not in ['r', 'rb']): 453 | raise NotImplementedError('Only read mode is implemented.') 454 | 455 | super(CdImage, self).__init__(filename, 'rb', *args) 456 | 457 | super(CdImage, self).seek(0, 2) 458 | if self.__mode in [2352, 2336]: 459 | self.length = super(CdImage, self).tell() * 2048//self.__mode 460 | else: 461 | self.length = super(CdImage, self).tell() 462 | super(CdImage, self).seek(0, 0) 463 | 464 | self.seek(0) 465 | 466 | def realOffset(self, a) -> int: 467 | _a = int(a) 468 | ret = _a//2048 * self.__mode + _a % 2048 + \ 469 | self._sectorOffset + self.__manualRawOffset 470 | return ret 471 | 472 | def seek(self, a: int, b: int = 0): 473 | if self.__mode == 2048: 474 | super(CdImage, self).seek(a, b) 475 | 476 | elif self.__mode in [2352, 2336]: 477 | if b == 0: 478 | self.binpointer: int = a 479 | if b == 1: 480 | self.binpointer: int = self.binpointer + a 481 | if b == 2: 482 | self.binpointer: int = self.length - a 483 | 484 | realpointer = self.realOffset(self.binpointer) 485 | super(CdImage, self).seek(realpointer, 0) 486 | 487 | def read(self, length=None): 488 | if self.__mode == 2048: 489 | return super(CdImage, self).read(length) 490 | 491 | elif self.__mode in [2352, 2336]: 492 | if length == None: 493 | length = self.length - self.binpointer 494 | 495 | # Amount of bytes left until beginning of next sector 496 | tmp = int(2048 - self.binpointer % 2048) 497 | FutureOffset = self.binpointer + length 498 | realLength = self.realOffset( 499 | FutureOffset) - self.realOffset(self.binpointer) 500 | # This will (hopefully) accelerates readings on HDDs at the 501 | # cost of more memory use. 502 | buff = BytesIO(super(CdImage, self).read(realLength)) 503 | # The first read can be < 2048 bytes 504 | data = buff.read(tmp) 505 | length -= tmp 506 | buff.seek(self._skipToNext, 1) 507 | length = int(length) 508 | # The middle reads are all 2048 so we optimize here! 509 | for i in range(length // 2048): 510 | data += buff.read(2048) 511 | buff.seek(self._skipToNext, 1) 512 | # The last read can be < 2048 bytes 513 | data += buff.read(length % 2048) 514 | # Seek back to where we should be 515 | self.seek(FutureOffset) 516 | return data 517 | 518 | def tell(self): 519 | if self.__mode == 2048: 520 | return super(CdImage, self).tell() 521 | 522 | elif self.__mode in [2352, 2336]: 523 | return self.binpointer 524 | 525 | 526 | class OffsetedFile(CdImage): 527 | """ 528 | Like a file, but offsetted! Padding is made of 0x00. 529 | 530 | READ ONLY: trying to open a file in write mode will raise a 531 | NotImplementedError 532 | """ 533 | 534 | def __init__(self, filename, *args, **kwargs): 535 | 536 | if 'offset' in kwargs: 537 | self.offset = kwargs.pop('offset') 538 | else: 539 | self.offset = 0 540 | 541 | if (len(args) > 0) and (args[0] not in ['r', 'rb']): 542 | raise NotImplementedError('Only read mode is implemented.') 543 | super(OffsetedFile, self).__init__(filename, **kwargs) 544 | 545 | super(OffsetedFile, self).seek(0, 2) 546 | self.length = super(OffsetedFile, self).tell() 547 | super(OffsetedFile, self).seek(0, 0) 548 | 549 | self.seek(0) 550 | 551 | def seek(self, a, b=0): 552 | if b == 0: 553 | self.pointer = a 554 | if b == 1: 555 | self.pointer += a 556 | if b == 2: 557 | self.pointer = self.length + self.offset - a 558 | 559 | if self.pointer > self.offset: 560 | super(OffsetedFile, self).seek(self.pointer - self.offset) 561 | else: 562 | super(OffsetedFile, self).seek(0) 563 | 564 | def read(self, length=None): 565 | if length == None: 566 | length = self.offset + self.length - self.pointer 567 | tmp = self.pointer 568 | FutureOffset = self.pointer + length 569 | if tmp >= self.offset: 570 | # print 'AFTER OFFSET' 571 | self.seek(tmp) 572 | data = super(OffsetedFile, self).read(length) 573 | elif FutureOffset < self.offset: 574 | # print 'BEFORE OFFSET' 575 | data = b'\x00'*length 576 | else: 577 | # print 'CROSSING OFFSET' 578 | preData = b'\x00'*(self.offset - tmp) 579 | self.seek(self.offset) 580 | postData = super(OffsetedFile, self).read( 581 | FutureOffset - self.offset) 582 | data = preData + postData 583 | self.seek(FutureOffset) 584 | return data 585 | 586 | def tell(self): 587 | return self.pointer 588 | 589 | 590 | class WormHoleFile(OffsetedFile): 591 | """ 592 | Redirects an offset-range to another offset in a file. Because 593 | everbody likes wormholes. 594 | 595 | I even chose that name before WH were mainsteam (Interstellar) 596 | """ 597 | 598 | def __init__(self, *args, **kwargs): 599 | 600 | # *wormhole* should be [target_offset, source_offset, wormlen] 601 | # target_offset + wormlen < source_offset 602 | 603 | if 'wormhole' in kwargs: 604 | self.target, self.source, self.wormlen = kwargs.pop('wormhole') 605 | else: 606 | self.target, self.source, self.wormlen = [0, 0, 0] 607 | 608 | super(WormHoleFile, self).__init__(*args, **kwargs) 609 | 610 | def read(self, length=None): 611 | 612 | if length == None: 613 | length = self.offset + self.length - self.pointer 614 | tmp = self.pointer 615 | FutureOffset = self.pointer + length 616 | 617 | # If we start after the wormhole or if we don't reach it, 618 | # everything is fine 619 | if (tmp >= self.target + self.wormlen) or (FutureOffset < self.target): 620 | # print 'OUT OF WORMHOLE' 621 | data = super(WormHoleFile, self).read(length) 622 | 623 | # If we start inside the wormhole, it's trickier 624 | elif tmp >= self.target: 625 | # print 'START INSIDE' 626 | # Through the wormhole to the source 627 | self.seek(tmp - self.target + self.source) 628 | 629 | # If we don't exit the wormhole, it's somewhat simple 630 | if FutureOffset < self.target + self.wormlen: 631 | # print 'DON\'T EXIT IT' 632 | data = super(WormHoleFile, self).read( 633 | length) # Read in the source 634 | 635 | # If we exit the wormhole midway, it's even trickier 636 | else: 637 | # print 'EXIT IT' 638 | inWorm_len = self.target + self.wormlen - tmp 639 | outWorm_len = FutureOffset - self.target - self.wormlen 640 | inWorm = super(WormHoleFile, self).read(inWorm_len) 641 | self.seek(self.target + self.wormlen) 642 | outWorm = super(WormHoleFile, self).read(outWorm_len) 643 | inWorm_bytes = inWorm if isinstance( 644 | inWorm, bytes) else inWorm.encode() 645 | outWorm_bytes = outWorm if isinstance( 646 | outWorm, bytes) else outWorm.encode() 647 | data = inWorm_bytes + outWorm_bytes 648 | 649 | # If we start before the wormhole then hop inside, it's also 650 | # kinda trickier 651 | elif FutureOffset < self.target + self.wormlen: 652 | # print 'START BEFORE, ENTER IT' 653 | preWorm_len = self.target - tmp 654 | inWorm_len = FutureOffset - self.target 655 | preWorm = super(WormHoleFile, self).read(preWorm_len) 656 | self.seek(self.source) 657 | inWorm = super(WormHoleFile, self).read(inWorm_len) 658 | data = preWorm + inWorm 659 | 660 | # Now if we start before the wormhole and jump over it, it's 661 | # the trickiest 662 | elif FutureOffset > self.target + self.wormlen: 663 | # print 'START BEFORE, END AFTER' 664 | preWorm_len = self.target - tmp 665 | inWorm_len = self.wormlen 666 | postWorm_len = FutureOffset - self.target - self.wormlen 667 | 668 | preWorm = super(WormHoleFile, self).read(preWorm_len) 669 | self.seek(self.source) 670 | inWorm = super(WormHoleFile, self).read(inWorm_len) 671 | self.seek(self.target + inWorm_len) 672 | postWorm = super(WormHoleFile, self).read(postWorm_len) 673 | 674 | data = preWorm + inWorm + postWorm 675 | 676 | # Pretend we're still where we should, in case we went where we 677 | # shouldn't have! 678 | self.seek(FutureOffset) 679 | return data 680 | 681 | 682 | class AppendedFiles(): 683 | """ 684 | Two WormHoleFiles one after another. 685 | Takes 1 or 2 dict(s) as arguments; they're passed to WormHoleFiles' 686 | at the init. 687 | 688 | This is aimed at merging the TOC track starting at LBA45000 with 689 | the last one to mimic one big track at LBA0 with the files at the 690 | same LBA than the GD-ROM. 691 | """ 692 | 693 | def __init__(self, wormfile1, wormfile2=None, *args, **kwargs): 694 | 695 | self._f1 = WormHoleFile(**wormfile1) 696 | 697 | self._f1.seek(0, 2) 698 | self._f1_len = self._f1.tell() 699 | self._f1.seek(0, 0) 700 | 701 | self._f2_len = 0 702 | if wormfile2: 703 | self._f2 = WormHoleFile(**wormfile2) 704 | 705 | self._f2.seek(0, 2) 706 | self._f2_len = self._f2.tell() 707 | self._f2.seek(0, 0) 708 | else: 709 | # So the rest of the code works for one or 2 files. 710 | self._f2 = BytesIO(b'') 711 | 712 | self.seek(0, 0) 713 | 714 | def seek(self, a, b=0): 715 | if b == 0: 716 | self.MetaPointer = a 717 | if b == 1: 718 | self.MetaPointer += a 719 | if b == 2: 720 | self.MetaPointer = self._f1_len + self._f2_len - a 721 | 722 | if self.MetaPointer >= self._f1_len: 723 | self._f1.seek(0, 2) 724 | self._f2.seek(a - self._f1_len, 0) 725 | else: 726 | self._f1.seek(a, 0) 727 | self._f2.seek(0, 0) 728 | 729 | def read(self, length=None): 730 | if length == None: 731 | length = self._f1_len + self._f2_len - self.MetaPointer 732 | tmp = self.MetaPointer 733 | FutureOffset = self.MetaPointer + length 734 | if FutureOffset < self._f1_len: # Read inside file1 735 | data = self._f1.read(length) 736 | elif tmp > self._f1_len: # Read inside file2 737 | data = self._f2.read(length) 738 | else: # Read end of file1 and start of file2 739 | data = self._f1.read(self._f1_len - tmp) 740 | data += self._f2.read(FutureOffset - self._f1_len) 741 | 742 | self.seek(FutureOffset) # It might be enough to just update 743 | # self.MetaPointer, but this is safer. 744 | return data 745 | 746 | def tell(self): 747 | return self.MetaPointer 748 | 749 | def __enter__(self): 750 | return self 751 | 752 | def __exit__(self, type=None, value=None, traceback=None): 753 | # This is required to close files properly when using the with 754 | # statement. Which isn't required by ISO9660 anymore, but could 755 | # be useful for other uses so it stays! 756 | self._f1.__exit__() 757 | if self._f2_len: 758 | self._f2.__exit__() 759 | 760 | 761 | def gdishrink(filename, odir=None, erase_bak=False, blank_check=True, verbose=True): 762 | """ 763 | Function to shrink a GDI. 764 | 765 | *filename* should point to a valid gdi file with all tracks in the same folder. 766 | default output path *odir* in the same as the input one. 767 | """ 768 | # 1- Managing filenames and input GDI infos 769 | absname = os.path.abspath(filename) 770 | basedir = os.path.dirname(absname) 771 | basename = os.path.basename(filename) 772 | isize = get_total_gdi_dumpsize(absname) # For saved-space comparison 773 | 774 | if odir is None: 775 | odir = basedir 776 | else: 777 | odir = os.path.abspath(odir) 778 | 779 | with GDIfile(absname) as gdi: 780 | itracks = gdi._gdi 781 | numtracks = len(itracks) 782 | if blank_check: 783 | first_blank_sector, first_file_sector = gdi.shrink_blank_check() 784 | else: 785 | first_blank_sector = gdi.get_last_toc_sector() 786 | first_file_sector = gdi.get_first_file_sector() 787 | sanity_check_file_A = gdi.get_file_by_record( 788 | gdi._sorted_records(crit='ex_loc')[0]) 789 | 790 | # 2- We plan the new tracks, considering 3tracks or 5+tracks dumps 791 | otracks = deepcopy(itracks) # New tracks 792 | for t in otracks: 793 | t['filename'] = t['filename'].replace(basedir, odir) 794 | for i in [0, 2, -1]: # 1,3,last tracks: simpler than checking the number of tracks 795 | otracks[i]['mode'] = 2048 796 | otracks[i]['filename'] = otracks[i]['filename'].replace('.bin', '.iso') 797 | if numtracks == 3: 798 | d = dict( 799 | filename=os.path.join(odir, 'track04.iso'), 800 | lba=first_file_sector, 801 | mode=2048, 802 | # Untested as of 2017-10-16 803 | offset=2048*(first_file_sector - first_blank_sector), 804 | tnum=4, 805 | ttype='data' 806 | ) 807 | otracks = otracks+[d] 808 | else: 809 | otracks[-1]['offset'] = 2048*(first_file_sector - first_blank_sector) 810 | otracks[-1]['lba'] = first_file_sector 811 | 812 | # 3- If we shrink in-folder, we backup everything in case it goes south 813 | if odir == basedir: 814 | itracks_bak = itracks[:3] 815 | if numtracks > 3: 816 | itracks_bak = itracks_bak + [itracks[-1]] 817 | backup_files([absname]+[t['filename'] for t in itracks_bak]) 818 | # Track list now point to backup files 819 | for t in itracks_bak: 820 | t['filename'] += '.bak' 821 | 822 | # 4- We copy the relevent data from input tracks to output tracks 823 | # *** THIS IS WHERE THE SHRINKING REALLY HAPPENS *** 824 | # TRACK03 825 | with ISO9660(itracks) as gdi, open(otracks[2]['filename'], 'wb') as ofile: 826 | gdifile = gdi._gdifile 827 | begin_offset = otracks[2]['lba']*2048 828 | length = first_blank_sector*2048 - begin_offset 829 | gdifile.seek(begin_offset) 830 | _copy_buffered(gdifile, ofile, length=length) 831 | # LAST TRACK 832 | with ISO9660(itracks) as gdi, open(otracks[-1]['filename'], 'wb') as ofile: 833 | gdifile = gdi._gdifile 834 | begin_offset = first_file_sector*2048 835 | gdifile.seek(begin_offset) 836 | _copy_buffered(gdifile, ofile, length=None) # Until the end 837 | 838 | # 5- Dummy and untouched tracks 839 | # Generating dummy files for track01 and track02 840 | # TRACK01 841 | with open(otracks[0]['filename'], 'wb') as ofile: 842 | ofile.write(getDummyDataTrack()) 843 | # TRACK02 844 | with open(otracks[1]['filename'], 'wb') as ofile: 845 | ofile.write(getDummyAudioTrack()) 846 | # Moving the HD-area audio tracks too if they exist 847 | if numtracks > 3: 848 | # Only the 2de session audio tracks 849 | for iat, oat in list(zip(itracks, otracks))[3:-1]: 850 | if not os.path.isfile(oat['filename']): 851 | shutil.copy2(iat['filename'], oat['filename']) 852 | 853 | # 5- We dump the proper GDI file for the shrinked dump 854 | ofilename = os.path.join(odir, basename) 855 | with open(ofilename, 'wb') as f: 856 | f.write(gen_new_gdifile(otracks)) 857 | # SANITY CHECK 858 | with GDIfile(ofilename) as gdi: 859 | sanity_check_file_B = gdi.get_file_by_record( 860 | gdi._sorted_records(crit='ex_loc')[0]) 861 | if not sanity_check_file_A == sanity_check_file_B: 862 | raise AssertionError( 863 | 'Filesystem of the shrinked gdi is inconsistent. Cleaning skipped.') 864 | 865 | # 6- Post-shrinking cleaning 866 | if odir == basedir and erase_bak: 867 | erase_backup([absname+'.bak']+[t['filename'] for t in itracks_bak]) 868 | 869 | # 7- Boasting about the compression... or lack thereof... 870 | osize = get_total_gdi_dumpsize(ofilename) 871 | if verbose: 872 | from math import log10 873 | a = (isize-osize)/1e6 874 | b = 100*(1-float(osize)/isize) 875 | c = 100-b 876 | # Aligning decimals with Math 877 | d = ' '*(3-int(log10(isize/1e6))) 878 | e = ' '*(3-int(log10(osize/1e6))) 879 | print(f'\nGDIshrink results on {filename}:') 880 | print( 881 | f' Input:\t{d}{isize/1e6:0.3f} MB\n Output:\t{e}{osize/1e6:.3f} MB') 882 | print(f'Saved {a:.3f} MB, or {b:.2f}% at {c:.2f}% compression ratio!\n') 883 | 884 | return isize, osize # For testing, should be removed once shrinking works fine 885 | 886 | 887 | def gen_new_gdifile(_tracks): 888 | tracks = deepcopy(_tracks) 889 | gdiline = '{tnum} {lba} {tracktype} {mode} {fname} {zero}\n' 890 | s = str(len(tracks))+'\n' 891 | for i, t in enumerate(tracks): 892 | pass 893 | for t in tracks: 894 | s += gdiline.format( 895 | tracktype=4 if t['ttype'] == 'data' else 0, 896 | fname=os.path.basename(t['filename']), 897 | zero=0, 898 | **t) 899 | return s.encode('utf-8') 900 | 901 | 902 | def get_total_gdi_dumpsize(filename): 903 | filename = os.path.abspath(filename) 904 | s = get_filesize(filename) 905 | with GDIfile(filename) as gdi: 906 | tracks = gdi._gdi 907 | for t in tracks: 908 | s += get_filesize(t['filename']) 909 | return s 910 | 911 | 912 | def backup_files(files, verbose=False): 913 | """ 914 | Backups *files*, appending '.bak' to the filenames. 915 | Never overwrites a previous backup. 916 | """ 917 | if not isinstance(files, list): 918 | files = [files] 919 | for f in files: 920 | f = os.path.abspath(f) 921 | if not os.path.isfile(f+'.bak'): 922 | shutil.move(f, f+'.bak') 923 | else: 924 | if verbose: 925 | print( 926 | f"warning: backup file '{f}.bak' already exists; backup skipped") 927 | 928 | 929 | def restore_backup(bakfiles, verbose=False): 930 | """ 931 | Restores files, removing the last 4 chars (that should be '.bak'). 932 | Always overwrites target file if present. 933 | """ 934 | if not isinstance(bakfiles, list): 935 | bakfiles = [bakfiles] 936 | for f in bakfiles: 937 | if not f[-4:] == '.bak': 938 | raise NameError(f"Backup file ({f}) should end in '.bak' ") 939 | f = os.path.abspath(f) 940 | if os.path.isfile(f[:-4]): 941 | if verbose: 942 | print( 943 | f"warning: file '{f[:-4]} is being overwritten by backup") 944 | shutil.move(f, f[:-4]) 945 | 946 | 947 | def erase_backup(bakfiles, verbose=False): 948 | """ 949 | Erases the provided *bakfiles* 950 | """ 951 | if not isinstance(bakfiles, list): 952 | bakfiles = [bakfiles] 953 | for f in bakfiles: 954 | os.remove(f) 955 | 956 | 957 | def getDummyAudioTrack(): 958 | return b'\x00'*300*2352 959 | 960 | 961 | def getDummyDataTrack(): 962 | from zlib import decompress 963 | from base64 import b64decode 964 | # Compressed twice to make it smaller/prettier... really... I know it shouldn't... 965 | return decompress(decompress(b64decode('eNqruPX29um8yw4iDBc8b7qI7maKNUpyFV8iHO41ZelTn+DpFo6FShP5H27/sekf8xFdRkfvyI8BFu7bju8r/jvJTersCT5GBvzgRejlKW17DdaLz/7+8fmy2ctu2gXt33/v+Psu93e7o3eZfvn98IdeSc2ntb8qt1eK+r3v83Per/3r4eGLk5efj7sn8/Z8/5/QzXtW3E69O2WzTLl1oZHU0s+rT5vFXft8J+92aV7S1lNPq3Z2rV+92WKOj16SXM702Udzos59trOoC15i0nW9uXxnzNbTR39+XbB23auf60LP5RXveqWXLrP65avcvX2vY8zq/5R2m8gsV4rl6U76rqN59w73EvmWakmpt//9lh+2f3x5+j95oCcsYvbetix7XA9ivvlY/2LfemOwv9nfXP9/w3bOR6WaswblDKOAWHAg/7tkxo8DNwGBZqUF'))) 966 | 967 | 968 | def parse_gdi(filename, verbose=False): 969 | filename = os.path.realpath(filename) 970 | dirname = os.path.dirname(filename) 971 | 972 | try: 973 | with open(filename) as f: # if i.split() removes blank lines 974 | l = [i.split() for i in f.readlines() if i.split()] 975 | if not int(l[3][1]) == 45000: 976 | raise AssertionError( 977 | 'Invalid gdi file: track03 LBA should be 45000') 978 | except FileNotFoundError: 979 | print(f"File '{filename}' not found!") 980 | return None 981 | 982 | nbt = int(l[0][0]) 983 | 984 | gdi = [dict(filename=dirname + '/' + t[4], mode=int(t[3]), tnum=int(t[0]), lba=int(t[1]), 985 | ttype='audio' if t[2] == '0' else 'data' if t[2] == '4' else 'unknown') 986 | for t in l[1:]] 987 | 988 | gdi[2]['offset'] = 45000*2048 989 | gdi[2]['wormhole'] = [0, 45000*2048, 32*2048] 990 | 991 | if nbt > 3: 992 | gdi[nbt-1]['offset'] = 2048 * \ 993 | (gdi[nbt-1]['lba'] - get_filesize(gdi[2] 994 | ['filename'])//gdi[2]['mode'] - 45000) 995 | 996 | if verbose: 997 | print(f'\nParsed gdi file: {os.path.basename(filename)}') 998 | print(f'Base Directory: {dirname}') 999 | print(f'Number of tracks: {nbt}') 1000 | for j in gdi: 1001 | if j['ttype'] == 'data': 1002 | if j['tnum'] == 1: 1003 | tlabel = 'PC DATA' 1004 | elif j['tnum'] == nbt: 1005 | tlabel = 'GAME DATA' 1006 | else: 1007 | tlabel = 'TOC' 1008 | else: 1009 | tlabel = 'AUDIO' 1010 | print('\nLOW-DENSITY:\n' if j['tnum'] == 1011 | 1 else '\nHIGH-DENSITY:\n' if j['tnum'] == 3 else '') 1012 | print(f" {tlabel} track:") 1013 | print(f" Filename: {os.path.basename(j['filename'])}") 1014 | print(f" LBA: {j['lba']} ") 1015 | print(f" Mode: {j['mode']} bytes/sector") 1016 | if 'offset' in j: 1017 | print(f" Offset: {j['offset']//2048}") 1018 | if 'wormhole' in j: 1019 | print(f" WormHole: {[k//2048 for k in j['wormhole']]}") 1020 | print('') 1021 | 1022 | return gdi 1023 | 1024 | 1025 | def get_filesize(filename): 1026 | with open(filename) as f: 1027 | f.seek(0, 2) 1028 | return f.tell() 1029 | 1030 | 1031 | def UpdateLine(text): 1032 | """ 1033 | Allows to print successive messages over the last line. Line is 1034 | force to be 80 chars long to avoid display issues. 1035 | """ 1036 | #import sys 1037 | # if len(text) > 80: 1038 | # text = text[:80] 1039 | # if text[-1] == '\r': 1040 | # text = text[:-1] 1041 | #text += ' '*(80-len(text))+'\r' 1042 | # sys.stdout.write(text) 1043 | # sys.stdout.flush() 1044 | print(text) 1045 | 1046 | 1047 | def _copy_buffered(f1, f2, length=None, bufsize=1*1024*1024, closeOut=True): 1048 | """ 1049 | Copy istream f1 into ostream f2 in bufsize chunks 1050 | """ 1051 | if length is None: # By default it reads all the file 1052 | tmp = f1.tell() 1053 | f1.seek(0, 2) 1054 | length = f1.tell() 1055 | f1.seek(tmp, 0) 1056 | f2.seek(0, 0) 1057 | 1058 | for i in range(length//bufsize): 1059 | f2.write(f1.read(bufsize)) 1060 | f2.write(f1.read(length % bufsize)) 1061 | 1062 | # while length: 1063 | # chunk = min(length, bufsize) 1064 | # length = length - chunk 1065 | # data = f1.read(chunk) 1066 | # f2.write(data) 1067 | 1068 | if closeOut: 1069 | f2.close() 1070 | 1071 | 1072 | def _printUsage(pname='gditools.py'): 1073 | print(f'Usage: {pname} -i input_gdi [options]\n') 1074 | print(' -h, --help Display this help') 1075 | print(' -l, --list List all files in the filesystem and exit') 1076 | print(' -o [outdir] Output directory. Default: gdi folder') 1077 | print(' -s [filename] Create a sorttxt file with custom name') 1078 | print(' (It uses *data-folder* as prefix)') 1079 | print(' -b [ipname] Dump the ip.bin with custom name') 1080 | print(' -e [filename] Dump a single file from the filesystem') 1081 | print(' --extract-all Dump all the files in the *data-folder*') 1082 | print(' --data-folder [name] *data-folder* subfolder. Default: data') 1083 | print((' '*27 + '(__volume_label__ --> Use ISO9660 volume label)')) 1084 | print(' --sort-spacer [num] Sorttxt entries are sperated by num') 1085 | print(' --silent Minimal verbosity mode') 1086 | print(' [no option] Display gdi infos if not silent') 1087 | print('\n') 1088 | print('gditools.py by FamilyGuy, http://sourceforge.net/p/dcisotools/') 1089 | print(' Licensed under GPLv3, see licences folder.') 1090 | print('') 1091 | print('iso9660.py by Barney Gale, http://github.com/barneygale') 1092 | print(' Licensed under a BSD-based license, see licences folder.') 1093 | 1094 | 1095 | def main(argv): 1096 | progname = argv[0] 1097 | argv = argv[1:] 1098 | 1099 | inputfile = '' 1100 | outputpath = '' 1101 | sorttxtfile = '' 1102 | bootsectorfile = '' 1103 | extract = '' 1104 | silent = False 1105 | datafolder = 'data' 1106 | listFiles = False 1107 | sort_spacer = 1 1108 | try: 1109 | opts, args = getopt.getopt(argv, "hli:o:s:b:e:", 1110 | ['help', 'silent', 'list', 1111 | 'extract-all', 'data-folder=', 1112 | 'sort-spacer=']) 1113 | 1114 | except getopt.GetoptError: 1115 | _printUsage(progname) 1116 | sys.exit(2) 1117 | 1118 | options = [o[0] for o in opts] 1119 | 1120 | if not '-i' in options: 1121 | _printUsage(progname) 1122 | sys.exit() 1123 | 1124 | if '-h' in options: 1125 | _printUsage(progname) 1126 | sys.exit() 1127 | 1128 | if '--help' in options: 1129 | _printUsage(progname) 1130 | sys.exit() 1131 | 1132 | if '-l' in options: 1133 | listFiles = True 1134 | 1135 | if '--list' in options: 1136 | listFiles = True 1137 | 1138 | for opt, arg in opts: 1139 | if opt == '-i': 1140 | inputfile = arg 1141 | elif opt == '-o': 1142 | outputpath = arg 1143 | elif opt == '-s': 1144 | sorttxtfile = arg 1145 | elif opt == '-b': 1146 | bootsectorfile = arg 1147 | elif opt == '--silent': 1148 | silent = True 1149 | elif opt == '-e': 1150 | extract = arg 1151 | elif opt == '--extract-all': 1152 | extract = '__all__' 1153 | elif opt == '--data-folder': 1154 | datafolder = arg 1155 | elif opt == '--sort-spacer': 1156 | sort_spacer = arg 1157 | 1158 | try: 1159 | with GDIfile(inputfile, verbose=not silent) as gdi: 1160 | if listFiles: 1161 | print('Listing all files in the filesystem:\n') 1162 | gdi.print_files() 1163 | sys.exit() 1164 | 1165 | if outputpath: 1166 | if outputpath[-1] == '/': 1167 | outputpath = outputpath[:-1] 1168 | 1169 | gdi._dirname = os.path.abspath(outputpath) 1170 | 1171 | if not os.path.exists(gdi._dirname): 1172 | os.makedirs(gdi._dirname) 1173 | if not silent: 1174 | tmp_str = f'Created directory: {gdi._dirname}' 1175 | print((tmp_str + ' '*(80-len(tmp_str)))) 1176 | 1177 | if datafolder == '__volume_label__': 1178 | datafolder = gdi.get_volume_label() 1179 | 1180 | if sorttxtfile: 1181 | gdi.dump_sorttxt(filename=sorttxtfile, 1182 | prefix=datafolder, spacer=sort_spacer) 1183 | 1184 | if bootsectorfile: 1185 | gdi.dump_bootsector(filename=bootsectorfile) 1186 | 1187 | if extract: 1188 | if extract.lower() in ['__all__']: 1189 | if not silent: 1190 | print('\nDumping all files:') 1191 | gdi.dump_all_files(target=datafolder) 1192 | else: 1193 | gdi.dump_file(extract, target=gdi._dirname) 1194 | except GDIException: 1195 | print('Error: Invalid GDI file') 1196 | return 1197 | 1198 | 1199 | if __name__ == '__main__': 1200 | if len(sys.argv) > 1: 1201 | main(sys.argv) 1202 | else: 1203 | _printUsage(sys.argv[0]) 1204 | -------------------------------------------------------------------------------- /tools/iso9660.py: -------------------------------------------------------------------------------- 1 | import urllib.request 2 | import urllib.parse 3 | import urllib.error 4 | import struct 5 | from io import BytesIO 6 | 7 | 8 | class ISO9660IOError(IOError): 9 | def __init__(self, path): 10 | self.path = path 11 | 12 | def __str__(self): 13 | return "Path not found: %s" % self.path 14 | 15 | 16 | class ISO9660(object): 17 | def __init__(self, url): 18 | self._buff = None # input buffer 19 | self._root = None # root node 20 | self._pvd = {} # primary volume descriptor 21 | self._paths = [] # path table 22 | 23 | self._url = url 24 | self._get_sector = self._get_sector_url if url.startswith( 25 | 'http') else self._get_sector_file 26 | 27 | # Volume Descriptors 28 | sector = 0x10 29 | while True: 30 | self._get_sector(sector, 2048) 31 | sector += 1 32 | ty = self._unpack('B') 33 | 34 | if ty == 1: 35 | self._unpack_pvd() 36 | elif ty == 255: 37 | break 38 | else: 39 | continue 40 | 41 | # Path table 42 | l0 = self._pvd['path_table_size'] 43 | self._get_sector(self._pvd['path_table_l_loc'], l0) 44 | 45 | while l0 > 0: 46 | p = {} 47 | l1 = self._unpack('B') 48 | l2 = self._unpack('B') 49 | p['ex_loc'] = self._unpack('i') 181 | self._pvd['path_table_opt_m_loc'] = self._unpack('>i') 182 | _, self._root = self._unpack_record() # root directory record 183 | self._pvd['volume_set_identifer'] = self._unpack_string(128) 184 | self._pvd['publisher_identifier'] = self._unpack_string(128) 185 | self._pvd['data_preparer_identifier'] = self._unpack_string(128) 186 | self._pvd['application_identifier'] = self._unpack_string(128) 187 | self._pvd['copyright_file_identifier'] = self._unpack_string(38) 188 | self._pvd['abstract_file_identifier'] = self._unpack_string(36) 189 | self._pvd['bibliographic_file_identifier'] = self._unpack_string(37) 190 | self._pvd['volume_datetime_created'] = self._unpack_vd_datetime() 191 | self._pvd['volume_datetime_modified'] = self._unpack_vd_datetime() 192 | self._pvd['volume_datetime_expires'] = self._unpack_vd_datetime() 193 | self._pvd['volume_datetime_effective'] = self._unpack_vd_datetime() 194 | self._pvd['file_structure_version'] = self._unpack('B') 195 | 196 | ## 197 | # Unpack a directory record (a listing of a file or folder) 198 | ## 199 | 200 | def _unpack_record(self, read=0): 201 | l0 = self._unpack('B') 202 | 203 | if l0 == 0: 204 | return read+1, None 205 | 206 | l1 = self._unpack('B') 207 | 208 | d = dict() 209 | d['ex_loc'] = self._unpack_both('I') 210 | d['ex_len'] = self._unpack_both('I') 211 | d['datetime'] = self._unpack_dir_datetime() 212 | d['flags'] = self._unpack('B') 213 | d['interleave_unit_size'] = self._unpack('B') 214 | d['interleave_gap_size'] = self._unpack('B') 215 | d['volume_sequence'] = self._unpack_both('h') 216 | 217 | l2 = self._unpack('B') 218 | d['name'] = self._unpack_string(l2).split(';')[0] 219 | if d['name'] == '\x00': 220 | d['name'] = '' 221 | 222 | if l2 % 2 == 0: 223 | self._unpack('B') 224 | 225 | t = 34 + l2 - (l2 % 2) 226 | 227 | e = l0-t 228 | if e > 0: 229 | extra = self._unpack_raw(e) 230 | #print(f"record: {d}") 231 | return read+l0, d 232 | 233 | # Assuming d is a directory record, this generator yields its children 234 | def _unpack_dir_children(self, d): 235 | sector = d['ex_loc'] 236 | read = 0 237 | self._get_sector(sector, 2048) 238 | 239 | read, r_self = self._unpack_record(read) 240 | read, r_parent = self._unpack_record(read) 241 | 242 | while read < r_self['ex_len']: # Iterate over files in the directory 243 | if read % 2048 == 0: 244 | sector += 1 245 | self._get_sector(sector, 2048) 246 | read, data = self._unpack_record(read) 247 | 248 | if data == None: # end of directory listing 249 | to_read = 2048 - (read % 2048) 250 | self._unpack_raw(to_read) 251 | read += to_read 252 | else: 253 | yield data 254 | 255 | # Search for one child amongst the children 256 | def _search_dir_children(self, d, term): 257 | for e in self._unpack_dir_children(d): 258 | if e['name'] == term: 259 | return e 260 | 261 | raise ISO9660IOError(term) 262 | ## 263 | # Datatypes 264 | ## 265 | 266 | def _unpack_raw(self, l): 267 | return self._buff.read(l) 268 | 269 | # both-endian 270 | def _unpack_both(self, st): 271 | a = self._unpack('<'+st) 272 | b = self._unpack('>'+st) 273 | assert a == b 274 | return a 275 | 276 | def _unpack_string(self, l): 277 | return self._buff.read(l).rstrip(b' ').decode('utf-8') 278 | 279 | def _unpack(self, st): 280 | if st[0] not in ('<', '>'): 281 | st = '<' + st 282 | d = struct.unpack(st, self._buff.read(struct.calcsize(st))) 283 | if len(st) == 2: 284 | return d[0] 285 | else: 286 | return d 287 | 288 | def _unpack_vd_datetime(self): 289 | return self._unpack_raw(17) # TODO 290 | 291 | def _unpack_dir_datetime(self): 292 | return self._unpack_raw(7) # TODO 293 | 294 | 295 | if __name__ == '__main__': 296 | import sys 297 | if len(sys.argv) < 2: 298 | print("usage: python iso9660.py isourl [path]") 299 | else: 300 | iso_path = sys.argv[1] 301 | ret_path = sys.argv[2] if len(sys.argv) > 2 else None 302 | cd = ISO9660(iso_path) 303 | if ret_path: 304 | sys.stdout.write(cd.get_file(ret_path)) 305 | else: 306 | for path in cd.tree(): 307 | print(path) 308 | --------------------------------------------------------------------------------