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
extern crate java_data_io_rs;

use java_data_io_rs::{from_java_string, to_java_string, JavaDataInput, JavaDataOutput};
use std::convert::TryFrom;
use std::error;
use std::fmt;
use std::io;
use std::result;
use std::string;

const FORMAT_VERSION: i32 = 2;

pub(crate) type Result<T> = result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    IoError(io::Error),
    FormatError(String),
}

macro_rules! def_value_type {
    ($x:tt,) => (1);
    ($x:tt, $($y:tt,)*) => (1+def_value_type!($($y,)*));
    ($t:ty) => {
        impl TryFrom<$t> for ValueType {
            type Error = Error;
            fn try_from(v: $t) -> result::Result<Self, Self::Error> {
                VALUE_TYPES
                    .get(v as usize)
                    .copied()
                    .ok_or_else(|| Error::FormatError(format!("Invalid ValueType ({})", v)))
            }
        }
    };
    ($($t:ty;)*) => { $(def_value_type!($t);)* };
    ($($a:tt $b:tt $c:tt,)*) => {

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum ValueType {
            $($a $b $c,)*
        }

        static VALUE_TYPES: [ValueType; def_value_type!($($a,)*)] = {
            use ValueType::*;
            let mut table = [
                $($a,)*
            ];
            $(table[$a as usize] = $a;)*
            table
        };

        def_value_type!(i8;i16;i32;i64;u8;u16;u32;u64;);
    };
}

def_value_type!(
    ServiceName = 0,
    ServiceUrl = 1,
    Id = 2,
    Password = 3,
    Email = 4,
    ReminderQuestion = 5,
    ReminderAnswer = 6,
    Description = 7,
);

impl fmt::Display for ValueType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ValueType::*;
        match self {
            ServiceName => write!(f, "service name"),
            ServiceUrl => write!(f, "service url"),
            Id => write!(f, "id"),
            Password => write!(f, "password"),
            Email => write!(f, "email"),
            ReminderQuestion => write!(f, "reminder question"),
            ReminderAnswer => write!(f, "reminder answer"),
            Description => write!(f, "description"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Value {
    pub value_type: ValueType,
    pub value: String,
}

#[derive(Debug, PartialEq, Eq)]
pub struct Service {
    pub time: i64,
    pub values: Vec<Value>,
    pub(crate) secrets: Vec<u8>,
}

#[derive(Debug)]
pub(crate) struct Memo {
    pub(crate) services: Vec<Service>,
}

impl Value {
    pub fn new(value_type: ValueType, value: &str) -> Self {
        Self {
            value_type,
            value: value.into(),
        }
    }

    pub(crate) fn save<W>(&self, dst: &mut JavaDataOutput<W>) -> Result<()>
    where
        W: io::Write,
    {
        dst.write_byte(self.value_type as i32)?;
        dst.write_utf(&to_java_string(&self.value))?;
        Ok(())
    }

    pub(crate) fn load<R>(src: &mut JavaDataInput<R>) -> Result<Value>
    where
        R: io::Read,
    {
        let t = src.read_byte()?;
        let s = src.read_utf()?;
        Ok(Value {
            value_type: ValueType::try_from(t)?,
            value: from_java_string(&s)?,
        })
    }

    pub fn is_empty(&self) -> bool {
        self.value.trim().is_empty()
    }
}

impl Service {
    pub fn new(name: &str) -> Self {
        let v = Value::new(ValueType::ServiceName, name);
        Self {
            time: 0,
            values: vec![v],
            secrets: Vec::new(),
        }
    }

    pub fn get_service_name(&self) -> &str {
        for v in self.values.iter() {
            if matches!(v.value_type, ValueType::ServiceName) {
                return &v.value;
            }
        }
        ""
    }

    pub(crate) fn save<W>(&self, dst: &mut JavaDataOutput<W>) -> Result<()>
    where
        W: io::Write,
    {
        dst.write_long(self.time)?;
        let values = Service::filter_values(&self.values);
        dst.write_int(values.len() as i32)?;
        for v in values {
            v.save(dst)?;
        }
        dst.write_int(self.secrets.len() as i32)?;
        dst.write(&self.secrets)?;
        Ok(())
    }

    pub(crate) fn load_v1<R>(src: &mut JavaDataInput<R>) -> Result<Service>
    where
        R: io::Read,
    {
        let vc = src.read_int()?;
        if vc < 0 {
            return Err(Error::FormatError(format!("invalid value count ({})", vc)));
        }
        let mut values: Vec<Value> = Vec::with_capacity(vc as usize);
        for _ in 0..vc {
            let v = Value::load(src)?;
            values.push(v);
        }
        let sc = src.read_int()?;
        if sc < 0 {
            return Err(Error::FormatError(format!("invalid secret size ({})", sc)));
        }
        let mut secrets: Vec<u8> = vec![0; sc as usize];
        src.read_fully(&mut secrets)?;
        Ok(Service {
            time: 0,
            values,
            secrets,
        })
    }

    pub(crate) fn load<R>(src: &mut JavaDataInput<R>) -> Result<Service>
    where
        R: io::Read,
    {
        let time = src.read_long()?;
        let vc = src.read_int()?;
        if vc < 0 {
            return Err(Error::FormatError(format!("invalid value count ({})", vc)));
        }
        let mut values: Vec<Value> = Vec::with_capacity(vc as usize);
        for _ in 0..vc {
            let v = Value::load(src)?;
            values.push(v);
        }
        let sc = src.read_int()?;
        if sc < 0 {
            return Err(Error::FormatError(format!("invalid secret size ({})", sc)));
        }
        let mut secrets: Vec<u8> = vec![0; sc as usize];
        src.read_fully(&mut secrets)?;
        Ok(Service {
            time,
            values,
            secrets,
        })
    }

    pub(crate) fn filter_values(values: &[Value]) -> Vec<&Value> {
        values.iter().filter(|v| !v.is_empty()).collect()
    }

    pub(crate) fn write_secrets<W>(dst: &mut JavaDataOutput<W>, values: &[&Value]) -> Result<()>
    where
        W: io::Write,
    {
        dst.write_int(values.len() as i32)?;
        for v in values {
            v.save(dst)?;
        }
        Ok(())
    }

    pub(crate) fn read_secrets<R>(src: &mut JavaDataInput<R>) -> Result<Vec<Value>>
    where
        R: io::Read,
    {
        let count = src.read_int()?;
        if count < 0 {
            return Err(Error::FormatError(format!(
                "invalid secret value count({})",
                count
            )));
        }
        let mut values: Vec<Value> = Vec::with_capacity(count as usize);
        for _ in 0..count {
            let v = Value::load(src)?;
            values.push(v);
        }
        Ok(values)
    }
}

impl Memo {
    pub(crate) fn new(services: Vec<Service>) -> Self {
        Self { services }
    }

    pub(crate) fn save<W>(&self, dst: &mut JavaDataOutput<W>) -> Result<()>
    where
        W: io::Write,
    {
        dst.write_int(FORMAT_VERSION)?;
        let services: Vec<_> = self
            .services
            .iter()
            .filter(|s| !s.get_service_name().trim().is_empty())
            .collect();
        dst.write_int(services.len() as i32)?;
        for s in services {
            s.save(dst)?;
        }
        Ok(())
    }

    pub(crate) fn load<R>(src: &mut JavaDataInput<R>) -> Result<Memo>
    where
        R: io::Read,
    {
        let version = src.read_int()?;
        if !(0..=FORMAT_VERSION).contains(&version) {
            return Err(Error::FormatError(format!(
                "Unsupport Format Version ({})",
                version
            )));
        }
        let count = src.read_int()?;
        if count < 0 {
            return Err(Error::FormatError(format!(
                "invalid service count({})",
                count
            )));
        }
        let mut services: Vec<Service> = Vec::with_capacity(count as usize);
        for _ in 0..count {
            let s = if version == 1 {
                Service::load_v1(src)?
            } else {
                Service::load(src)?
            };
            services.push(s);
        }
        Ok(Memo { services })
    }
}

impl From<java_data_io_rs::Error> for Error {
    fn from(err: java_data_io_rs::Error) -> Self {
        use java_data_io_rs::Error::IoError;
        match err {
            IoError(err) => Error::IoError(err),
            err => Error::FormatError(format!("{}", err)),
        }
    }
}

impl From<string::FromUtf16Error> for Error {
    fn from(err: string::FromUtf16Error) -> Self {
        Error::FormatError(format!("{}", err))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            IoError(ref e) => fmt::Display::fmt(e, f),
            FormatError(ref s) => write!(f, "FormatError({})", s),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use Error::*;
        match self {
            IoError(ref e) => Some(e),
            FormatError(_) => None,
        }
    }
}