From fcfc8b0949df85120fd9c707007ab99de80befa7 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Wed, 23 Oct 2019 20:13:12 +0200 Subject: [PATCH] Initial version Signed-off-by: Knut Ahlers --- .gitignore | 1 + LICENSE | 202 ++++++++++++++++++++++++++++++++++++++++++ README.md | 25 ++++++ b0rkhash/README.md | 7 ++ b0rkhash/hash.go | 190 +++++++++++++++++++++++++++++++++++++++ b0rkhash/hash_test.go | 23 +++++ b0rkhash/uint128.go | 14 +++ go.mod | 13 +++ go.sum | 52 +++++++++++ main.go | 132 +++++++++++++++++++++++++++ scs/scs.go | 198 +++++++++++++++++++++++++++++++++++++++++ 11 files changed, 857 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 b0rkhash/README.md create mode 100644 b0rkhash/hash.go create mode 100644 b0rkhash/hash_test.go create mode 100644 b0rkhash/uint128.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go create mode 100644 scs/scs.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f3b076 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +scs-extract diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2ce1cf5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019- Knut Ahlers + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..ca70180 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +[![Go Report Card](https://goreportcard.com/badge/github.com/Luzifer/scs-extract)](https://goreportcard.com/report/github.com/Luzifer/scs-extract) +![](https://badges.fyi/github/license/Luzifer/scs-extract) +![](https://badges.fyi/github/downloads/Luzifer/scs-extract) +![](https://badges.fyi/github/latest-release/Luzifer/scs-extract) +![](https://knut.in/project-status/scs-extract) + +# Luzifer / scs-extract + +`scs-extract` is a Linux / MacOS CLI util to list / extract files from SCS archives used in Euro Truck Simulator 2 / American Truck Simulator. + +## Usage + +`scs-extract [options] [files to extract]` + +```console +# scs-extract ~/.steam/steam/steamapps/common/Euro\ Truck\ Simulator\ 2/def.scs def/economy_data.sii +def/economy_data.sii + +# scs-extract --help +Usage of scs-extract: + -d, --dest string Path prefix to use to extract files to (default ".") + -x, --extract Extract files (if not given files are just listed) + --log-level string Log level (debug, info, warn, error, fatal) (default "info") + --version Prints current version and exits +``` diff --git a/b0rkhash/README.md b/b0rkhash/README.md new file mode 100644 index 0000000..5901e86 --- /dev/null +++ b/b0rkhash/README.md @@ -0,0 +1,7 @@ +# DO NOT USE THIS! + +This folder contains a broken implementation of the Google CityHash algorithm to access the SCS archive files of ETS2. + +- It uses more constants than the original implementation +- For file names with 8 characters length ALWAYS the same hash (K2) is returned +- Multiple other derivations from the original C-implementation made by Google diff --git a/b0rkhash/hash.go b/b0rkhash/hash.go new file mode 100644 index 0000000..ce905de --- /dev/null +++ b/b0rkhash/hash.go @@ -0,0 +1,190 @@ +package b0rkhash + +import ( + "encoding/binary" +) + +// Some primes between 2^63 and 2^64 for various uses. +const ( + k0 uint64 = 0xc3a5c85c97cb3127 + k1 uint64 = 0xb492b66fbe98f273 + k2 uint64 = 0x9ae16a3b2f90404f + k3 uint64 = 0xc949d7c7509e6557 +) + +func fetch32(p []byte) uint32 { + return binary.LittleEndian.Uint32(p) +} + +func fetch64(p []byte) uint64 { + r := binary.LittleEndian.Uint64(p) + return r +} + +// Bitwise right rotate +func rotate(val uint64, shift uint) uint64 { + // Avoid shifting by 64: doing so yields an undefined result. + if shift == 0 { + return val + } + return (val >> shift) | val<<(64-shift) +} + +func rotateByAtleast1(val uint64, shift uint) uint64 { + return (val >> shift) | (val << (64 - shift)) +} + +func shiftMix(val uint64) uint64 { + return val ^ (val >> 47) +} + +func hash128to64(x Uint128) uint64 { + const mul = uint64(0x9ddfea08eb382d69) + a := (x.Low64() ^ x.High64()) * mul + a ^= (a >> 47) + b := (x.High64() ^ a) * mul + b ^= (b >> 47) + b *= mul + return b +} + +func hashLen16(u, v uint64) uint64 { + return hash128to64(Uint128{u, v}) +} + +func hashLen0to16(s []byte, length int) uint64 { + if length > 8 { + a := fetch64(s) + b := fetch64(s[length-8:]) + return hashLen16(a, rotateByAtleast1(b+uint64(length), uint(length))) ^ b + } + + if length >= 4 { + a := uint64(fetch32(s)) + return hashLen16(uint64(length)+(a<<3), uint64(fetch32(s[length-4:]))) + } + + if length > 0 { + a := uint8(s[0]) + b := uint8(s[length>>1]) + c := uint8(s[length-1]) + y := uint32(a) + (uint32(b) << 8) + z := uint32(length) + (uint32(c) << 2) + return shiftMix(uint64(y)*k2^uint64(z)*k3) * k2 + } + + return k2 +} + +// This probably works well for 16-byte strings as well, but is may be overkill +// in that case +func hashLen17to32(s []byte, length int) uint64 { + a := fetch64(s) * k1 + b := fetch64(s[8:]) + c := fetch64(s[length-8:]) * k2 + d := fetch64(s[length-16:]) * k0 + return hashLen16(rotate(a-b, 43)+rotate(c, 30)+d, + a+rotate(b^k3, 20)-c+uint64(length)) +} + +// Return a 16-byte hash for 48 bytes. Quick and dirty. +// callers do best to use "random-looking" values for a and b. +func weakHashLen32WithSeeds(w, x, y, z, a, b uint64) Uint128 { + a += w + b = rotate(b+a+z, 21) + c := a + a += x + a += y + b += rotate(a, 44) + return Uint128{a + z, b + c} +} + +// Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. +func weakHashLen32WithSeedsByte(s []byte, a, b uint64) Uint128 { + return weakHashLen32WithSeeds( + fetch64(s), + fetch64(s[8:]), + fetch64(s[16:]), + fetch64(s[24:]), + a, + b) +} + +// Return an 8-byte hash for 33 to 64 bytes. +func hashLen33to64(s []byte, length int) uint64 { + z := fetch64(s[24:]) + a := fetch64(s) + (uint64(length)+fetch64(s[length-16:]))*k0 + b := rotate(a+z, 52) + c := rotate(a, 37) + a += fetch64(s[8:]) + c += rotate(a, 7) + a += fetch64(s[16:]) + vf := a + z + vs := b + rotate(a, 31) + c + a = fetch64(s[16:]) + fetch64(s[length-32:]) + z = fetch64(s[length-8:]) + b = rotate(a+z, 52) + c = rotate(a, 37) + a += fetch64(s[length-24:]) + c += rotate(a, 7) + a += fetch64(s[length-16:]) + wf := a + z + ws := b + rotate(a, 31) + c + r := shiftMix((vf+ws)*k2 + (wf+vs)*k0) + return shiftMix(r*k0+vs) * k2 +} + +// CityHash64 return a 64-bit hash. +func CityHash64(s []byte) uint64 { + length := len(s) + if length <= 32 { + if length <= 16 { + return hashLen0to16(s, length) + } + return hashLen17to32(s, length) + } else if length <= 64 { + return hashLen33to64(s, length) + } + + // For string over 64 bytes we hash the end first, and then as we + // loop we keep 56 bytes of state: v, w, x, y and z. + x := fetch64(s[length-40:]) + y := fetch64(s[length-16:]) + fetch64(s[length-56:]) + z := hashLen16(fetch64(s[length-48:])+uint64(length), fetch64(s[length-24:])) + v := weakHashLen32WithSeedsByte(s[length-64:], uint64(length), z) + w := weakHashLen32WithSeedsByte(s[length-32:], y+k1, x) + x = x*k1 + fetch64(s) + + // Decrease len to the nearest multiple of 64, and operate on 64-byte chunks. + tmpLength := uint32(length) + tmpLength = uint32(tmpLength-1) & ^uint32(63) + for { + x = rotate(x+y+v.Low64()+fetch64(s[8:]), 37) * k1 + y = rotate(y+v.High64()+fetch64(s[48:]), 42) * k1 + x ^= w.High64() + y += v.Low64() + fetch64(s[40:]) + z = rotate(z+w.Low64(), 33) * k1 + v = weakHashLen32WithSeedsByte(s, v.High64()*k1, x+w.Low64()) + w = weakHashLen32WithSeedsByte(s[32:], z+w.High64(), y+fetch64(s[16:])) + z, x = x, z + s = s[64:] + tmpLength -= 64 + if tmpLength == 0 { + break + } + } + + return hashLen16( + hashLen16(v.Low64(), w.Low64())+shiftMix(y)*k1+z, + hashLen16(v.High64(), w.High64())+x) +} + +// CityHash64WithSeed return a 64-bit hash with a seed. +func CityHash64WithSeed(s []byte, seed uint64) uint64 { + return CityHash64WithSeeds(s, k2, seed) +} + +// CityHash64WithSeeds return a 64-bit hash with two seeds. +func CityHash64WithSeeds(s []byte, seed0, seed1 uint64) uint64 { + return hashLen16(CityHash64(s)-seed0, seed1) +} diff --git a/b0rkhash/hash_test.go b/b0rkhash/hash_test.go new file mode 100644 index 0000000..c17328f --- /dev/null +++ b/b0rkhash/hash_test.go @@ -0,0 +1,23 @@ +package b0rkhash + +import "testing" + +func TestCityHash64(t *testing.T) { + for input, expect := range map[string]uint64{ + ``: 0x9AE16A3B2F90404F, + `custom/city.sii`: 0x1ffe051698fba3e2, + `def`: 0x2C6F469EFB31C45A, + `def/camera/city_start/actions.sii`: 0xa74e0b70addb8e2d, + `def/city`: 0x5e1b1d2c928270d1, // This is a definitive bug but also exists in SCS implementation + `def/economy_data.sii`: 0xce3123f8a189862e, + `def/map_data.sii`: 0x73aded9d5c6b4762, + `def/bank_data.sii`: 0xdb6507b90c06f96a, + } { + h := CityHash64([]byte(input)) + if h != expect { + t.Errorf("Unexpected hash for input %q: expect=0x%x result=0x%x", input, expect, h) + } else { + t.Logf("Success for input %q: expect=0x%x result=0x%x", input, expect, h) + } + } +} diff --git a/b0rkhash/uint128.go b/b0rkhash/uint128.go new file mode 100644 index 0000000..09e801d --- /dev/null +++ b/b0rkhash/uint128.go @@ -0,0 +1,14 @@ +package b0rkhash + +// Uint128 type uint128 +type Uint128 [2]uint64 + +// Low64 return the low 64-bit of u. +func (u Uint128) Low64() uint64 { + return u[0] +} + +// High64 return the high 64-bit of u. +func (u Uint128) High64() uint64 { + return u[1] +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3ba819a --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module github.com/Luzifer/scs-extract + +go 1.13 + +require ( + github.com/Luzifer/go_helpers/v2 v2.9.1 + github.com/Luzifer/rconfig/v2 v2.2.1 + github.com/onsi/ginkgo v1.10.2 // indirect + github.com/onsi/gomega v1.7.0 // indirect + github.com/pkg/errors v0.8.1 + github.com/sirupsen/logrus v1.4.2 + github.com/tenfyzhong/cityhash v0.0.0-20181130044406-4c2731b5918c +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..03a4011 --- /dev/null +++ b/go.sum @@ -0,0 +1,52 @@ +github.com/Luzifer/go_helpers v2.8.1+incompatible h1:9YvrAn7pU2viK5vRpAnI+0gyz+Tw8rxWHVIYHi642zk= +github.com/Luzifer/go_helpers/v2 v2.9.1 h1:MVUOlD6tJ2m/iTF0hllnI/QVZH5kI+TikUm1WRGg/c4= +github.com/Luzifer/go_helpers/v2 v2.9.1/go.mod h1:ZnWxPjyCdQ4rZP3kNiMSUW/7FigU1X9Rz8XopdJ5ZCU= +github.com/Luzifer/rconfig v2.2.0+incompatible h1:Kle3+rshPM7LxciOheaR4EfHUzibkDDGws04sefQ5m8= +github.com/Luzifer/rconfig/v2 v2.2.1 h1:zcDdLQlnlzwcBJ8E0WFzOkQE1pCMn3EbX0dFYkeTczg= +github.com/Luzifer/rconfig/v2 v2.2.1/go.mod h1:OKIX0/JRZrPJ/ZXXWklQEFXA6tBfWaljZbW37w+sqBw= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf/go.mod h1:hyb9oH7vZsitZCiBt0ZvifOrB+qc8PS5IiilCIb87rg= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/leekchan/gtf v0.0.0-20190214083521-5fba33c5b00b/go.mod h1:thNruaSwydMhkQ8dXzapABF9Sc1Tz08ZBcDdgott9RA= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.2 h1:uqH7bpe+ERSiDa34FDOF7RikN6RzXgduUF8yarlZp94= +github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/tenfyzhong/cityhash v0.0.0-20181130044406-4c2731b5918c h1:Y3PUeYj+OuuOy7BnbIvtGOj9YDKjPHsZyN/2AJqN32s= +github.com/tenfyzhong/cityhash v0.0.0-20181130044406-4c2731b5918c/go.mod h1:Izvvi9mFtnF9nbPc2Z/gazIliNnYtxOsbQnFYpmxbfc= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/validator.v2 v2.0.0-20180514200540-135c24b11c19 h1:WB265cn5OpO+hK3pikC9hpP1zI/KTwmyMFKloW9eOVc= +gopkg.in/validator.v2 v2.0.0-20180514200540-135c24b11c19/go.mod h1:o4V0GXN9/CAmCsvJ0oXYZvrZOe7syiDZSN1GWGZTGzc= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go new file mode 100644 index 0000000..7e28440 --- /dev/null +++ b/main.go @@ -0,0 +1,132 @@ +package main + +import ( + "fmt" + "io" + "os" + "path" + + "github.com/Luzifer/go_helpers/v2/str" + "github.com/Luzifer/rconfig/v2" + "github.com/Luzifer/scs-extract/scs" + log "github.com/sirupsen/logrus" +) + +var ( + cfg = struct { + Dest string `flag:"dest,d" default:"." description:"Path prefix to use to extract files to"` + Extract bool `flag:"extract,x" default:"false" description:"Extract files (if not given files are just listed)"` + LogLevel string `flag:"log-level" default:"info" description:"Log level (debug, info, warn, error, fatal)"` + VersionAndExit bool `flag:"version" default:"false" description:"Prints current version and exits"` + }{} + + version = "dev" +) + +func init() { + if err := rconfig.ParseAndValidate(&cfg); err != nil { + log.Fatalf("Unable to parse commandline options: %s", err) + } + + if cfg.VersionAndExit { + fmt.Printf("scs-extract %s\n", version) + os.Exit(0) + } + + if l, err := log.ParseLevel(cfg.LogLevel); err != nil { + log.WithError(err).Fatal("Unable to parse log level") + } else { + log.SetLevel(l) + } +} + +func main() { + var ( + archive string + extract []string + ) + + switch len(rconfig.Args()) { + case 1: + // No positional arguments + log.Fatal("No SCS archive given") + + case 2: + archive = rconfig.Args()[1] + + default: + archive = rconfig.Args()[1] + extract = rconfig.Args()[2:] + } + + f, err := os.Open(archive) + if err != nil { + log.WithError(err).Fatal("Unable to open input file") + } + defer f.Close() + + r, err := scs.NewReader(f, 0) + if err != nil { + log.WithError(err).Fatal("Unable to read SCS file headers") + } + + log.WithField("no_files", len(r.Files)).Debug("Opened archive") + + destInfo, err := os.Stat(cfg.Dest) + if err != nil { + if !os.IsNotExist(err) { + log.WithError(err).Fatal("Unable to access destination") + } + + if err := os.MkdirAll(cfg.Dest, 0755); err != nil { + log.WithError(err).Fatal("Unable to create destination directory") + } + } + + if destInfo != nil && !destInfo.IsDir() { + log.Fatal("Destination exists and is no directory") + } + + for _, file := range r.Files { + if !str.StringInSlice(file.Name, extract) && len(extract) > 0 { + // Files to extract are given but this is not mentioned + continue + } + + if file.Type == scs.EntryTypeCompressedNames || file.Type == scs.EntryTypeCompressedNamesCopy || + file.Type == scs.EntryTypeUncompressedNames || file.Type == scs.EntryTypeUncompressedNamesCopy { + // Don't care about directories, if they contain files they will be created + continue + } + + if !cfg.Extract { + // Not asked to extract, do not extract + fmt.Println(file.Name) + continue + } + + destPath := path.Join(cfg.Dest, file.Name) + if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil { + log.WithError(err).Fatal("Unable to create directory") + } + + src, err := file.Open() + if err != nil { + log.WithError(err).Fatal("Unable to open file from archive") + } + + dest, err := os.Create(destPath) + if err != nil { + log.WithError(err).Fatal("Unable to create destination file") + } + + if _, err = io.Copy(dest, src); err != nil { + log.WithError(err).Fatal("Unable to write file contents") + } + + dest.Close() + src.Close() + + log.WithField("file", file.Name).Info("File extracted") + } +} diff --git a/scs/scs.go b/scs/scs.go new file mode 100644 index 0000000..b3f7b18 --- /dev/null +++ b/scs/scs.go @@ -0,0 +1,198 @@ +package scs + +import ( + "bufio" + "bytes" + "compress/flate" + "encoding/binary" + "io" + "io/ioutil" + "path" + "reflect" + "strings" + + "github.com/Luzifer/scs-extract/b0rkhash" + "github.com/pkg/errors" +) + +var rootPathHash = b0rkhash.CityHash64([]byte("")) + +type CatalogEntry struct { + HashedPath uint64 + Offset int32 + _ int32 + Type EntryType + CRC uint32 + Size int32 + ZSize int32 +} + +type EntryType int32 + +// See https://forum.scssoft.com/viewtopic.php?p=644638#p644638 +const ( + EntryTypeUncompressedFile EntryType = iota + EntryTypeUncompressedNames + EntryTypeCompressedFile + EntryTypeCompressedNames + EntryTypeUncompressedFileCopy + EntryTypeUncompressedNamesCopy + EntryTypeCompressedFileCopy + EntryTypeCompressedNamesCopy +) + +type File struct { + Name string + + archiveReader io.ReaderAt + + CatalogEntry +} + +func (f *File) Open() (io.ReadCloser, error) { + var rc io.ReadCloser + + switch f.Type { + + case EntryTypeCompressedFile, EntryTypeCompressedFileCopy, EntryTypeCompressedNames, EntryTypeCompressedNamesCopy: + r := io.NewSectionReader(f.archiveReader, int64(f.Offset+2), int64(f.ZSize)) + rc = flate.NewReader(r) + + case EntryTypeUncompressedFile, EntryTypeUncompressedFileCopy, EntryTypeUncompressedNames, EntryTypeUncompressedNamesCopy: + r := io.NewSectionReader(f.archiveReader, int64(f.Offset), int64(f.Size)) + rc = ioutil.NopCloser(r) + + } + return rc, nil +} + +type Reader struct { + Files []*File +} + +func NewReader(r io.ReaderAt, size int64) (*Reader, error) { + var magic = make([]byte, 4) + n, err := r.ReadAt(magic, 0) + if err != nil || n != 4 { + return nil, errors.Wrap(err, "Unable to read file magic") + } + + if !reflect.DeepEqual(magic, []byte{0x53, 0x43, 0x53, 0x23}) { + return nil, errors.New("Did not receive expected file magic") + } + + var entries = make([]byte, 4) + n, err = r.ReadAt(entries, 0xC) + if err != nil || n != 4 { + return nil, errors.Wrap(err, "Unable to read entry count") + } + + var entryCount int32 + if err = binary.Read(bytes.NewReader(entries), binary.LittleEndian, &entryCount); err != nil { + return nil, errors.Wrap(err, "Unable to parse entry count") + } + + out := &Reader{} + + var offset int64 = 0x1000 + for i := int32(0); i < entryCount; i++ { + var hdr = make([]byte, 32) + n, err = r.ReadAt(hdr, offset) + if err != nil || n != 32 { + return nil, errors.Wrap(err, "Unable to read file header") + } + + var e = CatalogEntry{} + if err = binary.Read(bytes.NewReader(hdr), binary.LittleEndian, &e); err != nil { + return nil, errors.Wrap(err, "Unable to parse file header") + } + + out.Files = append(out.Files, &File{ + CatalogEntry: e, + archiveReader: r, + }) + offset += 32 + } + + return out, out.populateFileNames() +} + +func (r *Reader) populateFileNames() error { + // first seek root entry, without the archive is not usable for us + var entry *File + for _, e := range r.Files { + if e.HashedPath == rootPathHash { + entry = e + break + } + } + + if entry == nil || + (entry.ZSize == 0 && entry.Size == 0) || + (entry.Type != EntryTypeCompressedNames && + entry.Type != EntryTypeCompressedNamesCopy && + entry.Type != EntryTypeUncompressedNames && + entry.Type != EntryTypeUncompressedNamesCopy) { + return errors.New("No root path entry found or root path empty") + } + + entry.Name = "" + + return r.populateFileTree(entry) +} + +func (r *Reader) populateFileTree(node *File) error { + f, err := node.Open() + if err != nil { + return errors.Wrap(err, "Unable to open file") + } + defer f.Close() + + var entries []string + + scanner := bufio.NewScanner(f) + for scanner.Scan() { + entries = append(entries, scanner.Text()) + } + + if err := scanner.Err(); err != nil { + return errors.Wrap(err, "Unable to read from file") + } + + for _, entry := range entries { + var ( + hash uint64 + recurse bool + ) + + if entry[0] == '*' { + // Directory here + recurse = true + entry = entry[1:] + } + + hash = b0rkhash.CityHash64([]byte(strings.TrimPrefix(path.Join(node.Name, entry), "/"))) + + var next *File + for _, rf := range r.Files { + if rf.HashedPath == hash { + next = rf + break + } + } + + if next == nil { + return errors.Errorf("Found missing reference: %s", path.Join(node.Name, entry)) + } + + next.Name = strings.TrimPrefix(path.Join(node.Name, entry), "/") + if recurse { + if err = r.populateFileTree(next); err != nil { + return err + } + } + + } + + return nil +}