aboutsummaryrefslogtreecommitdiff
path: root/Minecraft.Client/PS3/Network/SonyRemoteStorage_PS3.cpp
blob: ab7b47703cbf8fbdcceced85abe9d081b03304d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#include "stdafx.h"

#include "SonyRemoteStorage_PS3.h"
#include <stdio.h>
#include <string>
#include <stdlib.h>
// #include <cell/sysmodule.h>
// #include <cell/http.h>
// #include <cell/ssl.h>
// #include <netex/net.h>
// #include <netex/libnetctl.h>
// #include <np.h>
// #include <sysutil/sysutil_common.h>
// #include <sys/timer.h>
// #include <sys/paths.h>
// #include <sysutil\sysutil_savedata.h>



// 4J-PB - ticketing changed to our SCEE product id
#define TICKETING_SERVICE_ID "EP4433-NPEB01899_00" //"EP9009-NPWA00114_00"
#define CLIENT_ID "969e9d21-527c-4c22-b539-f8e479f690bc"




void SonyRemoteStorage_PS3::npauthhandler(int event, int result, void *arg)
{
#ifdef __PS3__
	if (event != SCE_NP_MANAGER_EVENT_GOT_TICKET || result <= 0)
	{
		app.DebugPrintf("Could not retrieve ticket: 0x%x\n", result);
	}
	else
	{
		psnTicketSize = result;
		psnTicket = malloc(psnTicketSize);
<<<<<<< HEAD
		if (psnTicket == nullptr) 
=======
		if (psnTicket == NULL)
>>>>>>> origin/main
		{
			app.DebugPrintf("Failed to allocate for ticket\n");
		}

		int ret = sceNpManagerGetTicket(psnTicket, &psnTicketSize);
		if (ret < 0)
		{
			app.DebugPrintf("Could not retrieve ticket: 0x%x\n", ret);
			free(psnTicket);
			psnTicket = 0;
			return;
		}
	}
	m_waitingForTicket = false;
#endif
}

int SonyRemoteStorage_PS3::initPreconditions()
{
	int ret = 0;

	SceNpId npId;

	ret = sceNpManagerGetNpId(&npId);
	if(ret < 0)
	{
		return ret;
	}
	SceNpTicketVersion ticketVersion;
	ticketVersion.major = 3;
	ticketVersion.minor = 0;
	ret = sceNpManagerRequestTicket2(&npId, &ticketVersion, TICKETING_SERVICE_ID, NULL, 0, NULL, 0);
	if(ret < 0)
	{
		return ret;
	}
	m_waitingForTicket = true;
	while(m_waitingForTicket)
	{
		cellSysutilCheckCallback();
		sys_timer_usleep(50000); //50 milliseconds.
	}
	if(psnTicket == nullptr)
		return -1;

	return 0;
}

void SonyRemoteStorage_PS3::staticInternalCallback(const SceRemoteStorageEvent event, int32_t retCode, void * userData)
{
	static_cast<SonyRemoteStorage_PS3 *>(userData)->internalCallback(event, retCode);
}

void SonyRemoteStorage_PS3::internalCallback(const SceRemoteStorageEvent event, int32_t retCode)
{
	m_lastErrorCode = retCode;

	switch(event)
	{
	case ERROR_OCCURRED:
		app.DebugPrintf("An error occurred with retCode: 0x%x \n", retCode);
// 		shutdown();				// removed, as the remote storage lib now tries to reconnect if an error has occurred
		m_status = e_error;
		runCallback();
		m_bTransferStarted = false;
		break;

	case GET_DATA_RESULT:
		if(retCode >= 0)
		{
			app.DebugPrintf("Get Data success \n");
			m_status = e_getDataSucceeded;
		}
		else
		{
			app.DebugPrintf("An error occurred while Get Data was being processed. retCode: 0x%x \n", retCode);
			m_status = e_error;
		}
		runCallback();
		m_bTransferStarted = false;
		break;

	case GET_DATA_PROGRESS:
		app.DebugPrintf("Get data progress: %i%%\n", retCode);
		m_status = e_getDataInProgress;
		m_dataProgress = retCode;
		m_startTime = System::currentTimeMillis();
		break;

	case GET_STATUS_RESULT:
		if(retCode >= 0)
		{
			app.DebugPrintf("Get Status success \n");
			app.DebugPrintf("Remaining Syncs for this user: %llu\n", outputGetStatus->remainingSyncs);
			app.DebugPrintf("Number of files on the cloud: %d\n", outputGetStatus->numFiles);
			for(int i = 0; i < outputGetStatus->numFiles; i++)
			{
				app.DebugPrintf("\n*** File %d information: ***\n", (i + 1));
				app.DebugPrintf("File name: %s \n", outputGetStatus->data[i].fileName);
				app.DebugPrintf("File description: %s \n", outputGetStatus->data[i].fileDescription);
				app.DebugPrintf("MD5 Checksum: %s \n", outputGetStatus->data[i].md5Checksum);
				app.DebugPrintf("Size of the file: %u bytes \n", outputGetStatus->data[i].fileSize);
				app.DebugPrintf("Timestamp: %s \n", outputGetStatus->data[i].timeStamp);
				app.DebugPrintf("Visibility: \"%s\" \n", (outputGetStatus->data[i].visibility ==  0)?"Private":((outputGetStatus->data[i].visibility ==  1)?"Public read only":"Public read and write"));
			}
			m_status = e_getStatusSucceeded;
		}
		else
		{
			app.DebugPrintf("An error occurred while Get Status was being processed. retCode: 0x%x \n", retCode);
			m_status = e_error;
		}
		runCallback();
		break;

	case PSN_SIGN_IN_REQUIRED:
		app.DebugPrintf("User's PSN sign-in through web browser is required \n");
		m_status = e_signInRequired;
		runCallback();
		break;

	case SET_DATA_RESULT:
		if(retCode >= 0)
		{
			app.DebugPrintf("Set Data success \n");
			m_status = e_setDataSucceeded;
		}
		else
		{
			app.DebugPrintf("An error occurred while Set Data was being processed. retCode: 0x%x \n", retCode);
			m_status = e_error;
		}
		runCallback();
	m_bTransferStarted = false;
		break;

	case SET_DATA_PROGRESS:
		app.DebugPrintf("Set data progress: %i%%\n", retCode);
		m_status = e_setDataInProgress;
		m_dataProgress = retCode;

		break;

	case USER_ACCOUNT_LINKED:
		app.DebugPrintf("User's account has been linked with PSN \n");
		m_bInitialised = true;
		m_status = e_accountLinked;
		runCallback();
		break;

	case WEB_BROWSER_RESULT:
		app.DebugPrintf("This function is not used on PS Vita, as the account will be linked, it is not needed to open a browser to link it \n");
		assert(0);
		break;

	default:
		app.DebugPrintf("This should never happen \n");
		assert(0);
		break;

	}
}

bool SonyRemoteStorage_PS3::init(CallbackFunc cb, LPVOID lpParam)
{
	m_callbackFunc = cb;
	m_callbackParam = lpParam;
	m_bTransferStarted = false;
	m_bAborting = false;

	if(m_bInitialised)
	{
		runCallback();
		return true;
	}


	if(m_bInitialised)
	{
		internalCallback(USER_ACCOUNT_LINKED, 0);
		return true;
	}

	int ret = initPreconditions();
	if(ret < 0)
	{
		return false;
	}

	SceRemoteStorageInitParams params;

	params.callback = staticInternalCallback;
	params.userData = this;
	params.thread.threadAffinity = 0; //Not used in PS3
	params.thread.threadPriority = 1000; //Must be between [0-3071], being 0 the highest.
	params.psnTicket = psnTicket;
	params.psnTicketSize = psnTicketSize;
	strcpy(params.clientId, CLIENT_ID);
	params.timeout.connectMs = 30 * 1000;	//30 seconds is the default
	params.timeout.resolveMs = 30 * 1000;	//30 seconds is the default
	params.timeout.receiveMs = 120 * 1000;	//120 seconds is the default
	params.timeout.sendMs = 120 * 1000;		//120 seconds is the default
	params.pool.memPoolSize = 7 * 1024 * 1024;
	if(m_memPoolBuffer == nullptr)
		m_memPoolBuffer = malloc(params.pool.memPoolSize);
	params.pool.memPoolBuffer = m_memPoolBuffer;

// 	SceRemoteStorageAbortReqParams abortParams;

	ret = sceRemoteStorageInit(params);
	if(ret >= 0 || ret == SCE_REMOTE_STORAGE_ERROR_ALREADY_INITIALISED)
	{
// 		abortParams.requestId = ret;
		//ret = sceRemoteStorageAbort(abortParams);
		app.DebugPrintf("Session will be created \n");
		//if(ret >= 0)
		//{
		//	printf("Session aborted \n");
		//} else
		//{
		//	printf("Error aborting session: 0x%x \n", ret);
		//}
	}
	else
	{
		app.DebugPrintf("Error creating session: 0x%x \n", ret);
		return false;
	}
	return true;
}



bool SonyRemoteStorage_PS3::getRemoteFileInfo(SceRemoteStorageStatus* pInfo, CallbackFunc cb, LPVOID lpParam)
{
	m_callbackFunc = cb;
	m_callbackParam = lpParam;
	outputGetStatus = pInfo;

	SceRemoteStorageStatusReqParams params;
	reqId = sceRemoteStorageGetStatus(params, outputGetStatus);
	m_status = e_getStatusInProgress;

	if(reqId >= 0)
	{
		app.DebugPrintf("Get Status request sent \n");
		return true;
	}
	else
	{
		app.DebugPrintf("Error sending Get Status request: 0x%x \n", reqId);
		return false;
	}
}

void SonyRemoteStorage_PS3::abort()
{
	m_bAborting = true;
	app.DebugPrintf("Aborting...\n");
	if(m_bTransferStarted)
	{
		app.DebugPrintf("transfer has started so we'll call sceRemoteStorageAbort...\n");

		SceRemoteStorageAbortReqParams params;
		params.requestId = reqId;
		int ret = sceRemoteStorageAbort(params);

		if(ret >= 0)
		{
			app.DebugPrintf("Abort request done \n");
		}
		else
		{
			app.DebugPrintf("Error in Abort request: 0x%x \n", ret);
		}
	}
}



bool SonyRemoteStorage_PS3::setDataInternal()
{
	CompressSaveData();		// check if we need to re-save the file compressed first


	strcpy(m_saveFilename, m_setDataSaveInfo->UTF8SaveFilename);
	strcpy(m_saveFileDesc, m_setDataSaveInfo->UTF8SaveTitle);


	SceRemoteStorageSetDataReqParams params;
	params.visibility = PUBLIC_READ_WRITE;
	strcpy(params.pathLocation, m_saveFilename);
	sprintf(params.fileName, getRemoteSaveFilename());

	DescriptionData descData;
	ZeroMemory(&descData, sizeof(DescriptionData));
	descData.m_platform[0] = SAVE_FILE_PLATFORM_LOCAL & 0xff;
	descData.m_platform[1] = (SAVE_FILE_PLATFORM_LOCAL >> 8) & 0xff;
	descData.m_platform[2] = (SAVE_FILE_PLATFORM_LOCAL >> 16) & 0xff;
	descData.m_platform[3] = (SAVE_FILE_PLATFORM_LOCAL >> 24)& 0xff;

	if(m_thumbnailData)
	{
		unsigned int uiHostOptions;
		bool bHostOptionsRead;
		DWORD uiTexturePack;
		char seed[22];
		app.GetImageTextData(m_thumbnailData, m_thumbnailDataSize,reinterpret_cast<unsigned char *>(seed), uiHostOptions, bHostOptionsRead, uiTexturePack);

		int64_t iSeed = strtoll(seed, nullptr,10);
		char seedHex[17];
		sprintf(seedHex,"%016llx",iSeed);
		memcpy(descData.m_seed,seedHex,16); // Don't copy null

		// Save the host options that this world was last played with
		char hostOptions[9];
		sprintf(hostOptions,"%08x",uiHostOptions);
		memcpy(descData.m_hostOptions,hostOptions,8); // Don't copy null

		// Save the texture pack id
		char texturePack[9];
		sprintf(texturePack,"%08x",uiTexturePack);
		memcpy(descData.m_texturePack,texturePack,8); // Don't copy null
	}

	memcpy(descData.m_saveNameUTF8, m_saveFileDesc, strlen(m_saveFileDesc)+1); // plus null
	memcpy(params.fileDescription, &descData, sizeof(descData));
	strcpy(params.ps3DataFilename, "GAMEDATA");

	params.ps3FileType = CELL_SAVEDATA_FILETYPE_NORMALFILE;
	memcpy(params.secureFileId, m_secureFileId, CELL_SAVEDATA_SECUREFILEID_SIZE);


	if(m_bAborting)
	{
		runCallback();
		return false;
	}
	reqId = sceRemoteStorageSetData(params);

	app.DebugPrintf("\n*******************************\n");
	if(reqId >= 0)
	{
		app.DebugPrintf("Set Data request sent \n");
		m_bTransferStarted = true;
		m_status = e_setDataInProgress;
		return true;
	}
	else
	{
		app.DebugPrintf("Error sending Set Data request: 0x%x \n", reqId);
		return false;
	}
}

bool SonyRemoteStorage_PS3::getData( const char* remotePath, const char* localPath, CallbackFunc cb, LPVOID lpParam )
{
	m_callbackFunc = cb;
	m_callbackParam = lpParam;

	SceRemoteStorageGetDataReqParams params;
	strcpy(params.pathLocation, localPath);//"ABCD12345-RS-DATA");
	strcpy(params.fileName, remotePath);//"/test/small.txt");
	strcpy(params.ps3DataFilename, "GAMEDATA");
	params.ps3FileType = CELL_SAVEDATA_FILETYPE_NORMALFILE;
	memcpy(params.secureFileId, m_secureFileId, CELL_SAVEDATA_SECUREFILEID_SIZE);

	reqId = sceRemoteStorageGetData(params, &outputGetData);

	app.DebugPrintf("\n*******************************\n");
	if(reqId >= 0)
	{
		app.DebugPrintf("Get Data request sent \n");
		m_bTransferStarted = true;
		m_status = e_getDataInProgress;
	} else
	{
		app.DebugPrintf("Error sending Get Data request: 0x%x \n", reqId);
	}

}

void SonyRemoteStorage_PS3::runCallback()
{
	assert(m_callbackFunc);
	if(m_callbackFunc)
	{
		m_callbackFunc(m_callbackParam, m_status, m_lastErrorCode);
	}
	m_lastErrorCode = ERROR_SUCCESS;
}

int SonyRemoteStorage_PS3::SaveCompressCallback(LPVOID lpParam,bool bRes)
{
	SonyRemoteStorage_PS3* pRS = static_cast<SonyRemoteStorage_PS3 *>(lpParam);
	pRS->m_compressedSaveState = e_state_Idle;
	return 0;
}

int SonyRemoteStorage_PS3::LoadCompressCallback(void *pParam,bool bIsCorrupt, bool bIsOwner)
{
	SonyRemoteStorage_PS3* pRS = static_cast<SonyRemoteStorage_PS3 *>(pParam);
	int origFilesize = StorageManager.GetSaveSize();
	void* pOrigSaveData = malloc(origFilesize);
	unsigned int retFilesize;
	StorageManager.GetSaveData( pOrigSaveData, &retFilesize );
	// check if this save file is already compressed
	if(*static_cast<int *>(pOrigSaveData) != 0)
	{
		app.DebugPrintf("compressing save data\n");

		// Assume that the compression will make it smaller so initially attempt to allocate the current file size
		// We add 4 bytes to the start so that we can signal compressed data
		// And another 4 bytes to store the decompressed data size
		unsigned int compLength = origFilesize+8;
		byte *compData = static_cast<byte *>(malloc(compLength));
		Compression::UseDefaultThreadStorage();
		Compression::getCompression()->Compress(compData+8,&compLength,pOrigSaveData,origFilesize);
		ZeroMemory(compData,8);
		int saveVer = 0;
		memcpy( compData, &saveVer, sizeof(int) );
		memcpy( compData+4, &origFilesize, sizeof(int) );

		StorageManager.FreeSaveData();
		StorageManager.SetSaveData(compData,compLength+8);
		pRS->m_compressedSaveState = e_state_CompressedSave;
	}
	else
	{
		// already compressed, do nothing
		pRS->m_compressedSaveState = e_state_Idle;
	}

	return 0;
}

void SonyRemoteStorage_PS3::CompressSaveData()
{
	app.DebugPrintf("CompressSaveData\n");
	m_compressedSaveState = e_state_LoadingSave;
	app.DebugPrintf("Loading save\n");
	waitForStorageManagerIdle();
	C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveData(m_setDataSaveInfo, &LoadCompressCallback, this);
	if(eLoadStatus != C4JStorage::ESaveGame_Load)
	{
		app.DebugPrintf("Failed to load savegame for compression!!!!!!\n");
		m_compressedSaveState = e_state_Idle;
		return;
	}
	while(m_compressedSaveState == e_state_LoadingSave)
	{
		Sleep(10);
	}
	if(m_compressedSaveState == e_state_CompressedSave)
	{

		waitForStorageManagerIdle();
		app.DebugPrintf("Saving compressed save\n");
		waitForStorageManagerIdle();
		StorageManager.SetDefaultSaveImage();		// we can't get the save image back to overwrite, so set it to the default
		C4JStorage::ESaveGameState storageState = StorageManager.SaveSaveData( &SaveCompressCallback, this, true );		// only save the data file, so we don't overwrite the icon
		if(storageState == C4JStorage::ESaveGame_Save)
		{
			m_compressedSaveState = e_state_SavingSave;
			while(m_compressedSaveState == e_state_SavingSave)
			{
				Sleep(10);
			}
		}
		else
		{
			app.DebugPrintf("StorageManager.SaveSaveData failed, save is left uncompressed\n");
		}
	}
	waitForStorageManagerIdle();

	app.DebugPrintf("done\n");
	assert(m_compressedSaveState == e_state_Idle);
}