heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Heroforge sync protocol implementation.
//!
//! This implements the wire protocol for Heroforge synchronization.

use crate::error::Result;
use crate::hash;
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::{Read, Write};

/// A card in the Heroforge sync protocol.
#[derive(Debug, Clone)]
pub enum Card {
    /// Login card: login userid nonce signature
    Login {
        userid: String,
        nonce: String,
        signature: String,
    },
    /// Push card: push servercode projectcode
    Push {
        servercode: String,
        projectcode: String,
    },
    /// Pull card: pull servercode projectcode
    Pull {
        servercode: String,
        projectcode: String,
    },
    /// Clone card: clone [protocol-version sequence-number]
    Clone {
        protocol_version: Option<u32>,
        sequence_number: Option<u64>,
    },
    /// File card: file artifact-id [delta-source-id] size \n content
    File {
        artifact_id: String,
        delta_source: Option<String>,
        content: Vec<u8>,
    },
    /// Compressed file card (for clone protocol 3+)
    CFile {
        artifact_id: String,
        delta_source: Option<String>,
        uncompressed_size: usize,
        content: Vec<u8>,
    },
    /// Igot card: igot artifact-id [private-flag]
    Igot {
        artifact_id: String,
        is_private: bool,
    },
    /// Gimme card: gimme artifact-id
    Gimme { artifact_id: String },
    /// Cookie card: cookie payload
    Cookie { payload: String },
    /// Error card: error message
    Error { message: String },
    /// Message card: message text
    Message { text: String },
    /// Pragma card: pragma name value...
    Pragma { name: String, values: Vec<String> },
    /// Comment card: # text
    Comment { text: String },
    /// Private marker (precedes a file card)
    Private,
    /// Clone sequence number response
    CloneSeqNo { sequence_number: u64 },
    /// Request config card
    ReqConfig { name: String },
    /// Config card with content
    Config { name: String, content: Vec<u8> },
}

/// A sync protocol message (request or response).
#[derive(Debug, Clone, Default)]
pub struct Message {
    pub cards: Vec<Card>,
}

impl Message {
    /// Create a new empty message.
    pub fn new() -> Self {
        Self { cards: Vec::new() }
    }

    /// Add a card to the message.
    pub fn add(&mut self, card: Card) {
        self.cards.push(card);
    }

    /// Encode the message to bytes (compressed with size prefix).
    ///
    /// Heroforge's HTTP sync protocol uses a 4-byte big-endian size prefix
    /// (uncompressed size) before the zlib-compressed data.
    pub fn encode(&self) -> Result<Vec<u8>> {
        let text = self.to_text()?;
        let uncompressed_size = text.len() as u32;
        let compressed = compress(text.as_bytes())?;

        // Build result with 4-byte size prefix
        let mut result = Vec::with_capacity(4 + compressed.len());
        result.extend_from_slice(&uncompressed_size.to_be_bytes());
        result.extend_from_slice(&compressed);

        Ok(result)
    }

    /// Encode the message to text (uncompressed, for debugging).
    pub fn to_text(&self) -> Result<String> {
        let mut lines: Vec<String> = Vec::new();

        for card in &self.cards {
            lines.push(card.to_line()?);
        }

        Ok(lines.join(""))
    }

    /// Decode a message from compressed bytes.
    ///
    /// This properly handles binary file content within the message.
    pub fn decode(data: &[u8]) -> Result<Self> {
        let bytes = decompress_bytes(data)?;
        Self::from_bytes(&bytes)
    }

    /// Parse a message from uncompressed bytes.
    ///
    /// This handles binary file/cfile content properly.
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        let mut message = Message::new();
        let mut pos = 0;

        while pos < data.len() {
            // Skip whitespace
            while pos < data.len()
                && (data[pos] == b' ' || data[pos] == b'\n' || data[pos] == b'\r')
            {
                pos += 1;
            }
            if pos >= data.len() {
                break;
            }

            // Find end of line
            let line_start = pos;
            while pos < data.len() && data[pos] != b'\n' {
                pos += 1;
            }
            let line_end = pos;
            if pos < data.len() {
                pos += 1; // Skip newline
            }

            let line = String::from_utf8_lossy(&data[line_start..line_end]);
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            let parts: Vec<&str> = line.splitn(2, ' ').collect();
            let op = parts[0];
            let args = parts.get(1).unwrap_or(&"");

            match op {
                "file" | "cfile" => {
                    // file artifact-id size                    (3 parts total, 2 args)
                    // file artifact-id delta-src size          (4 parts total, 3 args)
                    // cfile artifact-id size usize             (4 parts total, 3 args)
                    // cfile artifact-id delta-src size usize   (5 parts total, 4 args)
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let (artifact_id, delta_source, size) = if op == "cfile" {
                            // cfile: artifact-id [delta-src] size usize
                            // parts[0] = artifact-id
                            // If 4+ parts: parts[1]=delta, parts[2]=size, parts[3]=usize
                            // If 3 parts: parts[1]=size, parts[2]=usize (no delta)
                            if parts.len() >= 4 {
                                (
                                    parts[0].to_string(),
                                    Some(parts[1].to_string()),
                                    parts[2].parse::<usize>().unwrap_or(0),
                                )
                            } else if parts.len() == 3 {
                                (
                                    parts[0].to_string(),
                                    None,
                                    parts[1].parse::<usize>().unwrap_or(0),
                                )
                            } else {
                                continue;
                            }
                        } else {
                            // file: artifact-id [delta-src] size
                            // parts[0] = artifact-id
                            // If 3+ parts: check if parts[1] looks like a hash (delta) or number (size)
                            // If 2 parts: parts[1] = size (no delta)
                            if parts.len() >= 3 {
                                // Could be "artifact delta size" or misparse
                                // Delta source is a 64-char hash, size is a number
                                if parts[1].len() == 64
                                    && parts[1].chars().all(|c| c.is_ascii_hexdigit())
                                {
                                    // parts[1] is a hash -> delta source
                                    (
                                        parts[0].to_string(),
                                        Some(parts[1].to_string()),
                                        parts[2].parse::<usize>().unwrap_or(0),
                                    )
                                } else {
                                    // parts[1] is size, no delta
                                    (
                                        parts[0].to_string(),
                                        None,
                                        parts[1].parse::<usize>().unwrap_or(0),
                                    )
                                }
                            } else {
                                (
                                    parts[0].to_string(),
                                    None,
                                    parts[1].parse::<usize>().unwrap_or(0),
                                )
                            }
                        };

                        // Read the content bytes
                        let content_end = (pos + size).min(data.len());
                        let content = data[pos..content_end].to_vec();
                        pos = content_end;

                        if op == "cfile" {
                            message.add(Card::CFile {
                                artifact_id,
                                delta_source,
                                content,
                                uncompressed_size: parts
                                    .last()
                                    .and_then(|s| s.parse().ok())
                                    .unwrap_or(0),
                            });
                        } else {
                            message.add(Card::File {
                                artifact_id,
                                delta_source,
                                content,
                            });
                        }
                    }
                }
                _ => {
                    // Handle other cards via text parsing
                    if let Some(card) = Self::parse_text_card(op, args) {
                        message.add(card);
                    }
                }
            }
        }

        Ok(message)
    }

    /// Parse a non-file card from text.
    fn parse_text_card(op: &str, args: &str) -> Option<Card> {
        match op {
            "login" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                if parts.len() >= 3 {
                    Some(Card::Login {
                        userid: decode_fossil_string(parts[0]),
                        nonce: parts[1].to_string(),
                        signature: parts[2].to_string(),
                    })
                } else {
                    None
                }
            }
            "push" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                if parts.len() >= 2 {
                    Some(Card::Push {
                        servercode: parts[0].to_string(),
                        projectcode: parts[1].to_string(),
                    })
                } else {
                    None
                }
            }
            "pull" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                if parts.len() >= 2 {
                    Some(Card::Pull {
                        servercode: parts[0].to_string(),
                        projectcode: parts[1].to_string(),
                    })
                } else {
                    None
                }
            }
            "clone" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                Some(Card::Clone {
                    protocol_version: parts.first().and_then(|s| s.parse().ok()),
                    sequence_number: parts.get(1).and_then(|s| s.parse().ok()),
                })
            }
            "clone_seqno" => Some(Card::CloneSeqNo {
                sequence_number: args.trim().parse().unwrap_or(0),
            }),
            "igot" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                if !parts.is_empty() {
                    Some(Card::Igot {
                        artifact_id: parts[0].to_string(),
                        is_private: parts.get(1).map(|&s| s == "1").unwrap_or(false),
                    })
                } else {
                    None
                }
            }
            "gimme" => Some(Card::Gimme {
                artifact_id: args.trim().to_string(),
            }),
            "cookie" => Some(Card::Cookie {
                payload: decode_fossil_string(args.trim()),
            }),
            "error" => Some(Card::Error {
                message: decode_fossil_string(args.trim()),
            }),
            "pragma" => {
                let parts: Vec<&str> = args.split_whitespace().collect();
                if !parts.is_empty() {
                    Some(Card::Pragma {
                        name: parts[0].to_string(),
                        values: parts[1..].iter().map(|s| s.to_string()).collect(),
                    })
                } else {
                    None
                }
            }
            _ => {
                // Unknown card type - ignore
                None
            }
        }
    }

    /// Parse a message from uncompressed text.
    pub fn from_text(text: &str) -> Result<Self> {
        let mut message = Message::new();
        let mut lines = text.lines().peekable();

        while let Some(line) = lines.next() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            let parts: Vec<&str> = line.splitn(2, ' ').collect();
            let op = parts[0];
            let args = parts.get(1).unwrap_or(&"");

            match op {
                "login" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 3 {
                        message.add(Card::Login {
                            userid: decode_fossil_string(parts[0]),
                            nonce: parts[1].to_string(),
                            signature: parts[2].to_string(),
                        });
                    }
                }
                "push" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 2 {
                        message.add(Card::Push {
                            servercode: parts[0].to_string(),
                            projectcode: parts[1].to_string(),
                        });
                    }
                }
                "pull" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 2 {
                        message.add(Card::Pull {
                            servercode: parts[0].to_string(),
                            projectcode: parts[1].to_string(),
                        });
                    }
                }
                "clone" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 2 {
                        message.add(Card::Clone {
                            protocol_version: parts[0].parse().ok(),
                            sequence_number: parts[1].parse().ok(),
                        });
                    } else {
                        message.add(Card::Clone {
                            protocol_version: None,
                            sequence_number: None,
                        });
                    }
                }
                "file" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if parts.len() >= 2 {
                        let (artifact_id, delta_source, _size) = if parts.len() == 2 {
                            (
                                parts[0].to_string(),
                                None,
                                parts[1].parse::<usize>().unwrap_or(0),
                            )
                        } else {
                            (
                                parts[0].to_string(),
                                Some(parts[1].to_string()),
                                parts[2].parse::<usize>().unwrap_or(0),
                            )
                        };

                        // Read inline content - this is tricky with lines iterator
                        // For now, we'll handle this in a more complete parser
                        message.add(Card::File {
                            artifact_id,
                            delta_source,
                            content: Vec::new(), // Content parsed separately
                        });
                    }
                }
                "igot" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if !parts.is_empty() {
                        let is_private = parts.get(1).map(|&s| s == "1").unwrap_or(false);
                        message.add(Card::Igot {
                            artifact_id: parts[0].to_string(),
                            is_private,
                        });
                    }
                }
                "gimme" => {
                    message.add(Card::Gimme {
                        artifact_id: args.trim().to_string(),
                    });
                }
                "cookie" => {
                    message.add(Card::Cookie {
                        payload: args.to_string(),
                    });
                }
                "error" => {
                    message.add(Card::Error {
                        message: decode_fossil_string(args),
                    });
                }
                "message" => {
                    message.add(Card::Message {
                        text: decode_fossil_string(args),
                    });
                }
                "pragma" => {
                    let parts: Vec<&str> = args.split_whitespace().collect();
                    if !parts.is_empty() {
                        message.add(Card::Pragma {
                            name: parts[0].to_string(),
                            values: parts[1..].iter().map(|s| s.to_string()).collect(),
                        });
                    }
                }
                "private" => {
                    message.add(Card::Private);
                }
                "clone_seqno" => {
                    if let Ok(seq) = args.trim().parse() {
                        message.add(Card::CloneSeqNo {
                            sequence_number: seq,
                        });
                    }
                }
                "reqconfig" => {
                    message.add(Card::ReqConfig {
                        name: args.trim().to_string(),
                    });
                }
                _ if op.starts_with('#') => {
                    message.add(Card::Comment {
                        text: line.to_string(),
                    });
                }
                _ => {
                    // Unknown card type - skip
                }
            }
        }

        Ok(message)
    }

    /// Create a login card with proper signature.
    pub fn create_login(userid: &str, password: &str, payload: &str) -> Card {
        // nonce = SHA1(payload)
        let nonce = hash::sha1_hex(payload.as_bytes());
        // signature = SHA1(nonce + password)
        let sig_input = format!("{}{}", nonce, password);
        let signature = hash::sha1_hex(sig_input.as_bytes());

        Card::Login {
            userid: userid.to_string(),
            nonce,
            signature,
        }
    }
}

impl Card {
    /// Convert a card to its line representation.
    pub fn to_line(&self) -> Result<String> {
        match self {
            Card::Login {
                userid,
                nonce,
                signature,
            } => Ok(format!(
                "login {} {} {}\n",
                encode_fossil_string(userid),
                nonce,
                signature
            )),
            Card::Push {
                servercode,
                projectcode,
            } => Ok(format!("push {} {}\n", servercode, projectcode)),
            Card::Pull {
                servercode,
                projectcode,
            } => Ok(format!("pull {} {}\n", servercode, projectcode)),
            Card::Clone {
                protocol_version,
                sequence_number,
            } => {
                if let (Some(pv), Some(seq)) = (protocol_version, sequence_number) {
                    Ok(format!("clone {} {}\n", pv, seq))
                } else {
                    Ok("clone\n".to_string())
                }
            }
            Card::File {
                artifact_id,
                delta_source,
                content,
            } => {
                if let Some(delta) = delta_source {
                    Ok(format!(
                        "file {} {} {}\n",
                        artifact_id,
                        delta,
                        content.len()
                    ))
                } else {
                    Ok(format!("file {} {}\n", artifact_id, content.len()))
                }
            }
            Card::CFile {
                artifact_id,
                delta_source,
                uncompressed_size,
                content,
            } => {
                if let Some(delta) = delta_source {
                    Ok(format!(
                        "cfile {} {} {} {}\n",
                        artifact_id,
                        delta,
                        uncompressed_size,
                        content.len()
                    ))
                } else {
                    Ok(format!(
                        "cfile {} {} {}\n",
                        artifact_id,
                        uncompressed_size,
                        content.len()
                    ))
                }
            }
            Card::Igot {
                artifact_id,
                is_private,
            } => {
                if *is_private {
                    Ok(format!("igot {} 1\n", artifact_id))
                } else {
                    Ok(format!("igot {}\n", artifact_id))
                }
            }
            Card::Gimme { artifact_id } => Ok(format!("gimme {}\n", artifact_id)),
            Card::Cookie { payload } => Ok(format!("cookie {}\n", payload)),
            Card::Error { message } => Ok(format!("error {}\n", encode_fossil_string(message))),
            Card::Message { text } => Ok(format!("message {}\n", encode_fossil_string(text))),
            Card::Pragma { name, values } => {
                if values.is_empty() {
                    Ok(format!("pragma {}\n", name))
                } else {
                    Ok(format!("pragma {} {}\n", name, values.join(" ")))
                }
            }
            Card::Comment { text } => Ok(format!("{}\n", text)),
            Card::Private => Ok("private\n".to_string()),
            Card::CloneSeqNo { sequence_number } => {
                Ok(format!("clone_seqno {}\n", sequence_number))
            }
            Card::ReqConfig { name } => Ok(format!("reqconfig {}\n", name)),
            Card::Config { name, content } => Ok(format!("config {} {}\n", name, content.len())),
        }
    }

    /// Get file content bytes for file/cfile cards.
    pub fn content_bytes(&self) -> Option<&[u8]> {
        match self {
            Card::File { content, .. } => Some(content),
            Card::CFile { content, .. } => Some(content),
            Card::Config { content, .. } => Some(content),
            _ => None,
        }
    }
}

/// Encode a string for Heroforge protocol (escape spaces and special chars).
pub fn encode_fossil_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace(' ', "\\s")
        .replace('\n', "\\n")
}

/// Decode a Heroforge-encoded string.
pub fn decode_fossil_string(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('s') => result.push(' '),
                Some('n') => result.push('\n'),
                Some('\\') => result.push('\\'),
                Some(other) => {
                    result.push('\\');
                    result.push(other);
                }
                None => result.push('\\'),
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Compress data using zlib.
pub fn compress(data: &[u8]) -> Result<Vec<u8>> {
    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(data)?;
    Ok(encoder.finish()?)
}

/// Get the zlib-compressed data, stripping any size prefix.
fn get_compressed_data(data: &[u8]) -> &[u8] {
    if data.len() >= 5 {
        // Check if this looks like a size prefix followed by zlib header
        // Zlib header starts with 0x78 (deflate with default/max compression)
        if data[4] == 0x78 {
            // Has size prefix, skip it
            return &data[4..];
        }
    }
    if !data.is_empty() && data[0] == 0x78 {
        // No prefix, starts with zlib header directly
        return data;
    }
    // Try as-is
    data
}

/// Decompress zlib data to bytes.
///
/// Heroforge's HTTP sync protocol uses a 4-byte big-endian size prefix
/// before the zlib-compressed data.
pub fn decompress_bytes(data: &[u8]) -> Result<Vec<u8>> {
    let compressed_data = get_compressed_data(data);
    let mut decoder = ZlibDecoder::new(compressed_data);
    let mut result = Vec::new();
    decoder.read_to_end(&mut result)?;
    Ok(result)
}

/// Decompress zlib data to string.
///
/// Heroforge's HTTP sync protocol uses a 4-byte big-endian size prefix
/// before the zlib-compressed data.
#[allow(dead_code)]
pub fn decompress(data: &[u8]) -> Result<String> {
    let compressed_data = get_compressed_data(data);
    let mut decoder = ZlibDecoder::new(compressed_data);
    let mut result = String::new();
    decoder.read_to_string(&mut result)?;
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_decode_string() {
        assert_eq!(encode_fossil_string("hello world"), "hello\\sworld");
        assert_eq!(encode_fossil_string("line1\nline2"), "line1\\nline2");
        assert_eq!(decode_fossil_string("hello\\sworld"), "hello world");
        assert_eq!(decode_fossil_string("line1\\nline2"), "line1\nline2");
    }

    #[test]
    fn test_message_parse() {
        let text = "push abc123 def456\nigot hash1\nigot hash2 1\ngimme hash3\n";
        let msg = Message::from_text(text).unwrap();
        assert_eq!(msg.cards.len(), 4);
    }

    #[test]
    fn test_compress_decompress() {
        let original = "Hello, Heroforge sync protocol!";
        let compressed = compress(original.as_bytes()).unwrap();
        let decompressed = decompress(&compressed).unwrap();
        assert_eq!(decompressed, original);
    }
}