blob: 6a7c03c07c7c808fa43534179583b69541ba3864 [file] [log] [blame]
gauthamtb7bb39b2014-11-10 11:40:41 -08001package security
2
3import (
4 "io"
gauthamt1e313bc2014-11-10 15:45:56 -08005 "os"
gauthamtb7bb39b2014-11-10 11:40:41 -08006)
7
8// SerializerReaderWriter is a factory for managing the readers and writers used for
9// serialization and deserialization of signed data.
10type SerializerReaderWriter interface {
11 // Readers returns io.ReadCloser for reading serialized data and its
12 // integrity signature.
13 Readers() (data io.ReadCloser, signature io.ReadCloser, err error)
14 // Writers returns io.WriteCloser for writing serialized data and its
15 // integrity signature.
16 Writers() (data io.WriteCloser, signature io.WriteCloser, err error)
17}
gauthamt1e313bc2014-11-10 15:45:56 -080018
19// FileSerializer implements SerializerReaderWriter that persists state to files.
20type FileSerializer struct {
gauthamt1e313bc2014-11-10 15:45:56 -080021 dataFilePath string
22 signatureFilePath string
23}
24
25// NewFileSerializer creates a FileSerializer with the given data and signature files.
Ankur27c56fd2014-11-17 19:30:34 -080026func NewFileSerializer(dataFilePath, signatureFilePath string) *FileSerializer {
gauthamt1e313bc2014-11-10 15:45:56 -080027 return &FileSerializer{
gauthamt1e313bc2014-11-10 15:45:56 -080028 dataFilePath: dataFilePath,
29 signatureFilePath: signatureFilePath,
Ankur27c56fd2014-11-17 19:30:34 -080030 }
gauthamt1e313bc2014-11-10 15:45:56 -080031}
32
33func (fs *FileSerializer) Readers() (io.ReadCloser, io.ReadCloser, error) {
Ankur27c56fd2014-11-17 19:30:34 -080034 data, err := os.Open(fs.dataFilePath)
35 if err != nil && !os.IsNotExist(err) {
36 return nil, nil, err
37 }
38 signature, err := os.Open(fs.signatureFilePath)
39 if err != nil && !os.IsNotExist(err) {
40 return nil, nil, err
41 }
42 if data == nil || signature == nil {
gauthamt1e313bc2014-11-10 15:45:56 -080043 return nil, nil, nil
44 }
Ankur27c56fd2014-11-17 19:30:34 -080045 return data, signature, nil
gauthamt1e313bc2014-11-10 15:45:56 -080046}
47
48func (fs *FileSerializer) Writers() (io.WriteCloser, io.WriteCloser, error) {
49 // Remove previous version of the files
50 os.Remove(fs.dataFilePath)
51 os.Remove(fs.signatureFilePath)
Ankur27c56fd2014-11-17 19:30:34 -080052 data, err := os.Create(fs.dataFilePath)
53 if err != nil {
gauthamt1e313bc2014-11-10 15:45:56 -080054 return nil, nil, err
55 }
Ankur27c56fd2014-11-17 19:30:34 -080056 signature, err := os.Create(fs.signatureFilePath)
57 if err != nil {
gauthamt1e313bc2014-11-10 15:45:56 -080058 return nil, nil, err
59 }
Ankur27c56fd2014-11-17 19:30:34 -080060 return data, signature, nil
gauthamt1e313bc2014-11-10 15:45:56 -080061}