-
Notifications
You must be signed in to change notification settings - Fork 2
/
HDLGameSvr.c
executable file
·1536 lines (1279 loc) · 53.1 KB
/
HDLGameSvr.c
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <kernel.h>
#include <libcdvd.h>
#include <limits.h>
#include <iopcontrol.h>
#include <iopheap.h>
#include <libmc.h>
#include <libpwroff.h>
#include <loadfile.h>
#include <malloc.h>
#include <sifcmd.h>
#include <sifrpc.h>
#include <stdio.h>
#include <string.h>
#include <ps2ip.h>
#include <wchar.h>
#include <speedregs.h>
#include <atahw.h>
#include <debug.h>
#include <libhdd.h>
#include <fileXio_rpc.h>
#include <hdd-ioctl.h>
#include <sys/fcntl.h>
#include "main.h"
#include "HDLGameList.h"
#include "system.h"
#include "io.h"
#include "OSD.h"
#include "HDLGameSvr.h"
typedef int SOCKET;
extern void *_gp;
enum TASK_MODES {
TASK_GAME_INSTALLATION = 0,
TASK_OSD_RESOURCE_CONFIG,
TASK_NONE = -1
};
struct GameInstallationContext
{
int fd;
int write;
u32 remaining;
char partition[40];
struct BuffDesc *bd;
void *ioBuffer;
};
struct OSDResourceConfigContext
{
char partition[40];
struct OSDResourceFileEntry resources[NUM_OSD_FILES_ENTS];
void *NewFileBuffer; // Temporary pointer for storing the address of the buffer of an incoming resource file.
unsigned int AllocatedBufferLength, NewFileResourceIndex;
};
enum THREAD_CMD {
THREAD_CMD_NOP = 0,
THREAD_CMD_STOP,
};
struct ClientData
{
u8 RxBuffer[HDLGMAN_RECV_MAX] ALIGNED(64);
u8 TxBuffer[HDLGMAN_SEND_MAX] ALIGNED(64);
u8 stack[CLIENT_THREAD_STACK_SIZE] ALIGNED(16);
u8 DataThreadStack[CLIENT_DATA_THREAD_STACK_SIZE] ALIGNED(16);
struct sockaddr_in peer;
SOCKET socket;
SOCKET DataSocket;
int task;
void *TaskData;
unsigned char status;
unsigned char DataThreadRunning;
unsigned char ServerThreadRunning;
int ServerThreadID;
int DataThreadID;
int StateSemaID; // Semaphore for locking the thread running state.
};
struct ServerData
{
int cmd;
unsigned char status;
int CmdThreadID; // Thread that is waiting for the command to complete.
int CmdSemaID; // Only 1 thread can issue a command.
int StateSemaID; // Semaphore for locking the thread running state.
};
static SOCKET srvSocket;
static struct ClientData ClientData[MAX_CLIENTS] ALIGNED(64);
static u8 NumClientsConnected;
static u8 NeedReloadGameList;
struct ServerData ServerData;
extern struct RuntimeData RuntimeData;
static void ServerThreadExecCmd(int cmd);
static int SendResponse(SOCKET connection, int rcode, const void *payload, unsigned int PayloadLength);
static int SendPayload(SOCKET connection, const void *payload, unsigned int PayloadLength);
static int ReceiveData(SOCKET connection, void *buffer, int length);
static int GetResponse(SOCKET connection, void *buffer, int NumBytes);
static int CreateServerThread(void);
static int CreateClientThread(struct ClientData *client);
static void DeinitServer(void);
static void DisconnectSocketConnection(SOCKET connection);
static void DisconnectDataConnection(SOCKET connection);
static int EndInstallation(struct ClientData *client);
static int CloseGame(struct ClientData *client);
static int CleanupClientConnection(struct ClientData *client);
static int PowerOffServer(struct ClientData *client, void *buffer, unsigned int length);
static int HandlePacket(struct ClientData *client, unsigned int command, unsigned char *buffer, unsigned int length);
static void ServerClientService(struct ClientData *client);
static int StartClientThread(struct ClientData *client, SOCKET s, const struct sockaddr *peer);
static void ServerLoop(void);
static void DataThread(struct ClientData *client);
static int MountOpenGame(struct GameInstallationContext *InstallationContext, struct ClientData *client, u32 sectors, u32 offset, int write);
static int PrepareGameInstallation(struct ClientData *client, void *buffer, unsigned int length);
static int InitDataConnection(struct ClientData *client);
static int InitGameWrite(struct ClientData *client, void *buffer, unsigned int length);
static int WriteGame(struct ClientData *client);
static int InitGameRead(struct ClientData *client, void *buffer, unsigned int length);
static int ReadGame(struct ClientData *client);
static int HandleCloseGame(struct ClientData *client);
static int GetIOStatus(struct ClientData *client);
static int LoadGameList(struct ClientData *client, void *buffer, unsigned int length);
static int ReadGameList(struct ClientData *client, void *buffer, unsigned int length);
static int ReadGameListEntry(struct ClientData *client, void *buffer, unsigned int length);
static int ReadGameListEntryDetails(struct ClientData *client, void *buffer, unsigned int length);
static int UpdateGameListEntry(struct ClientData *client, void *buffer, unsigned int length);
static int DeleteGameEntry(struct ClientData *client, void *buffer, unsigned int length);
static int GetPartName(struct ClientData *client, void *buffer, unsigned int length);
static int GetFreeSpace(struct ClientData *client);
static int InitDefaultOSDResources(struct ClientData *client, void *buffer, unsigned int length);
static int InitOSDResources(struct ClientData *client, void *buffer, unsigned int length);
static int OSDResourceLoadInit(struct ClientData *client, void *buffer, unsigned int length);
static int WriteOSDResources(struct ClientData *client, void *buffer, unsigned int length);
static int CancelOSDResourceWrite(struct ClientData *client, void *buffer, unsigned int length);
static int GetOSDResourceStat(struct ClientData *client, void *buffer, unsigned int length);
static int ReadOSDResource(struct ClientData *client, void *buffer, unsigned int length);
static int ReadOSDResourceTitles(struct ClientData *client, void *buffer, unsigned int length);
static int CheckMCSave(struct ClientData *client, void *buffer, unsigned int length);
static int GetMCSaveResourceStat(struct ClientData *client, void *buffer, unsigned int length);
static int ReadMCSaveResource(struct ClientData *client, void *buffer, unsigned int length);
static int PowerOffServer(struct ClientData *client, void *buffer, unsigned int length);
static int HandlePacket(struct ClientData *client, unsigned int command, unsigned char *buffer, unsigned int length);
static void ServerThreadExecCmd(int cmd)
{
int valid;
WaitSema(ServerData.CmdSemaID);
WaitSema(ServerData.StateSemaID);
valid = (ServerData.status & SERVER_STATUS_THREAD_RUN) != 0;
SignalSema(ServerData.StateSemaID);
if (valid) {
ServerData.CmdThreadID = GetThreadId();
ServerData.cmd = cmd;
SleepThread();
}
SignalSema(ServerData.CmdSemaID);
}
static int SendResponse(SOCKET connection, int rcode, const void *payload, unsigned int PayloadLength)
{
const unsigned char *ptr;
unsigned int remaining;
struct HDDToolsPacketHdr header;
int result;
header.command = HDLGMAN_SERVER_RESPONSE;
header.result = rcode;
header.PayloadLength = PayloadLength;
for (ptr = (const unsigned char *)&header, remaining = sizeof(struct HDDToolsPacketHdr); remaining > 0; remaining -= result, ptr += result) {
if ((result = send(connection, ptr, remaining, 0)) <= 0) {
result = -1;
break;
}
}
if (result >= 0)
result = SendPayload(connection, payload, PayloadLength);
return result;
}
static int SendPayload(SOCKET connection, const void *payload, unsigned int PayloadLength)
{
const unsigned char *ptr;
unsigned int remaining;
struct HDDToolsPacketHdr header;
int result;
remaining = PayloadLength;
ptr = payload;
result = 0;
while (remaining > 0) {
if ((result = send(connection, ptr, remaining, 0)) > 0) {
ptr += result;
remaining -= result;
} else {
result = -1;
break;
}
}
return (result > 0 ? PayloadLength : result);
}
static int ReceiveData(SOCKET connection, void *buffer, int length)
{
struct timeval timeout;
int result, remaining;
char *ptr;
fd_set readFDs;
for (ptr = (char *)buffer, remaining = length, result = 0; remaining > 0; remaining -= result, ptr += result) {
timeout.tv_sec = 30;
timeout.tv_usec = 0;
FD_ZERO(&readFDs);
FD_SET(connection, &readFDs);
if ((result = select(connection + 1, &readFDs, NULL, NULL, &timeout)) == 1) {
if ((result = recv(connection, ptr, remaining, 0)) <= 0) {
result = -EEXTCONNLOST;
break;
}
} else {
result = -EEXTCONNLOST;
DisconnectSocketConnection(connection);
break;
}
}
if (result > 0)
result = length;
return result;
}
static int GetResponse(SOCKET connection, void *buffer, int NumBytes)
{
int result;
struct HDDToolsPacketHdr header;
// Receive header.
if ((result = ReceiveData(connection, (void *)&header, sizeof(header))) == sizeof(header)) {
// Receive payload.
if (NumBytes > 0 && header.PayloadLength > 0) {
if ((result = ReceiveData(connection, buffer, (int)header.PayloadLength > NumBytes ? NumBytes : header.PayloadLength)) > 0)
result = header.result;
} else
result = header.result;
}
return result;
}
static int MainServerThreadID;
static unsigned char ServerThreadStack[SERVER_THREAD_STACK_SIZE] __attribute__((aligned(16)));
static int CreateServerThread(void)
{
ee_sema_t sema;
ServerData.status = SERVER_STATUS_THREAD_RUN;
ServerData.CmdThreadID = -1;
ServerData.cmd = THREAD_CMD_NOP;
sema.init_count = 1;
sema.max_count = 1;
sema.attr = 0;
sema.option = (u32) "server-cmd";
if ((ServerData.CmdSemaID = CreateSema(&sema)) >= 0) {
sema.init_count = 1;
sema.max_count = 1;
sema.attr = 0;
sema.option = (u32) "server-state";
if ((ServerData.StateSemaID = CreateSema(&sema)) >= 0) {
MainServerThreadID = SysCreateThread(&ServerLoop, ServerThreadStack, SERVER_THREAD_STACK_SIZE, NULL, SERVER_MAIN_THREAD_PRIORITY);
if (MainServerThreadID < 0) {
DeleteSema(ServerData.StateSemaID);
DeleteSema(ServerData.CmdSemaID);
}
return MainServerThreadID;
} else {
DeleteSema(ServerData.CmdSemaID);
return ServerData.StateSemaID;
}
} else {
return ServerData.CmdSemaID;
}
}
static int CreateClientThread(struct ClientData *client)
{
ee_sema_t sema;
ee_thread_t thread;
int ThreadID;
sema.init_count = 1;
sema.max_count = 1;
sema.attr = 0;
sema.option = (u32) "client-state";
if ((client->StateSemaID = CreateSema(&sema)) >= 0) {
thread.func = (void *)&DataThread;
thread.stack = client->DataThreadStack;
thread.stack_size = CLIENT_THREAD_STACK_SIZE;
thread.gp_reg = &_gp;
thread.initial_priority = SERVER_CLIENT_THREAD_PRIORITY;
thread.attr = 0;
thread.option = 0;
// Create the data thread. It will be in DORMANT state.
if ((client->DataThreadID = CreateThread(&thread)) >= 0) {
thread.func = (void *)ServerClientService;
thread.stack = client->stack;
thread.stack_size = CLIENT_THREAD_STACK_SIZE;
thread.gp_reg = &_gp;
thread.initial_priority = SERVER_CLIENT_THREAD_PRIORITY;
thread.attr = 0;
thread.option = 0;
// Create the client server thread. It will be in DORMANT state.
if ((client->ServerThreadID = CreateThread(&thread)) >= 0)
return 0;
DeleteThread(client->DataThreadID);
DeleteSema(client->StateSemaID);
return client->ServerThreadID;
} else {
DeleteSema(client->StateSemaID);
return client->DataThreadID;
}
} else {
return client->StateSemaID;
}
}
int InitializeStartServer(void)
{
ee_sema_t sema;
struct sockaddr_in addr;
unsigned int i;
int result;
DI();
RuntimeData.IsRemoteClientConnected = 0;
NumClientsConnected = 0;
NeedReloadGameList = 0;
EI();
srvSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
addr.sin_family = AF_INET;
addr.sin_port = htons(SERVER_PORT_NUM);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(srvSocket, (struct sockaddr *)&addr, sizeof(addr)) == 0 && listen(srvSocket, MAX_CLIENTS) == 0) {
for (i = 0; i < MAX_CLIENTS; i++) {
ClientData[i].status = 0;
ClientData[i].ServerThreadID = -1;
ClientData[i].task = TASK_NONE;
ClientData[i].TaskData = NULL;
ClientData[i].ServerThreadRunning = 0;
ClientData[i].DataThreadRunning = 0;
if ((result = CreateClientThread(&ClientData[i])) != 0) {
printf("Failed to create client thread: %d\n", result);
DisconnectSocketConnection(srvSocket);
return result;
}
}
result = 0;
} else {
result = -1;
DisconnectSocketConnection(srvSocket);
}
if (result >= 0)
CreateServerThread();
return result;
}
void DeinitializeServer(void)
{
ServerThreadExecCmd(THREAD_CMD_STOP);
TerminateThread(MainServerThreadID);
DeleteThread(MainServerThreadID);
MainServerThreadID = -1;
DeleteSema(ServerData.CmdSemaID);
ServerData.CmdSemaID = -1;
DeleteSema(ServerData.StateSemaID);
ServerData.StateSemaID = -1;
}
static void DeinitServer(void)
{
unsigned int i;
struct ClientData *client;
ee_thread_status_t info;
for (i = 0; i < MAX_CLIENTS; i++) {
if (ClientData[i].ServerThreadID >= 0) {
client = &ClientData[i];
if (!client->ServerThreadRunning) {
DeleteThread(client->ServerThreadID);
DeleteThread(client->DataThreadID);
client->ServerThreadID = -1;
client->DataThreadID = -1;
DeleteSema(client->StateSemaID);
client->StateSemaID = -1;
} else {
printf("Server: thread %d continued until shutdown.\n", client->ServerThreadID);
}
}
}
}
static void DisconnectSocketConnection(SOCKET connection)
{
shutdown(connection, SHUT_RDWR);
closesocket(connection);
}
// Close the socket gracefully, waiting for the remote to close the connection. Use this to complete successful data transfers.
static void DisconnectDataConnection(SOCKET connection)
{
char dummy;
shutdown(connection, SHUT_WR);
// Wait for the remote end to close the socket, which shall happen after all sent data has been received.
while (recv(connection, &dummy, sizeof(dummy), 0) > 0)
;
closesocket(connection);
}
static int EndInstallation(struct ClientData *client)
{
int result;
struct GameInstallationContext *InstallationContext;
/* Allow this to succeed by default. If the client and server's states do not match up,
allowing the client to close the game will allow the user to start a new operation. */
result = 0;
if (client->task == TASK_GAME_INSTALLATION) {
InstallationContext = client->TaskData;
if (InstallationContext->write)
result = IOEndWrite();
else
result = IOEndRead();
IOFree(&InstallationContext->bd, &InstallationContext->ioBuffer);
fileXioClose(InstallationContext->fd);
fileXioUmount("hdl0:");
client->status &= ~(CLIENT_STATUS_OPENED_FILE | CLIENT_STATUS_MOUNTED_FS);
client->task = TASK_NONE;
free(client->TaskData);
client->TaskData = NULL;
SignalSema(RuntimeData.InstallationLockSema);
}
return result;
}
static int CloseGame(struct ClientData *client)
{
int result;
WaitSema(client->StateSemaID);
result = EndInstallation(client);
SignalSema(client->StateSemaID);
return result;
}
static int CleanupClientConnection(struct ClientData *client)
{
int reload;
WaitSema(client->StateSemaID);
switch (client->task) {
case TASK_GAME_INSTALLATION:
EndInstallation(client);
break;
}
client->status = 0;
client->task = TASK_NONE;
if (client->TaskData != NULL) {
free(client->TaskData);
client->TaskData = NULL;
}
SignalSema(client->StateSemaID);
DI();
--NumClientsConnected;
if (NumClientsConnected < 1)
RuntimeData.IsRemoteClientConnected = 0;
if (NeedReloadGameList) { // Reload the game list
NeedReloadGameList = 0;
reload = 1;
} else {
reload = 0;
}
EI();
if (reload)
LoadHDLGameList(NULL);
return 0;
}
static void ServerClientService(struct ClientData *client)
{
struct timeval timeout;
fd_set readFDs;
int result, SkipPayload, id;
struct HDDToolsPacketHdr header;
client->ServerThreadRunning = 1;
printf("Client connected.\n");
while (1) {
result = recv(client->socket, &header, sizeof(header), 0);
if (result > 0) {
if (result != sizeof(struct HDDToolsPacketHdr)) {
DEBUG_PRINTF("Invalid header length: %d\n", result);
break;
}
switch (header.command) {
// Exceptions for automatic payload reading
default:
SkipPayload = 0;
}
if ((!SkipPayload) && (header.PayloadLength > 0)) {
if (header.PayloadLength > sizeof(client->RxBuffer)) {
printf("Error: Payload too long.\n");
if ((result = SendResponse(client->socket, -ENOMEM, NULL, 0)) < 0) {
DEBUG_PRINTF("Response send error: %d\n", result);
break;
}
continue;
}
if ((result = ReceiveData(client->socket, client->RxBuffer, header.PayloadLength)) != header.PayloadLength) {
if (result > 0)
result = -1;
DEBUG_PRINTF("Error retrieving payload: %d\n", result);
break;
}
}
if ((result = HandlePacket(client, header.command, client->RxBuffer, header.PayloadLength)) < 0) {
DEBUG_PRINTF("Error handling command: %d.\n", result);
break;
}
} else {
break;
}
}
printf("Client disconnected.\n");
DisconnectSocketConnection(client->socket);
CleanupClientConnection(client);
client->ServerThreadRunning = 0;
}
static int StartClientThread(struct ClientData *client, SOCKET s, const struct sockaddr *peer)
{
client->socket = s;
client->status = CLIENT_STATUS_CONNECTED;
memcpy(&client->peer, peer, sizeof(struct sockaddr));
return StartThread(client->ServerThreadID, client);
}
static void ServerLoop(void)
{
unsigned int i;
unsigned char done;
SOCKET TempSocketConnection;
int size, id;
struct sockaddr peer;
struct timeval timeout;
fd_set readFDs;
printf("Server started.\n");
done = 0;
while (!done) {
timeout.tv_sec = 3;
timeout.tv_usec = 0;
FD_ZERO(&readFDs);
FD_SET(srvSocket, &readFDs);
if (select(srvSocket + 1, &readFDs, NULL, NULL, &timeout) == 1) {
size = sizeof(peer);
if ((TempSocketConnection = accept(srvSocket, &peer, &size)) >= 0) {
for (i = 0; i < MAX_CLIENTS; i++) {
if (ClientData[i].status == 0) { /* Find an empty slot. */
if (StartClientThread(&ClientData[i], TempSocketConnection, &peer) >= 0) {
DI();
++NumClientsConnected;
RuntimeData.IsRemoteClientConnected = 1;
EI();
}
break;
}
}
if (i == MAX_CLIENTS) {
DisconnectSocketConnection(TempSocketConnection);
DEBUG_PRINTF("Error! Out of connection slots.\n");
}
} else {
done = 1;
}
} else {
switch (ServerData.cmd) {
case THREAD_CMD_STOP:
done = 1;
break;
default:
ServerData.cmd = THREAD_CMD_NOP;
}
}
}
printf("Server shutting down.");
DisconnectSocketConnection(srvSocket);
DeinitServer();
WaitSema(ServerData.StateSemaID);
ServerData.status &= ~SERVER_STATUS_THREAD_RUN;
if (ServerData.CmdThreadID >= 0) {
id = ServerData.CmdThreadID;
ServerData.CmdThreadID = -1;
WakeupThread(id);
}
SignalSema(ServerData.StateSemaID); // Unlock state
}
static void DataThread(struct ClientData *client)
{
int result;
struct GameInstallationContext *InstallationContext;
client->DataThreadRunning = 1;
if (client->task == TASK_GAME_INSTALLATION) {
InstallationContext = client->TaskData;
if (InstallationContext->write)
result = WriteGame(client);
else
result = ReadGame(client);
// Close the socket gracefully.
DisconnectDataConnection(client->DataSocket);
// Close the game here, regardless of how it went.
CloseGame(client);
}
client->DataThreadRunning = 0;
}
static int MountOpenGame(struct GameInstallationContext *InstallationContext, struct ClientData *client, u32 sectors, u32 offset, int write)
{
int result;
InstallationContext->write = write;
if ((result = fileXioMount("hdl0:", InstallationContext->partition, write ? FIO_MT_RDWR : FIO_MT_RDONLY)) >= 0) {
if ((result = InstallationContext->fd = fileXioOpen("hdl0:", write ? O_RDWR : O_RDONLY)) >= 0) {
if (offset != 0)
result = fileXioLseek(InstallationContext->fd, (s32)offset, SEEK_SET) == (s32)offset ? 0 : -ESPIPE;
if (result >= 0) {
InstallationContext->remaining = sectors;
if ((result = IOAlloc(&InstallationContext->bd, &InstallationContext->ioBuffer)) >= 0) {
if (write)
result = IOWriteInit(InstallationContext->fd, InstallationContext->bd, InstallationContext->ioBuffer, IO_BANKSIZE, IO_BANKMAX, SERVER_IO_THREAD_PRIORITY);
else
result = IOReadInit(InstallationContext->fd, InstallationContext->bd, InstallationContext->ioBuffer, IO_BANKSIZE, IO_BANKMAX, sectors, SERVER_IO_THREAD_PRIORITY);
if (result < 0) {
DEBUG_PRINTF("Error occurred while initializing I/O: %d\n", result);
IOFree(&InstallationContext->bd, &InstallationContext->ioBuffer);
}
} else
DEBUG_PRINTF("Could not allocate memory for I/O.\n");
}
if (result < 0)
fileXioClose(InstallationContext->fd);
} else
DEBUG_PRINTF("Error opening partition. Result: %d\n", InstallationContext->fd);
if (result < 0)
fileXioUmount("hdl0:");
} else
DEBUG_PRINTF("Error occurred while mounting: %d\n", result);
return result;
}
static int PrepareGameInstallation(struct ClientData *client, void *buffer, unsigned int length)
{
int result;
struct GameInstallationContext *InstallationContext;
const struct HDLGameInfo *info = (const struct HDLGameInfo *)buffer;
wchar_t GameTitle[GAME_TITLE_MAX_LEN + 1];
WaitSema(client->StateSemaID);
if ((client->task == TASK_NONE) && (PollSema(RuntimeData.InstallationLockSema) == RuntimeData.InstallationLockSema)) {
if ((client->TaskData = malloc(sizeof(struct GameInstallationContext))) != NULL) {
InstallationContext = client->TaskData;
InstallationContext->write = 1;
mbstowcs(GameTitle, info->GameTitle, GAME_TITLE_MAX_LEN + 1);
GeneratePartName(InstallationContext->partition, info->DiscID, GameTitle);
result = PrepareInstallHDLGame(GameTitle, info->DiscID, info->StartupFname, InstallationContext->partition,
info->SectorsInDiscLayer0, info->SectorsInDiscLayer1, info->DiscType, info->CompatibilityFlags,
info->TRType, info->TRMode);
if (result >= 0) {
if ((result = MountOpenGame(InstallationContext, client, info->SectorsInDiscLayer0 + info->SectorsInDiscLayer1, 0, 1)) >= 0) {
client->status |= (CLIENT_STATUS_MOUNTED_FS | CLIENT_STATUS_OPENED_FILE);
client->task = TASK_GAME_INSTALLATION;
DI();
NeedReloadGameList = 1;
EI();
result = InitDataConnection(client);
} else
RemoveGameInstallation(InstallationContext->partition);
}
if (result < 0)
EndInstallation(client);
} else
result = -ENOMEM;
} else
result = -EBUSY;
SignalSema(client->StateSemaID);
return SendResponse(client->socket, result, NULL, 0);
}
static int InitDataConnection(struct ClientData *client)
{
struct sockaddr_in addr;
SOCKET s;
int result;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
addr.sin_family = AF_INET;
addr.sin_port = htons(SERVER_DATA_PORT_NUM);
addr.sin_addr.s_addr = client->peer.sin_addr.s_addr;
if ((result = connect(s, (struct sockaddr *)&addr, sizeof(addr))) == 0) {
if (StartThread(client->DataThreadID, client) == client->DataThreadID) {
client->DataSocket = s;
result = 0;
} else
result = -1;
} else {
result = -1;
}
if (result != 0)
DisconnectSocketConnection(s);
return result;
}
static int InitGameWrite(struct ClientData *client, void *buffer, unsigned int length)
{
int result;
struct GameInstallationContext *InstallationContext;
const struct IOInitReq *req = (const struct IOInitReq *)buffer;
WaitSema(client->StateSemaID);
if (client->task == TASK_NONE && (PollSema(RuntimeData.InstallationLockSema) == RuntimeData.InstallationLockSema)) {
if ((client->TaskData = malloc(sizeof(struct GameInstallationContext))) != NULL) {
InstallationContext = client->TaskData;
snprintf(InstallationContext->partition, sizeof(InstallationContext->partition), "hdd0:%s", req->partition);
if ((result = MountOpenGame(InstallationContext, client, req->sectors, req->offset, 1)) >= 0) {
client->status |= (CLIENT_STATUS_MOUNTED_FS | CLIENT_STATUS_OPENED_FILE);
client->task = TASK_GAME_INSTALLATION;
result = InitDataConnection(client);
}
if (result < 0)
EndInstallation(client);
} else
result = -ENOMEM;
} else
result = -EBUSY;
SignalSema(client->StateSemaID);
return SendResponse(client->socket, result, NULL, 0);
}
// Receive the pre-specified amount of sectors or until remote closes the connection.
static int WriteGame(struct ClientData *client)
{
int result, len, lenBytes;
void *wrBuffer;
struct GameInstallationContext *InstallationContext = client->TaskData;
result = 0;
while ((InstallationContext->remaining > 0) && (result == 0)) {
wrBuffer = IOGetNextWrBuffer();
len = InstallationContext->remaining > IO_BANKSIZE ? IO_BANKSIZE : InstallationContext->remaining;
lenBytes = len * 2048;
if (ReceiveData(client->DataSocket, wrBuffer, lenBytes) == lenBytes) {
IOSignalWriteDone(lenBytes);
if (IOGetStatus() == IO_THREAD_STATE_ERROR) {
result = -EIO;
break;
}
InstallationContext->remaining -= len;
result = 0;
} else {
result = -EPIPE;
break;
}
}
return result;
}
static int InitGameRead(struct ClientData *client, void *buffer, unsigned int length)
{
int result;
struct GameInstallationContext *InstallationContext;
const struct IOInitReq *req = (const struct IOInitReq *)buffer;
WaitSema(client->StateSemaID);
if (client->task == TASK_NONE && (PollSema(RuntimeData.InstallationLockSema) == RuntimeData.InstallationLockSema)) {
if ((client->TaskData = malloc(sizeof(struct GameInstallationContext))) != NULL) {
InstallationContext = client->TaskData;
InstallationContext->write = 0;
snprintf(InstallationContext->partition, sizeof(InstallationContext->partition), "hdd0:%s", req->partition);
if ((result = MountOpenGame(InstallationContext, client, req->sectors, req->offset, 0)) >= 0) {
client->status |= (CLIENT_STATUS_MOUNTED_FS | CLIENT_STATUS_OPENED_FILE);
client->task = TASK_GAME_INSTALLATION;
result = InitDataConnection(client);
}
if (result < 0)
EndInstallation(client);
} else
result = -ENOMEM;
} else
result = -EBUSY;
SignalSema(client->StateSemaID);
return SendResponse(client->socket, result, NULL, 0);
}
static int ReadGame(struct ClientData *client)
{
int result, len;
struct GameInstallationContext *InstallationContext = client->TaskData;
const void *RespPayload;
const u8 *ptr;
unsigned int RespPayloadLength, remaining;
result = 0;
while ((InstallationContext->remaining > 0) && (result == 0)) {
if ((result = IOReadNext(&RespPayload)) >= 0) {
RespPayloadLength = result;
result = 0;
for (ptr = (const u8 *)RespPayload, remaining = RespPayloadLength; remaining > 0; remaining -= len, ptr += len) {
if ((len = send(client->DataSocket, ptr, remaining, 0)) <= 0) {
result = -EPIPE;
break;
}
}
if (result == 0) {
if (IOGetStatus() == IO_THREAD_STATE_ERROR) {
result = -EIO;
break;
}
InstallationContext->remaining -= RespPayloadLength / 2048;
if (InstallationContext->remaining > 0)
IOReadAdvance();
result = 0;
}
}
}
return result;
}
static void CloseGameThreadCB(s32 alarm_id, u16 time, void *arg)
{
iWakeupThread((int)arg);
}
static int HandleCloseGame(struct ClientData *client)
{
int result;
struct GameInstallationContext *InstallationContext;
// Wait for the data thread to terminate.
while (client->DataThreadRunning) {
printf("CloseGame: waiting for data thread %d.\n", client->DataThreadID);
SetAlarm(1000 * 16, &CloseGameThreadCB, (void *)GetThreadId());
SleepThread();
}
result = 0; // Game was already closed by the data thread.
return SendResponse(client->socket, result, NULL, 0);
}
static int GetIOStatus(struct ClientData *client)
{
int result;
result = IOGetStatus();
return SendResponse(client->socket, result, NULL, 0);
}
static int LoadGameList(struct ClientData *client, void *buffer, unsigned int length)
{
int reload, NumGames;
DI();
if (NeedReloadGameList) { // Reload the game list
NeedReloadGameList = 0;
reload = 1;
} else {
reload = 0;
}
EI();
NumGames = (reload) ? LoadHDLGameList(NULL) : GetHDLGameList(NULL);
return SendResponse(client->socket, NumGames, NULL, 0);
}
static int ReadGameList(struct ClientData *client, void *buffer, unsigned int length)
{
int NumGamesInList, result, i, rcode;
struct HDLGameEntry *GameList, *pGameEntry;
struct HDLGameEntryTransit GameEntryTransit;
LockCentralHDLGameList();
if ((NumGamesInList = GetHDLGameList(&GameList)) > 0) {
if ((result = SendResponse(client->socket, 0, NULL, 0)) == 0) {
for (i = 0; i < NumGamesInList; i++) {
pGameEntry = &GameList[i];