[+] Rewrite allnet

pull/14/head
Azalea 2024-02-25 20:23:06 -05:00
parent 1251205fdd
commit 51a0e46f8c
13 changed files with 214 additions and 474 deletions

View File

@ -0,0 +1,183 @@
package icu.samnyan.aqua.sega.allnet
import ext.API
import ext.plus
import ext.plusAssign
import ext.toUrl
import icu.samnyan.aqua.sega.util.AquaConst
import icu.samnyan.aqua.sega.util.Decoder.decodeAllNet
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.time.Instant
import java.time.LocalDateTime
import java.util.*
@Configuration
@ConfigurationProperties(prefix = "allnet.server")
class AllNetProps {
var host: String = ""
var port: Int? = null
var checkKeychip: Boolean = false
var placeName: String = ""
var placeId: String = "123"
var region0: String = "1"
var regionName0: String = "W"
var regionName1: String = "X"
var regionName2: String = "Y"
var regionName3: String = "Z"
var regionCountry: String = "JPN"
// Java assumes every application.properties as ISO-8859-1 (wtf), so we need to "correctly" convert it to UTF-8
// More better way to this is to use XML or yaml format as these treated as UTF-8
// but I rather use hack than breaking backward compatibility.. for now
// TODO: Fix this
val normalizedPlaceName: String by lazy {
String(placeName.toByteArray(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)
}
val map: Map<String, String> by lazy { mapOf(
"stat" to "1",
"name" to "",
"place_id" to placeId,
"region0" to region0,
"region_name0" to regionName0,
"region_name1" to regionName1,
"region_name2" to regionName2,
"region_name3" to regionName3,
"country" to regionCountry,
"nickname" to normalizedPlaceName,
) }
}
@Suppress("HttpUrlsUsage")
@RestController
class AllNet(
val keychipRepo: KeyChipRepo,
val props: AllNetProps
) {
@API("/")
fun root(response: HttpServletResponse) {
response.sendRedirect("web")
}
@API("/sys/test")
fun selfTest() = "Server running"
@API("/naomitest.html")
fun naomiTest() = "naomi ok"
@PostMapping("/sys/servlet/DownloadOrder", produces = ["text/plain"])
fun downloadOrder(dataStream: InputStream, req: HttpServletRequest?): String {
val bytes = dataStream.readAllBytes()
val reqMap = decodeAllNet(bytes)
logger.info("AllNet /DownloadOrder : $reqMap")
val serial = reqMap["serial"] ?: AquaConst.DEFAULT_KEYCHIP_ID
val resp = mapOf(
"stat" to "0",
"serial" to serial
)
logger.info("> Response: $resp")
return resp.toUrl() + "\n"
}
@PostMapping("/sys/servlet/PowerOn", produces = ["text/plain"])
fun powerOn(dataStream: InputStream, req: HttpServletRequest): String {
val localAddr = req.localAddr
val localPort = req.localPort.toString()
// game_id SDEZ, ver 1.35, serial A0000001234, ip, firm_ver 50000, boot_ver 0000,
// encode UTF-8, format_ver 3, hops 1 token 2010451813
val reqMap = decodeAllNet(dataStream.readAllBytes())
var serial = reqMap["serial"]
logger.info("AllNet /PowerOn : $reqMap")
// TODO: Proper keychip authentication
if (props.checkKeychip) {
// This will cause an allnet auth bad on client side
if (serial == null || !keychipRepo.existsByKeychipId(serial)) {
return "".also { logger.warn("> Rejected: Keychip not found") }
}
}
val gameId = reqMap["game_id"] ?: return "".also { logger.warn("> Rejected: No game_id provided") }
val ver = reqMap["ver"] ?: "1.0"
serial = UUID.randomUUID().toString()
val formatVer = reqMap["format_ver"] ?: ""
val resp = props.map.toMutableMap() + mapOf(
"uri" to switchUri(localAddr, localPort, gameId, ver, serial),
"host" to switchHost(localAddr, localPort, gameId),
)
// Different responses for different versions
if (formatVer.startsWith("2")) {
val now = LocalDateTime.now()
resp += mapOf(
"year" to now.year,
"month" to now.month.value,
"day" to now.dayOfMonth,
"hour" to now.hour,
"minute" to now.minute,
"second" to now.second,
"setting" to "1",
"timezone" to "+09:00",
"res_class" to "PowerOnResponseV2"
).mapValues { it.value.toString() }
} else {
resp += mapOf(
"allnet_id" to "456",
"client_timezone" to "+0900",
"utc_time" to Instant.now().toString().substring(0, 19) + "Z",
"setting" to "",
"res_ver" to "3",
"token" to reqMap["token"]
).mapValues { it.value.toString() }
}
logger.info("> Response: $resp")
return resp.toUrl() + "\n"
}
private fun switchUri(localAddr: String, localPort: String, gameId: String, ver: String, serial: String): String {
val addr = props.host.ifBlank { localAddr }
val port = props.port?.toString() ?: localPort
return when (gameId) {
"SDBT" -> "http://$addr:$port/ChuniServlet/$ver/$serial/"
"SBZV" -> "http://$addr:$port/diva/"
"SDDT" -> "http://$addr:$port/OngekiServlet/"
"SDEY" -> "http://$addr:$port/MaimaiServlet/"
"SDEZ" -> "http://$addr:$port/Maimai2Servlet/"
"SDHD" -> "http://$addr:$port/ChusanServlet/$ver/"
"SDED" -> "http://$addr:$port/CardMakerServlet/"
else -> "http://$addr:$port/"
}
}
private fun switchHost(localAddr: String, localPort: String, gameId: String): String {
val addr = props.host.ifBlank { localAddr }
val port = props.port?.toString() ?: localPort
return when (gameId) {
"SDDF" -> "$addr:$port/"
else -> addr
}
}
companion object {
val logger: Logger = LoggerFactory.getLogger(AllNet::class.java)
}
}

View File

@ -1,210 +0,0 @@
package icu.samnyan.aqua.sega.allnet;
import com.fasterxml.jackson.databind.ObjectMapper;
import icu.samnyan.aqua.sega.allnet.dao.keychip.KeyChipRepository;
import icu.samnyan.aqua.sega.allnet.model.response.DownloadOrderResponse;
import icu.samnyan.aqua.sega.allnet.model.response.PowerOnResponse;
import icu.samnyan.aqua.sega.allnet.model.response.PowerOnResponseV2;
import icu.samnyan.aqua.sega.allnet.model.response.PowerOnResponseV3;
import icu.samnyan.aqua.sega.util.Decoder;
import icu.samnyan.aqua.sega.allnet.util.KeychipChecker;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import static icu.samnyan.aqua.sega.util.AquaConst.DEFAULT_KEYCHIP_ID;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
@RestController
public class AllNetController {
private static final Logger logger = LoggerFactory.getLogger(AllNetController.class);
private final ObjectMapper mapper = new ObjectMapper();
private final String HOST_OVERRIDE;
private final String PORT_OVERRIDE;
private final String PLACE_NAME;
private final boolean MAIMAI2_NO_HTTP;
private final boolean ALLNET_CHECK_KEYCHIP;
private final KeyChipRepository keychipRepository;
public AllNetController(@Value("${allnet.server.host:}") String HOST,
@Value("${allnet.server.port:}") String PORT,
@Value("${allnet.server.place-name:}") String PLACE_NAME,
@Value("${game.maimai2.splash-old-patch:false}") boolean MAIMAI2_NO_HTTP,
@Value("${allnet.server.check-keychip:false}") boolean ALLNET_CHECK_KEYCHIP,
KeyChipRepository keychipRepository) {
this.HOST_OVERRIDE = HOST;
this.PORT_OVERRIDE = PORT;
this.MAIMAI2_NO_HTTP = MAIMAI2_NO_HTTP;
// Java assumes every application.properties as ISO-8859-1 (wtf), so we need to "correctly" convert it to UTF-8
// More better way to this is to use XML or yaml format as these treated as UTF-8
// but I rather use hack than breaking backward compatibility.. for now
this.PLACE_NAME = new String(PLACE_NAME.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
this.ALLNET_CHECK_KEYCHIP = ALLNET_CHECK_KEYCHIP;
this.keychipRepository = keychipRepository;
}
@GetMapping("/")
public void root(HttpServletResponse response) throws IOException {
response.sendRedirect("web");
}
@GetMapping("/sys/test")
public String selfTest() {
return "Server running";
}
@GetMapping("/naomitest.html")
public String naomiTest() {
return "naomi ok";
}
@PostMapping(value = "/sys/servlet/DownloadOrder", produces = "text/plain")
public String downloadOrder(InputStream dataStream, HttpServletRequest req) throws IOException {
byte[] bytes = dataStream.readAllBytes();
Map<String, String> reqMap = Decoder.decodeAllNet(bytes);
logger.info("Request: DownloadOrder, " + mapper.writeValueAsString(reqMap));
String serial = reqMap.getOrDefault("serial", DEFAULT_KEYCHIP_ID);
DownloadOrderResponse resp = new DownloadOrderResponse(1, serial);
logger.info("Response: " + mapper.writeValueAsString(resp));
return resp.toString().concat("\n");
}
@PostMapping(value = "/sys/servlet/PowerOn", produces = "text/plain")
public String powerOn(InputStream dataStream, HttpServletRequest req) throws IOException {
String localAddr = req.getLocalAddr();
String localPort = Integer.toString(req.getLocalPort());
byte[] bytes = dataStream.readAllBytes();
Map<String, String> reqMap = Decoder.decodeAllNet(bytes);
String serial = reqMap.getOrDefault("serial", "");
logger.info("Request: PowerOn, " + mapper.writeValueAsString(reqMap));
// TODO: Verify KeyChip id ?
// Seems verified now
if (this.ALLNET_CHECK_KEYCHIP){
KeychipChecker keychipChecker = new KeychipChecker(this.keychipRepository);
if (!keychipChecker.checkKeychip(serial)){
return "{}";
// This will cause an allnet auth bad on client side
// Which is just what we want
}
}
String gameId = reqMap.getOrDefault("game_id", "");
String ver = reqMap.getOrDefault("ver", "1.0");
serial = UUID.randomUUID().toString();
String format_ver = reqMap.getOrDefault("format_ver", "");
PowerOnResponse resp;
if (format_ver.startsWith("2")) {
var now = LocalDateTime.now();
resp = new PowerOnResponseV2(
1,
switchUri(localAddr, localPort, gameId, ver, serial),
switchHost(localAddr, localPort, gameId),
"123",
"",
PLACE_NAME,
"1",
"W",
"X",
"Y",
"Z",
"JPN",
now.getYear(),
now.getMonth().getValue(),
now.getDayOfMonth(),
now.getHour(),
now.getMinute(),
now.getSecond(),
"1",
"+09:00",
"PowerOnResponseV2"
);
} else {
resp = new PowerOnResponseV3(
1,
switchUri(localAddr, localPort, gameId, ver, serial),
switchHost(localAddr, localPort, gameId),
"123",
"",
PLACE_NAME,
"1",
"W",
"X",
"Y",
"Z",
"JPN",
"456",
"+0900",
Instant.now().toString().substring(0, 19).concat("Z"),
"",
"3",
reqMap.get("token")
);
}
logger.info("Response: " + mapper.writeValueAsString(resp));
return resp.toString().concat("\n");
}
private String switchUri(String localAddr, String localPort, String gameId, String ver, String serial) {
String addr = HOST_OVERRIDE.equals("") ? localAddr : HOST_OVERRIDE;
String port = PORT_OVERRIDE.equals("") ? localPort : PORT_OVERRIDE;
switch (gameId) {
case "SDBT":
return "http://" + addr + ":" + port + "/ChuniServlet/" + ver + "/" + serial + "/";
case "SBZV":
return "http://" + addr + ":" + port + "/diva/";
case "SDDT":
return "http://" + addr + ":" + port + "/OngekiServlet/";
case "SDEY":
return "http://" + addr + ":" + port + "/MaimaiServlet/";
case "SDEZ":
// Workaround for old splash patch
if (MAIMAI2_NO_HTTP) {
return addr + ":" + port + "/Maimai2Servlet/";
} else {
return "http://" + addr + ":" + port + "/Maimai2Servlet/";
}
case "SDHD":
return "http://" + addr + ":" + port + "/ChusanServlet/" + ver + "/";
case "SDED":
return "http://" + addr + ":" + port + "/CardMakerServlet/";
default:
return "http://" + addr + ":" + port + "/";
}
}
private String switchHost(String localAddr, String localPort, String gameId) {
String addr = HOST_OVERRIDE.equals("") ? localAddr : HOST_OVERRIDE;
String port = PORT_OVERRIDE.equals("") ? localPort : PORT_OVERRIDE;
switch (gameId) {
case "SDDF":
return addr + ":" + port + "/";
default:
return addr;
}
}
}

View File

@ -0,0 +1,28 @@
package icu.samnyan.aqua.sega.allnet
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import java.io.Serializable
@Entity
@Table(name = "allnet_keychips")
class Keychip(
@Id
val id: Long = 0,
@Column(unique = true, nullable = false)
val keychipId: String = ""
) : Serializable {
companion object {
const val serialVersionUID = 1L
}
}
@Repository("KeyChipRepository")
interface KeyChipRepo : JpaRepository<Keychip?, Long?> {
fun existsByKeychipId(keychipId: String?): Boolean
}

View File

@ -1,14 +0,0 @@
package icu.samnyan.aqua.sega.allnet.dao.keychip;
import icu.samnyan.aqua.sega.allnet.model.Keychip;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository("KeyChipRepository")
public interface KeyChipRepository extends JpaRepository<Keychip, Long> {
@Query(value = "select 1 from allnet_keychips where keychip_id = ?1 limit 1", nativeQuery = true)
Optional<Integer> findKeyChipExistence(String KeychipId);
}

View File

@ -1,26 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Entity(name = "Keychip")
@Table(name = "allnet_keychips", uniqueConstraints = {@UniqueConstraint(columnNames = {"keychip_id"})})
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Keychip implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long id;
private String keychip_id;
}

View File

@ -1,25 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PowerOnRequest {
private String game_id;
private String ver;
private String serial;
private String ip;
private String firm_ver;
private String boot_ver;
private String encode;
private String format_ver;
private String hops;
private String token;
}

View File

@ -1,25 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DownloadOrderResponse {
private int stat;
private String serial;
//private String uri;
// Set uri to null: app code 300, option code 100 with http download error
// Exclude uri key or set stat to 0: both code 100 (current)
@Override
public String toString() {
return "stat=" + stat +
"&serial=" + serial;
}
}

View File

@ -1,8 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model.response;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
public interface PowerOnResponse {
String toString();
}

View File

@ -1,60 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PowerOnResponseV2 implements PowerOnResponse {
private int stat;
private String uri;
private String host;
private String place_id;
private String name;
private String nickname;
private String region0;
private String region_name0;
private String region_name1;
private String region_name2;
private String region_name3;
private String country;
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int second;
private String setting;
private String timezone;
private String res_class;
@Override
public String toString() {
return "stat=" + stat +
"&uri=" + uri +
"&host=" + host +
"&place_id=" + place_id +
"&name=" + name +
"&nickname=" + nickname +
"&region0=" + region0 +
"&region_name0=" + region_name0 +
"&region_name1=" + region_name1 +
"&region_name2=" + region_name2 +
"&region_name3=" + region_name3 +
"&country=" + country +
"&year=" + year +
"&month=" + month +
"&day=" + day +
"&hour=" + hour +
"&minute=" + minute +
"&second=" + second +
"&setting=" + setting +
"&timezone=" + timezone +
"&res_class=PowerOnResponseV2";
}
}

View File

@ -1,54 +0,0 @@
package icu.samnyan.aqua.sega.allnet.model.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author samnyan (privateamusement@protonmail.com)
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PowerOnResponseV3 implements PowerOnResponse {
private int stat;
private String uri;
private String host;
private String place_id;
private String name;
private String nickname;
private String region0;
private String region_name0;
private String region_name1;
private String region_name2;
private String region_name3;
private String country;
private String allnet_id;
private String client_timezone;
private String utc_time;
private String setting;
private String res_ver;
private String token;
@Override
public String toString() {
return "stat=" + stat +
"&uri=" + uri +
"&host=" + host +
"&place_id=" + place_id +
"&name=" + name +
"&nickname=" + nickname +
"&region0=" + region0 +
"&region_name0=" + region_name0 +
"&region_name1=" + region_name1 +
"&region_name2=" + region_name2 +
"&region_name3=" + region_name3 +
"&country=" + country +
"&allnet_id=" + allnet_id +
"&client_timezone=" + client_timezone +
"&utc_time=" + utc_time +
"&setting=" + setting +
"&res_ver=" + res_ver +
"&token=" + token;
}
}

View File

@ -1,28 +0,0 @@
package icu.samnyan.aqua.sega.allnet.service;
import icu.samnyan.aqua.sega.allnet.dao.keychip.KeyChipRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.NoSuchElementException;
import java.util.Optional;
@Service("CheckKeychipService")
public class CheckKeychipService {
private final KeyChipRepository keyChipRepository;
@Autowired
public CheckKeychipService(KeyChipRepository keyChipRepository) {
this.keyChipRepository = keyChipRepository;
}
public boolean checkKeyChipExistence(String keychipId){
Optional<Integer> findRes = keyChipRepository.findKeyChipExistence(keychipId);
try {
findRes.orElseThrow();
return true;
}catch (NoSuchElementException e){
return false;
}
}
}

View File

@ -1,18 +0,0 @@
package icu.samnyan.aqua.sega.allnet.util;
import icu.samnyan.aqua.sega.allnet.dao.keychip.KeyChipRepository;
import icu.samnyan.aqua.sega.allnet.service.CheckKeychipService;
public class KeychipChecker {
private final CheckKeychipService checkKeychipService;
public KeychipChecker(KeyChipRepository keyChipRepository) {
this.checkKeychipService = new CheckKeychipService(keyChipRepository);
}
public boolean checkKeychip(String keychipId){
return checkKeychipService.checkKeyChipExistence(keychipId);
}
}

View File

@ -1,7 +1,7 @@
package icu.samnyan.aqua.sega.util package icu.samnyan.aqua.sega.util
import java.nio.charset.StandardCharsets
import java.util.* import java.util.*
import kotlin.text.Charsets.UTF_8
object Decoder { object Decoder {
/** /**
@ -13,13 +13,10 @@ object Decoder {
if (base64) bytes = Base64.getMimeDecoder().decode(bytes) if (base64) bytes = Base64.getMimeDecoder().decode(bytes)
// Decompress the decoded byte array // Decompress the decoded byte array
val output = Compression.decompress(bytes, nowrap) val output = Compression.decompress(bytes, nowrap).toString(UTF_8).trim()
// Convert the decompressed byte array to a UTF-8 encoded string and trim any trailing spaces
val str = String(output, StandardCharsets.UTF_8).trim()
// Split the string by '&' symbol to separate key-value pairs // Split the string by '&' symbol to separate key-value pairs
return str.split("&").associate { return output.split("&").associate {
val (key, value) = it.split("=") val (key, value) = it.split("=")
key to value key to value
} }