Don't link with Carbon.framework.
[MacTF.git] / TFUSBControllerCommunicationBlock.m
blobc3b2cfaad556e4b1e59389927ee76f343649086f
1 //
2 //  TFUSBControllerCommunicationBlock.h
3 //  MacTF
4 //
5 //  Created by Kalle Olavi Niemitalo on 2007-10-23, based on:
6 //    TFUSBController.m
7 //    MacTF
8 //    Created by Nathan Oates on Sun Aug 01 2004.
9 //    Copyright (c) 2004-7 Nathan Oates nathan@noates.com All rights reserved.
10 //  May also include parts of:
11 //    uproar 0.1
12 //    Copyright (c) 2001 Kasima Tharnpipitchai <me@kasima.org>
14 // This source code is free software; you can redistribute it and/or
15 // modify it under the terms of the GNU Public License as published
16 // by the Free Software Foundation; either version 2 of the License,
17 // or (at your option) any later version.
19 // This source code is distributed in the hope that it will be useful,
20 // but WITHOUT ANY WARRANTY; without even the implied warranty of
21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
22 // Please refer to the GNU Public License for more details.
24 // You should have received a copy of the GNU Public License along with
25 // this source code; if not, write to:
26 // Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #import "TFUSBControllerCommunicationBlock.h"
29 #import "Errors.h"
31 @implementation TFUSBController (CommunicationBlock)
33 // ---------------------------------------------------------------------------
34 #pragma mark Framing of communication blocks
35 // ---------------------------------------------------------------------------
37 - (UInt16) findCRC:(const UInt8*)p length:(size_t)n
39         UInt16 m_crc16 = 0x0000;
40         static const UInt16 crc16Tbl[256] = {
41                 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
42                 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
43                 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
44                 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
45                 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
46                 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
47                 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
48                 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
49                 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
50                 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
51                 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
52                 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
53                 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
54                 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
55                 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
56                 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
57                 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
58                 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
59                 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
60                 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
61                 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
62                 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
63                 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
64                 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
65                 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
66                 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
67                 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
68                 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
69                 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
70                 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
71                 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
72                 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
73         };
74         size_t i;       
75         for(i = 0; i < n; i++)
76                         m_crc16 = (m_crc16 >> 8) ^ crc16Tbl[*p++ ^ (m_crc16 & 0xFF)];
77         return m_crc16;
80 - (NSMutableData*) swap:(NSData*)inData {
81         size_t len = [inData length];
82         size_t uneven = 0;
83         if (len % 2 != 0) {
84                 uneven = 1; // prepare space for padding
85         }
86         NSMutableData* outData = [NSMutableData dataWithLength:len+uneven];
87         swab([inData bytes], [outData mutableBytes], len-uneven);
88         if (uneven) {
89                 // swab() requires an even length.  The last byte was not given to
90                 // swab() above, so copy it separately.  Also clear the byte just
91                 // before the last one, even though the dataWithLength: class method
92                 // should have already cleared it.
93                 unsigned char final[2] = { 0, 0 };
94                 [inData getBytes:&final[1] range:(NSRange){len-1,1}];
95                 [outData replaceBytesInRange:(NSRange){len-1,2} withBytes:final];
96         }
97         return outData;
100 - (NSData*) prepareCommand:(TopfieldUSBCmd)cmd withData:(NSData*)inData {
101         NSMutableData* block = [NSMutableData dataWithLength:8];
102         if (inData != nil)
103                 [block appendData:inData];
104         size_t blockLength = [block length];
105         if (blockLength > 0xFFFF)
106                 return nil; // wouldn't fit in UInt16
108         UInt32 cmd_bigendian = EndianU32_NtoB(cmd);
109         [block replaceBytesInRange:(NSRange){4,4} withBytes:&cmd_bigendian];
111         UInt16 crc = [self findCRC:(const UInt8*)[block bytes]+4 length:blockLength-4];
112         UInt16 crc_bigendian = EndianU16_NtoB(crc);
113         [block replaceBytesInRange:(NSRange){2,2} withBytes:&crc_bigendian];
115         UInt16 blockLength_bigendian = EndianU16_NtoB(blockLength);
116         [block replaceBytesInRange:(NSRange){0,2} withBytes:&blockLength_bigendian];
118         return [self swap:block];
121 // Check the size and CRC of a received communication block.
122 - (BOOL) isCommunicationBlockValid:(NSData*)block
123         error:(NSError**)errorOut ecode:(TopfieldUSBEcode*)ecodeOut
125         NSError* error = nil;
126         TopfieldUSBEcode ecode = USB_OK;
128         if (block == nil) {
129                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
130                         @"ERR_COMMUNICATION_BLOCK_MISSING",
131                         nil, [NSBundle mainBundle],
132                         @"The PVR did not respond",
133                         @"A communication block was expected but not received");
134                 error = [NSError errorWithDomain:MacTFErrorDomain
135                         code:MACTF_ERR_COMMUNICATION_BLOCK_MISSING
136                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
137                                 forKey:NSLocalizedDescriptionKey]];
138                 ecode = USB_Err_RunFail;
139                 goto ret;
140         }
142         size_t length = [block length];
143         if (length < 8) {
144                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
145                         @"ERR_COMMUNICATION_BLOCK_LT_8_BYTES",
146                         nil, [NSBundle mainBundle],
147                         @"Received only %u bytes; eight are required",
148                         @"Topfield's USB protocol requires an 8-byte header in every"
149                          " communication block but the received block was too short"
150                          " for that");
151                 localizedDescription = [NSString stringWithFormat:localizedDescription,
152                         (unsigned) length];
153                 error = [NSError errorWithDomain:MacTFErrorDomain
154                         code:MACTF_ERR_COMMUNICATION_BLOCK_LT_8_BYTES
155                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
156                                 forKey:NSLocalizedDescriptionKey]];
157                 ecode = USB_Err_Size;
158                 goto ret;
159         }
161         UInt16 crc16_bigendian;
162         [block getBytes:&crc16_bigendian range:(NSRange){2,2}];
163         UInt16 crc = EndianU16_BtoN(crc16_bigendian);
164         UInt16 calcCrc = [self findCRC:(const UInt8*)[block bytes]+4
165                 length:length-4];
166         if (crc != calcCrc) {
167                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
168                         @"ERR_COMMUNICATION_BLOCK_CRC",
169                         nil, [NSBundle mainBundle],
170                         @"CRC mismatch in received data.  The header claims %#.4x but"
171                          " the data computes to %#.4x.",
172                         @"CRC mismatch in a received communication block");
173                 localizedDescription = [NSString stringWithFormat:localizedDescription,
174                         (unsigned) crc, (unsigned) calcCrc];
175                 error = [NSError errorWithDomain:MacTFErrorDomain
176                                         code:MACTF_ERR_COMMUNICATION_BLOCK_CRC
177                                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
178                                                 forKey:NSLocalizedDescriptionKey]];
179                 ecode = USB_Err_Crc;
180                 goto ret;
181         }
183 ret:
184         if (ecodeOut != NULL)
185                 *ecodeOut = ecode;
186         if (errorOut != NULL)
187                 *errorOut = error;
188         return error == nil;
191 // Get the cmd field from a communication block.  The caller must already have
192 // checked the length of the block.  (Use [self checkCommunicationBlock:block].)
193 // The returned value is typically in enum TopfieldUSBCmd, but other values can
194 // also be received, so this method returns the value as UInt32 instead.
195 - (UInt32) cmdFromCommunicationBlock:(NSData*)block {
196         UInt32 cmd_bigendian;
197         [block getBytes:&cmd_bigendian range:(NSRange){4,4}];
198         return EndianU32_BtoN(cmd_bigendian);
201 // ---------------------------------------------------------------------------
202 #pragma mark Common ingredients
203 // ---------------------------------------------------------------------------
205 - (BOOL) appendToData:(NSMutableData*)data fname:(NSString*)fname {
206         NSData* fnameData = [fname dataUsingEncoding:NSISOLatin1StringEncoding];
207         if (fnameData == nil) // fname contains characters unsupported by encoding
208                 return NO;
209         const size_t terminatorSize = 1;
210         [data appendData:fnameData];
211         [data increaseLengthBy:terminatorSize]; // fills with 0x00
212         return YES;
215 - (BOOL) appendToData:(NSMutableData*)data sizeAndFname:(NSString*)fname {
216         NSData* fnameData = [fname dataUsingEncoding:NSISOLatin1StringEncoding];
217         if (fnameData == nil) // fname contains characters unsupported by encoding
218                 return NO;
219         const size_t terminatorSize = 1;
220         const size_t nameSize = [fnameData length] + terminatorSize;
221         if (nameSize > 0xFFFF) // size would not fit in UInt16
222                 return NO;
223         const UInt16 nameSize_bigendian = EndianU16_NtoB(nameSize);
224         [data appendBytes:&nameSize_bigendian length:2];
225         [data appendData:fnameData];
226         [data increaseLengthBy:terminatorSize]; // fills with 0x00
227         return YES;
230 - (NSString*) fnameForFile:(NSString*)file atPath:(NSString*)path {
231         return [NSString stringWithFormat:@"%@\\%@", path, file];
234 // ---------------------------------------------------------------------------
235 #pragma mark Preparing communication blocks for various commands
236 // ---------------------------------------------------------------------------
238 - (NSData*) prepareFailWithECode:(TopfieldUSBEcode)ecode {
239         const UInt32 ecode_bigendian = EndianU32_NtoB(ecode);
240         NSData* data = [NSData dataWithBytes:&ecode_bigendian length:4];
241         if (data == nil) // out of memory presumably
242                 return nil;
243         return [self prepareCommand:USB_Fail withData:data];
246 - (NSData*) prepareSuccess {
247         return [self prepareCommand:USB_Success withData:nil];
250 - (NSData*) prepareCancel {
251         return [self prepareCommand:USB_Cancel withData:nil];
254 // Prepare a communication block that asks the Toppy to list the files
255 // in a directory.  Return the communication block, or nil on error.
256 - (NSData*) prepareCmdHddDirWithPath:(NSString*)path {
257         NSMutableData* cmdData = [NSMutableData data];
258         if (cmdData == nil) // out of memory presumably
259                 return nil;
260         if (![self appendToData:cmdData fname:path])
261                 return nil;
262         return [self prepareCommand:USB_CmdHddDir withData:cmdData];
265 - (NSData*) prepareCmdHddFileSendWithDirection:(UInt8)direction
266                 fname:(NSString*)fname offset:(UInt64)offset
268         NSMutableData *cmdData = [NSMutableData dataWithBytes:&direction length:1];
269         if (cmdData == nil) // out of memory presumably
270                 return nil;
271         if (![self appendToData:cmdData sizeAndFname:fname])
272                 return nil;
273         const UInt64 offset_bigendian = EndianU64_NtoB(offset);
274         [cmdData appendBytes:&offset_bigendian length:8];
275         return [self prepareCommand:USB_CmdHddFileSend withData:cmdData];
278 - (NSData*) prepareDataHddFileEnd {
279         return [self prepareCommand:USB_DataHddFileEnd withData:nil];
282 - (NSData*) prepareCmdTurboWithMode:(SInt32)mode {
283         const SInt32 mode_bigendian = EndianS32_NtoB(mode);
284         NSData* cmdData = [NSData dataWithBytes:&mode_bigendian length:4];
285         if (cmdData == nil) // out of memory presumably
286                 return nil;
287         return [self prepareCommand:USB_CmdTurbo withData:cmdData];
290 - (NSData*) prepareCmdHddDelWithFname:(NSString*)fname {
291         NSMutableData* cmdData = [NSMutableData data];
292         if (cmdData == nil) // out of memory presumably
293                 return nil;
294         if (![self appendToData:cmdData fname:fname])
295                 return nil;
296         return [self prepareCommand:USB_CmdHddDel withData:cmdData];
299 - (NSData*) prepareCmdHddRenameFromFname:(NSString*)oldFname toFname:(NSString*)newFname {
300         NSMutableData* cmdData = [NSMutableData data];
301         if (cmdData == nil) // out of memory presumably
302                 return nil;
303         if (![self appendToData:cmdData sizeAndFname:oldFname])
304                 return nil;
305         if (![self appendToData:cmdData sizeAndFname:newFname])
306                 return nil;
307         return [self prepareCommand:USB_CmdHddRename withData:cmdData];
310 - (NSData*) prepareCmdHddCreateDirWithFname:(NSString*)fname {
311         NSMutableData* cmdData = [NSMutableData data];
312         if (cmdData == nil) // out of memory presumably
313                 return nil;
314         if (![self appendToData:cmdData fname:fname])
315                 return nil;
316         return [self prepareCommand:USB_CmdHddCreateDir withData:cmdData];
319 @end