ProDOS-Utilities/prodos/file.go

455 lines
12 KiB
Go
Raw Permalink Normal View History

// Copyright Terence J. Boldt (c)2021-2022
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
// This file provides access to read, write and delete
// files on a ProDOS drive image
2021-06-06 12:00:20 +00:00
package prodos
import (
2022-12-30 11:12:41 +00:00
"encoding/binary"
2021-06-30 04:04:59 +00:00
"errors"
"fmt"
"io"
2022-12-30 11:12:41 +00:00
"os"
"path/filepath"
2021-06-06 12:00:20 +00:00
"strings"
2021-06-26 01:15:20 +00:00
"time"
2021-06-06 12:00:20 +00:00
)
// LoadFile loads in a file from a ProDOS volume into a byte array
func LoadFile(reader io.ReaderAt, path string) ([]byte, error) {
fileEntry, err := GetFileEntry(reader, path)
2021-06-30 04:04:59 +00:00
if err != nil {
return nil, err
}
2021-06-12 02:43:35 +00:00
blockList, err := getDataBlocklist(reader, fileEntry)
2021-07-02 10:54:25 +00:00
if err != nil {
return nil, err
}
2021-06-12 02:43:35 +00:00
buffer := make([]byte, fileEntry.EndOfFile)
for i := 0; i < len(blockList); i++ {
block, err := ReadBlock(reader, blockList[i])
if err != nil {
return nil, err
}
2021-06-12 02:43:35 +00:00
for j := 0; j < 512 && i*512+j < fileEntry.EndOfFile; j++ {
buffer[i*512+j] = block[j]
}
}
2021-06-30 04:04:59 +00:00
return buffer, nil
2021-06-12 02:43:35 +00:00
}
2022-12-30 11:12:41 +00:00
// WriteFileFromFile writes a file to a ProDOS volume from a host file
func WriteFileFromFile(readerWriter ReaderWriterAt, pathName string, fileType int, auxType int, inFileName string) error {
inFile, err := os.ReadFile(inFileName)
if err != nil {
return err
}
if auxType == 0 && fileType == 0 {
auxType, fileType, inFile, err = convertFileByType(inFileName, inFile)
if err != nil {
return err
}
}
if len(pathName) == 0 {
_, pathName = filepath.Split(inFileName)
pathName = strings.ToUpper(pathName)
ext := filepath.Ext(pathName)
if len(ext) > 0 {
switch ext {
case ".SYS", ".TXT", ".BAS", ".BIN":
pathName = strings.TrimSuffix(pathName, ext)
}
}
}
return WriteFile(readerWriter, pathName, fileType, auxType, inFile)
}
func convertFileByType(inFileName string, inFile []byte) (int, int, []byte, error) {
fileType := 0x06 // default to BIN
auxType := 0x2000 // default to $2000
var err error
// Check for an AppleSingle file as produced by cc65
if // Magic number
binary.BigEndian.Uint32(inFile[0x00:]) == 0x00051600 &&
// Version number
binary.BigEndian.Uint32(inFile[0x04:]) == 0x00020000 &&
// Number of entries
binary.BigEndian.Uint16(inFile[0x18:]) == 0x0002 &&
// Data Fork ID
binary.BigEndian.Uint32(inFile[0x1A:]) == 0x00000001 &&
// Offset
binary.BigEndian.Uint32(inFile[0x1E:]) == 0x0000003A &&
// Length
binary.BigEndian.Uint32(inFile[0x22:]) == uint32(len(inFile))-0x3A &&
// ProDOS File Info ID
binary.BigEndian.Uint32(inFile[0x26:]) == 0x0000000B &&
// Offset
binary.BigEndian.Uint32(inFile[0x2A:]) == 0x00000032 &&
// Length
binary.BigEndian.Uint32(inFile[0x2E:]) == 0x00000008 {
fileType = int(binary.BigEndian.Uint16(inFile[0x34:]))
auxType = int(binary.BigEndian.Uint32(inFile[0x36:]))
inFile = inFile[0x3A:]
} else {
// use extension to determine file type
ext := strings.ToUpper(filepath.Ext(inFileName))
switch ext {
case ".BAS":
inFile, err = ConvertTextToBasic(string(inFile))
fileType = 0xFC
auxType = 0x0801
if err != nil {
return 0, 0, nil, err
}
case ".SYS":
fileType = 0xFF
auxType = 0x2000
case ".BIN":
fileType = 0x06
auxType = 0x2000
case ".TXT":
inFile = []byte(strings.ReplaceAll(strings.ReplaceAll(string(inFile), "\r\n", "r"), "\n", "\r"))
fileType = 0x04
auxType = 0x0000
}
}
return auxType, fileType, inFile, err
}
2022-01-23 22:30:18 +00:00
// WriteFile writes a file to a ProDOS volume from a byte array
func WriteFile(readerWriter ReaderWriterAt, path string, fileType int, auxType int, buffer []byte) error {
2021-06-26 01:15:20 +00:00
directory, fileName := GetDirectoryAndFileNameFromPath(path)
existingFileEntry, _ := GetFileEntry(readerWriter, path)
2021-06-30 12:22:08 +00:00
if existingFileEntry.StorageType != StorageDeleted {
DeleteFile(readerWriter, path)
2021-06-30 12:22:08 +00:00
}
2021-06-26 01:15:20 +00:00
// get list of blocks to write file to
blockList, err := createBlockList(readerWriter, len(buffer))
if err != nil {
return err
}
2021-06-26 01:15:20 +00:00
// seedling file
if len(buffer) <= 0x200 {
WriteBlock(readerWriter, blockList[0], buffer)
2021-06-26 01:15:20 +00:00
}
// sapling file needs index block
if len(buffer) > 0x200 && len(buffer) <= 0x20000 {
writeSaplingFile(readerWriter, buffer, blockList)
2021-06-26 01:15:20 +00:00
}
// tree file needs master index and index blocks
if len(buffer) > 0x20000 && len(buffer) <= 0x1000000 {
writeTreeFile(readerWriter, buffer, blockList)
}
if len(buffer) > 0x1000000 {
return errors.New("files > 16MB not supported by ProDOS")
2021-06-30 12:22:08 +00:00
}
2021-06-26 01:15:20 +00:00
updateVolumeBitmap(readerWriter, blockList)
2021-06-30 04:04:59 +00:00
2021-06-26 01:15:20 +00:00
// add file entry to directory
fileEntry, err := getFreeFileEntryInDirectory(readerWriter, directory)
2021-07-02 10:54:25 +00:00
if err != nil {
return err
}
2021-06-26 01:15:20 +00:00
fileEntry.FileName = fileName
fileEntry.BlocksUsed = len(blockList)
fileEntry.CreationTime = time.Now()
fileEntry.ModifiedTime = time.Now()
2021-06-27 11:53:50 +00:00
fileEntry.AuxType = auxType
2021-06-26 01:15:20 +00:00
fileEntry.EndOfFile = len(buffer)
2021-06-27 11:53:50 +00:00
fileEntry.FileType = fileType
2021-06-26 01:15:20 +00:00
fileEntry.KeyPointer = blockList[0]
2021-06-30 04:04:59 +00:00
fileEntry.Access = 0b11100011
2021-06-30 12:22:08 +00:00
if len(blockList) == 1 {
fileEntry.StorageType = StorageSeedling
} else if len(blockList) <= 257 {
fileEntry.StorageType = StorageSapling
} else {
fileEntry.StorageType = StorageTree
}
writeFileEntry(readerWriter, fileEntry)
2021-06-30 12:22:08 +00:00
// increment file count
directoryHeaderBlock, err := ReadBlock(readerWriter, fileEntry.HeaderPointer)
if err != nil {
return err
}
2021-06-30 12:22:08 +00:00
directoryHeader := parseDirectoryHeader(directoryHeaderBlock, fileEntry.HeaderPointer)
directoryHeader.ActiveFileCount++
writeDirectoryHeader(readerWriter, directoryHeader)
2021-06-30 12:22:08 +00:00
return nil
}
2022-01-23 22:30:18 +00:00
// DeleteFile deletes a file from a ProDOS volume
func DeleteFile(readerWriter ReaderWriterAt, path string) error {
fileEntry, err := GetFileEntry(readerWriter, path)
2021-06-30 12:22:08 +00:00
if err != nil {
return errors.New("file not found")
2021-06-30 12:22:08 +00:00
}
if fileEntry.StorageType == StorageDeleted {
return errors.New("file already deleted")
2021-06-30 12:22:08 +00:00
}
2021-07-02 11:58:06 +00:00
if fileEntry.StorageType == StorageDirectory {
return errors.New("directory deletion not supported")
2021-07-02 11:58:06 +00:00
}
2021-06-30 12:22:08 +00:00
// free the blocks
blocks, err := getBlocklist(readerWriter, fileEntry)
if err != nil {
return err
}
volumeBitmap, err := ReadVolumeBitmap(readerWriter)
2021-07-02 10:54:25 +00:00
if err != nil {
return err
}
2021-06-30 12:22:08 +00:00
for i := 0; i < len(blocks); i++ {
freeBlockInVolumeBitmap(volumeBitmap, blocks[i])
}
writeVolumeBitmap(readerWriter, volumeBitmap)
2021-06-30 12:22:08 +00:00
// decrement the directory entry count
directoryBlock, err := ReadBlock(readerWriter, fileEntry.HeaderPointer)
if err != nil {
return err
}
2021-06-30 12:22:08 +00:00
directoryHeader := parseDirectoryHeader(directoryBlock, fileEntry.HeaderPointer)
2021-06-26 01:15:20 +00:00
2021-06-30 12:22:08 +00:00
directoryHeader.ActiveFileCount--
writeDirectoryHeader(readerWriter, directoryHeader)
2021-06-30 12:22:08 +00:00
// zero out directory entry
fileEntry.StorageType = 0
fileEntry.FileName = ""
writeFileEntry(readerWriter, fileEntry)
2021-06-30 04:04:59 +00:00
return nil
2021-06-26 01:15:20 +00:00
}
2022-01-23 22:30:18 +00:00
// GetDirectoryAndFileNameFromPath gets the directory and filename from a path
2021-07-02 10:54:25 +00:00
func GetDirectoryAndFileNameFromPath(path string) (string, string) {
path = strings.ToUpper(path)
paths := strings.Split(path, "/")
var directoryBuilder strings.Builder
for i := 1; i < len(paths)-1; i++ {
directoryBuilder.WriteString("/")
directoryBuilder.WriteString(paths[i])
}
directory := directoryBuilder.String()
fileName := paths[len(paths)-1]
return directory, fileName
}
func updateVolumeBitmap(readerWriter ReaderWriterAt, blockList []int) error {
volumeBitmap, err := ReadVolumeBitmap(readerWriter)
if err != nil {
fmt.Printf("%s", err)
return err
}
for i := 0; i < len(blockList); i++ {
markBlockInVolumeBitmap(volumeBitmap, blockList[i])
}
return writeVolumeBitmap(readerWriter, volumeBitmap)
}
func writeSaplingFile(writer io.WriterAt, buffer []byte, blockList []int) {
// write index block with pointers to data blocks
indexBuffer := make([]byte, 512)
for i := 0; i < 256; i++ {
if i < len(blockList)-1 {
indexBuffer[i] = byte(blockList[i+1] & 0x00FF)
indexBuffer[i+256] = byte(blockList[i+1] >> 8)
}
}
WriteBlock(writer, blockList[0], indexBuffer)
// write all data blocks
blockBuffer := make([]byte, 512)
blockPointer := 0
blockIndexNumber := 1
for i := 0; i < len(buffer); i++ {
blockBuffer[blockPointer] = buffer[i]
if blockPointer == 511 {
WriteBlock(writer, blockList[blockIndexNumber], blockBuffer)
blockPointer = 0
blockIndexNumber++
} else if i == len(buffer)-1 {
for j := blockPointer; j < 512; j++ {
blockBuffer[j] = 0
}
WriteBlock(writer, blockList[blockIndexNumber], blockBuffer)
} else {
blockPointer++
}
}
}
func writeTreeFile(writer io.WriterAt, buffer []byte, blockList []int) {
}
2021-07-02 10:54:25 +00:00
// Returns all blocks, including index blocks
func getBlocklist(reader io.ReaderAt, fileEntry FileEntry) ([]int, error) {
2021-06-12 02:43:35 +00:00
blocks := make([]int, fileEntry.BlocksUsed)
switch fileEntry.StorageType {
case StorageSeedling:
blocks[0] = fileEntry.KeyPointer
2021-07-02 10:54:25 +00:00
return blocks, nil
2021-06-12 02:43:35 +00:00
case StorageSapling:
index, err := ReadBlock(reader, fileEntry.KeyPointer)
if err != nil {
return nil, err
}
2021-06-30 04:04:59 +00:00
blocks[0] = fileEntry.KeyPointer
2021-06-30 12:22:08 +00:00
for i := 0; i < fileEntry.BlocksUsed-1; i++ {
blocks[i+1] = int(index[i]) + int(index[i+256])*256
2021-06-12 02:43:35 +00:00
}
2021-07-02 10:54:25 +00:00
return blocks, nil
2021-06-12 02:43:35 +00:00
case StorageTree:
masterIndex, err := ReadBlock(reader, fileEntry.KeyPointer)
if err != nil {
return nil, err
}
2021-06-30 04:04:59 +00:00
blocks[0] = fileEntry.KeyPointer
2021-06-12 02:43:35 +00:00
for i := 0; i < 128; i++ {
index, err := ReadBlock(reader, int(masterIndex[i])+int(masterIndex[i+256])*256)
if err != nil {
return nil, err
}
2021-06-12 02:43:35 +00:00
for j := 0; j < 256 && i*256+j < fileEntry.BlocksUsed; j++ {
2021-07-02 10:54:25 +00:00
if (int(index[j]) + int(index[j+256])*256) == 0 {
return blocks, nil
}
2021-06-12 02:43:35 +00:00
blocks[i*256+j] = int(index[j]) + int(index[j+256])*256
}
}
}
return nil, errors.New("unsupported file storage type")
2021-07-02 10:54:25 +00:00
}
func getDataBlocklist(reader io.ReaderAt, fileEntry FileEntry) ([]int, error) {
2021-07-02 10:54:25 +00:00
switch fileEntry.StorageType {
case StorageSeedling:
blocks := make([]int, 1)
blocks[0] = fileEntry.KeyPointer
return blocks, nil
case StorageSapling:
blocks := make([]int, fileEntry.BlocksUsed-1)
index, err := ReadBlock(reader, fileEntry.KeyPointer)
if err != nil {
return nil, err
}
2021-07-02 10:54:25 +00:00
for i := 0; i < fileEntry.BlocksUsed-1; i++ {
blocks[i] = int(index[i]) + int(index[i+256])*256
}
return blocks, nil
// case StorageTree:
// blocks := make([]int, fileEntry.BlocksUsed-fileEntry.BlocksUsed/256-1)
// masterIndex := ReadBlock(reader, fileEntry.KeyPointer)
// for i := 0; i < 128; i++ {
// blockNumber := 0
// blocks[j] = int(index[i]) + int(index[i+256])*256
// }
2021-07-02 10:54:25 +00:00
}
return nil, errors.New("unsupported file storage type")
2021-06-12 02:43:35 +00:00
}
func createBlockList(reader io.ReaderAt, fileSize int) ([]int, error) {
2021-06-26 01:15:20 +00:00
numberOfBlocks := fileSize / 512
//fmt.Printf("Number of blocks %d\n", numberOfBlocks)
2021-06-26 01:15:20 +00:00
if fileSize%512 > 0 {
//fmt.Printf("Adding block for partial usage\n")
2021-06-26 01:15:20 +00:00
numberOfBlocks++
}
2021-06-26 01:15:20 +00:00
if fileSize > 0x200 && fileSize <= 0x20000 {
//fmt.Printf("Adding index block for sapling file\n")
2021-06-26 01:15:20 +00:00
numberOfBlocks++ // add index block
}
2022-12-30 11:12:41 +00:00
if fileSize > 0x20000 && fileSize <= 0x1000000 {
//fmt.Printf("Tree file\n")
// add index blocks for each 256 blocks
numberOfBlocks += numberOfBlocks / 256
2021-06-26 01:15:20 +00:00
// add index block for any remaining blocks
if numberOfBlocks%256 > 0 {
2021-06-26 01:15:20 +00:00
numberOfBlocks++
}
// add master index block
numberOfBlocks++
2021-06-06 12:00:20 +00:00
}
if fileSize > 0x1000000 {
return nil, errors.New("file size too large")
}
volumeBitmap, err := ReadVolumeBitmap(reader)
if err != nil {
return nil, err
}
//fmt.Printf("findFreeBlocks %d\n", numberOfBlocks)
2021-06-29 02:26:20 +00:00
blockList := findFreeBlocks(volumeBitmap, numberOfBlocks)
2021-06-06 12:00:20 +00:00
return blockList, nil
2021-06-26 01:15:20 +00:00
}
2022-12-31 14:14:27 +00:00
// GetFileEntry returns a file entry for the given path
func GetFileEntry(reader io.ReaderAt, path string) (FileEntry, error) {
2021-06-26 01:15:20 +00:00
directory, fileName := GetDirectoryAndFileNameFromPath(path)
_, _, fileEntries, err := ReadDirectory(reader, directory)
if err != nil {
return FileEntry{}, err
}
2021-06-06 12:00:20 +00:00
2021-06-30 12:22:08 +00:00
if fileEntries == nil || len(fileEntries) == 0 {
return FileEntry{}, errors.New("file entry not found")
2021-06-06 12:00:20 +00:00
}
var fileEntry FileEntry
for i := 0; i < len(fileEntries); i++ {
if fileEntries[i].FileName == fileName {
fileEntry = fileEntries[i]
}
}
2021-06-30 12:22:08 +00:00
if fileEntry.StorageType == StorageDeleted {
return FileEntry{}, errors.New("file not found")
2021-06-30 12:22:08 +00:00
}
2021-06-30 04:04:59 +00:00
return fileEntry, nil
2021-06-12 02:43:35 +00:00
}