2020-12-25 18:54:07 +00:00
|
|
|
package kgm
|
|
|
|
|
|
|
|
import (
|
2022-11-18 23:25:42 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-11-18 23:25:38 +00:00
|
|
|
|
2021-03-02 10:16:19 +00:00
|
|
|
"github.com/unlock-music/cli/algo/common"
|
2020-12-25 18:54:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Decoder struct {
|
2022-11-18 23:25:43 +00:00
|
|
|
header header
|
|
|
|
cipher common.StreamDecoder
|
2022-11-18 23:25:42 +00:00
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
rd io.ReadSeeker
|
|
|
|
offset int
|
2022-11-18 23:25:42 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
func NewDecoder(rd io.ReadSeeker) common.Decoder {
|
|
|
|
return &Decoder{rd: rd}
|
2020-12-25 18:54:07 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
var kgmCryptoInitializers = map[uint32]func(header *header) (common.StreamDecoder, error){
|
|
|
|
3: newKgmCryptoV3,
|
2020-12-25 18:54:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Decoder) Validate() error {
|
2022-11-18 23:25:43 +00:00
|
|
|
if err := d.header.FromFile(d.rd); err != nil {
|
2022-11-18 23:25:42 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
// TODO; validate crypto version
|
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
initializer, ok := kgmCryptoInitializers[d.header.CryptoVersion]
|
2022-11-18 23:25:42 +00:00
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("kgm: unsupported crypto version %d", d.header.CryptoVersion)
|
2020-12-25 18:54:07 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
var err error
|
|
|
|
d.cipher, err = initializer(&d.header)
|
2022-11-18 23:25:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("kgm: failed to initialize crypto: %w", err)
|
|
|
|
}
|
2022-11-18 23:25:43 +00:00
|
|
|
|
2020-12-25 18:54:07 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-11-18 23:25:42 +00:00
|
|
|
|
2022-11-18 23:25:43 +00:00
|
|
|
func (d *Decoder) Read(buf []byte) (int, error) {
|
|
|
|
n, err := d.rd.Read(buf)
|
|
|
|
if n > 0 {
|
|
|
|
d.cipher.Decrypt(buf[:n], d.offset)
|
|
|
|
d.offset += n
|
|
|
|
}
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
2020-12-26 07:47:10 +00:00
|
|
|
func init() {
|
|
|
|
// Kugou
|
2021-11-11 15:43:20 +00:00
|
|
|
common.RegisterDecoder("kgm", false, NewDecoder)
|
|
|
|
common.RegisterDecoder("kgma", false, NewDecoder)
|
2020-12-26 07:47:10 +00:00
|
|
|
// Viper
|
2021-11-11 15:43:20 +00:00
|
|
|
common.RegisterDecoder("vpr", false, NewDecoder)
|
2020-12-26 07:47:10 +00:00
|
|
|
}
|