payload_dumper 0.8.1

A fast and efficient Android OTA payload dumper library and CLI
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 rhythmcache
// https://github.com/rhythmcache/payload-dumper-rust

use std::ffi::{CStr, CString, c_char, c_void};
use std::panic;
use std::ptr;
use std::sync::Arc;

use crate::extractor::local::{
    ExtractionProgress, ExtractionStatus, ProgressCallback, extract_partition,
    extract_partition_zip, list_partitions, list_partitions_zip,
};

#[cfg(feature = "remote_zip")]
use crate::extractor::remote::{
    extract_partition_remote_bin, extract_partition_remote_zip, list_partitions_remote_bin,
    list_partitions_remote_zip,
};

/* Error Handling */

thread_local! {
    static LAST_ERROR: std::cell::RefCell<Option<CString>> = std::cell::RefCell::new(None);
}

fn set_last_error(err: String) {
    LAST_ERROR.with(|last| {
        *last.borrow_mut() = CString::new(err).ok();
    });
}

fn clear_last_error() {
    LAST_ERROR.with(|last| {
        *last.borrow_mut() = None;
    });
}

/// get the last error message
/// returns NULL if no error occurred
/// the returned string is valid until the next call from the same thread
///
/// point: errors are thread-local. Each thread maintains its own error state.
#[unsafe(no_mangle)]
pub extern "C" fn payload_get_last_error() -> *const c_char {
    LAST_ERROR.with(|last| {
        last.borrow()
            .as_ref()
            .map(|s| s.as_ptr())
            .unwrap_or(ptr::null())
    })
}

/// clear the last error
#[unsafe(no_mangle)]
pub extern "C" fn payload_clear_error() {
    clear_last_error();
}

/* String Handling */

/// free a string allocated by this library
#[unsafe(no_mangle)]
pub extern "C" fn payload_free_string(s: *mut c_char) {
    if !s.is_null() {
        unsafe {
            drop(CString::from_raw(s));
        }
    }
}

/* Partition List API (payload.bin) */

/// list all partitions in a payload.bin file
/// Returns a JSON string on success, NULL on failure
/// the caller must free the returned string with payload_free_string()
///
/// the returned JSON structure:
/// {
///   "partitions": [...],
///   "total_partitions": 10,
///   "total_operations": 1000,
///   "total_size_bytes": 5000000000,
///   "total_size_readable": "4.66 GB",
///   "security_patch_level": "2025-12-05" // optional, present only if available in payload
/// }
#[unsafe(no_mangle)]
pub extern "C" fn payload_list_partitions(payload_path: *const c_char) -> *mut c_char {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        if payload_path.is_null() {
            set_last_error("payload_path is NULL".to_string());
            return ptr::null_mut();
        }

        let path_str = unsafe {
            match CStr::from_ptr(payload_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in payload_path: {}", e));
                    return ptr::null_mut();
                }
            }
        };

        match list_partitions(path_str) {
            Ok(json) => match CString::new(json) {
                Ok(c_str) => c_str.into_raw(),
                Err(e) => {
                    set_last_error(format!("Failed to create C string: {}", e));
                    ptr::null_mut()
                }
            },
            Err(e) => {
                set_last_error(format!("Failed to list partitions: {}", e));
                ptr::null_mut()
            }
        }
    });

    match result {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("Panic occurred in payload_list_partitions".to_string());
            ptr::null_mut()
        }
    }
}

/* Partition List API ( Zip file ) */

/// list all partitions in a ZIP file containing payload.bin
/// returns a JSON string on success, NULL on failure
/// the caller must free the returned string with payload_free_string()
///
/// the returned JSON format is the same as payload_list_partitions()
#[unsafe(no_mangle)]
pub extern "C" fn payload_list_partitions_zip(zip_path: *const c_char) -> *mut c_char {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        if zip_path.is_null() {
            set_last_error("zip_path is NULL".to_string());
            return ptr::null_mut();
        }

        let path_str = unsafe {
            match CStr::from_ptr(zip_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in zip_path: {}", e));
                    return ptr::null_mut();
                }
            }
        };

        match list_partitions_zip(path_str) {
            Ok(json) => match CString::new(json) {
                Ok(c_str) => c_str.into_raw(),
                Err(e) => {
                    set_last_error(format!("Failed to create C string: {}", e));
                    ptr::null_mut()
                }
            },
            Err(e) => {
                set_last_error(format!("Failed to list partitions from ZIP: {}", e));
                ptr::null_mut()
            }
        }
    });

    match result {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("Panic occurred in payload_list_partitions_zip".to_string());
            ptr::null_mut()
        }
    }
}

/* Remote Partition List API (ZIP) */

/// list all partitions in a remote ZIP file containing payload.bin
/// returns a JSON string on success, NULL on failure
/// the caller must free the returned string with payload_free_string()
///
/// @param url URL to the remote ZIP file
/// @param user_agent Optional user agent string (pass NULL for default)
/// @param cookies Optional cookie string (pass NULL for default)
/// @param out_content_length Pointer to store the HTTP content length (pass NULL to ignore)
/// @return JSON string on success, NULL on failure
///
/// the returned JSON format is the same as payload_list_partitions()
/// if out_content_length is not NULL, it will be filled with the remote file size
/// Cookies must be provided as a raw HTTP "Cookie" header value
/// (for example "key1=value1; key2=value2")
#[cfg(feature = "remote_zip")]
#[unsafe(no_mangle)]
pub extern "C" fn payload_list_partitions_remote_zip(
    url: *const c_char,
    user_agent: *const c_char,
    cookies: *const c_char,
    out_content_length: *mut u64,
) -> *mut c_char {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        if url.is_null() {
            set_last_error("url is NULL".to_string());
            return ptr::null_mut();
        }

        let url_str = unsafe {
            match CStr::from_ptr(url).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in url: {}", e));
                    return ptr::null_mut();
                }
            }
        };

        let user_agent_str = if user_agent.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(user_agent).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in user_agent: {}", e));
                        return ptr::null_mut();
                    }
                }
            }
        };

        let cookies_str = if cookies.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(cookies).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in cookies: {}", e));
                        return ptr::null_mut();
                    }
                }
            }
        };

        match list_partitions_remote_zip(url_str.to_string(), user_agent_str, cookies_str) {
            Ok(result) => {
                // write content length if pointer provided
                if !out_content_length.is_null() {
                    unsafe {
                        *out_content_length = result.content_length;
                    }
                }

                match CString::new(result.json) {
                    Ok(c_str) => c_str.into_raw(),
                    Err(e) => {
                        set_last_error(format!("Failed to create C string: {}", e));
                        ptr::null_mut()
                    }
                }
            }
            Err(e) => {
                set_last_error(format!("Failed to list remote partitions: {}", e));
                ptr::null_mut()
            }
        }
    });

    match result {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("Panic occurred in payload_list_partitions_remote_zip".to_string());
            ptr::null_mut()
        }
    }
}

/* Remote Partition List API (.bin) */

/// list all partitions in a remote payload.bin file (not in ZIP)
/// returns a JSON string on success, NULL on failure
/// the caller must free the returned string with payload_free_string()
///
/// @param url URL to the remote payload.bin file
/// @param user_agent Optional user agent string (pass NULL for default)
/// @param cookies Optional cookie string (pass NULL for default)
/// @param out_content_length Pointer to store the HTTP content length (pass NULL to ignore)
/// @return JSON string on success, NULL on failure
///
/// the returned JSON format is the same as payload_list_partitions()
/// if out_content_length is not NULL, it will be filled with the remote file size
#[cfg(feature = "remote_zip")]
#[unsafe(no_mangle)]
pub extern "C" fn payload_list_partitions_remote_bin(
    url: *const c_char,
    user_agent: *const c_char,
    cookies: *const c_char,
    out_content_length: *mut u64,
) -> *mut c_char {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        if url.is_null() {
            set_last_error("url is NULL".to_string());
            return ptr::null_mut();
        }

        let url_str = unsafe {
            match CStr::from_ptr(url).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in url: {}", e));
                    return ptr::null_mut();
                }
            }
        };

        let user_agent_str = if user_agent.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(user_agent).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in user_agent: {}", e));
                        return ptr::null_mut();
                    }
                }
            }
        };

        let cookies_str = if cookies.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(cookies).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in cookies: {}", e));
                        return ptr::null_mut();
                    }
                }
            }
        };

        match list_partitions_remote_bin(url_str.to_string(), user_agent_str, cookies_str) {
            Ok(result) => {
                // write content length if pointer provided
                if !out_content_length.is_null() {
                    unsafe {
                        *out_content_length = result.content_length;
                    }
                }

                match CString::new(result.json) {
                    Ok(c_str) => c_str.into_raw(),
                    Err(e) => {
                        set_last_error(format!("Failed to create C string: {}", e));
                        ptr::null_mut()
                    }
                }
            }
            Err(e) => {
                set_last_error(format!("Failed to list remote partitions: {}", e));
                ptr::null_mut()
            }
        }
    });

    match result {
        Ok(ptr) => ptr,
        Err(_) => {
            set_last_error("Panic occurred in payload_list_partitions_remote_bin".to_string());
            ptr::null_mut()
        }
    }
}

/* Progress Callback */

/// progress callback function type
///
/// @param user_data User-provided data pointer
/// @param partition_name Name of the partition being extracted (temporary pointer)
/// @param current_operation Current operation number (0-based)
/// @param total_operations Total number of operations
/// @param percentage Completion percentage (0.0 to 100.0)
/// @param status Status code (see STATUS_* constants)
/// @param warning_message Warning message if status is STATUS_WARNING (temporary pointer)
/// @return non-zero to continue extraction, 0 to cancel
pub type CProgressCallback = extern "C" fn(
    user_data: *mut c_void,
    partition_name: *const c_char,
    current_operation: u64,
    total_operations: u64,
    percentage: f64,
    status: i32,
    warning_message: *const c_char,
) -> i32;

/// status codes for progress callback
pub const STATUS_STARTED: i32 = 0;
pub const STATUS_IN_PROGRESS: i32 = 1;
pub const STATUS_COMPLETED: i32 = 2;
pub const STATUS_WARNING: i32 = 3;

struct CCallbackWrapper {
    callback: CProgressCallback,
    user_data: *mut c_void,
}

// we require the user_data to be thread-safe
unsafe impl Send for CCallbackWrapper {}
unsafe impl Sync for CCallbackWrapper {}

impl CCallbackWrapper {
    fn call(&self, progress: ExtractionProgress) -> bool {
        // catch panics to prevent unwinding through C
        let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
            // allocate partition name as local CString
            let partition_name = match CString::new(progress.partition_name.clone()) {
                Ok(s) => s,
                Err(_) => return true, // continue on error
            };

            // handle status and warning message
            // keep warning_msg as a local CString so it's automatically freed
            let warning_msg;
            let (status, warning_msg_ptr) = match progress.status {
                ExtractionStatus::Started => (STATUS_STARTED, ptr::null()),
                ExtractionStatus::InProgress => (STATUS_IN_PROGRESS, ptr::null()),
                ExtractionStatus::Completed => (STATUS_COMPLETED, ptr::null()),
                ExtractionStatus::Warning { message, .. } => {
                    // create local CString -> no into_raw(), no manual cleanup needed
                    warning_msg = CString::new(message).ok();
                    let msg_ptr = warning_msg
                        .as_ref()
                        .map(|s| s.as_ptr())
                        .unwrap_or(ptr::null());
                    (STATUS_WARNING, msg_ptr)
                }
            };

            // call the C callback
            // all pointers are valid for the duration of this call
            // they will be automatically freed when locals are dropped
            let result = (self.callback)(
                self.user_data,
                partition_name.as_ptr(),
                progress.current_operation,
                progress.total_operations,
                progress.percentage,
                status,
                warning_msg_ptr,
            );

            result != 0
            // partition_name and warning_msg are automatically dropped here
        }));

        // if callback panicked, log error and continue
        match result {
            Ok(should_continue) => should_continue,
            Err(_) => {
                eprintln!("WARNING: Progress callback panicked - continuing extraction");
                true // Continue on panic
            }
        }
    }
}

/* Extract Partition API (payload.bin) */

/// extract a single partition from a payload.bin file
///
/// @param payload_path Path to the payload.bin file
/// @param partition_name Name of the partition to extract
/// @param output_path Path where the partition image will be written
/// @param callback Optional progress callback (pass NULL for no callback)
/// @param user_data User data passed to callback (can be NULL)
/// @return 0 on success, -1 on failure (check payload_get_last_error())
///
/// This function can be safely called from multiple threads concurrently.
/// Each thread can extract a different partition in parallel.
///
/// - pass NULL for callback parameter if you don't want progress updates
/// - the partition_name and warning_message pointers passed to the callback
///   are ONLY valid during the callback execution. Do NOT store these pointers.
/// - If you need to keep the strings, copy them immediately in the callback.
/// - do NOT call free() on these strings, they are managed by the library.
///
/// - Return 0 from the callback to cancel extraction
/// - Return non-zero to continue
/// - cancellation may not be immediate
#[unsafe(no_mangle)]
pub extern "C" fn payload_extract_partition(
    payload_path: *const c_char,
    partition_name: *const c_char,
    output_path: *const c_char,
    callback: CProgressCallback, // function pointer (use NULL-equivalent cast from C side)
    user_data: *mut c_void,
) -> i32 {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        // validate inputs
        if payload_path.is_null() {
            set_last_error("payload_path is NULL".to_string());
            return -1;
        }
        if partition_name.is_null() {
            set_last_error("partition_name is NULL".to_string());
            return -1;
        }
        if output_path.is_null() {
            set_last_error("output_path is NULL".to_string());
            return -1;
        }

        // convert C strings
        let payload_str = unsafe {
            match CStr::from_ptr(payload_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in payload_path: {}", e));
                    return -1;
                }
            }
        };

        let partition_str = unsafe {
            match CStr::from_ptr(partition_name).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in partition_name: {}", e));
                    return -1;
                }
            }
        };

        let output_str = unsafe {
            match CStr::from_ptr(output_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in output_path: {}", e));
                    return -1;
                }
            }
        };

        // check if callback is null by comparing function pointer to null cast
        let progress_cb: Option<ProgressCallback> = if callback as usize == 0 {
            None
        } else {
            let wrapper = Arc::new(CCallbackWrapper {
                callback,
                user_data,
            });

            Some(Box::new(move |progress| wrapper.call(progress)) as ProgressCallback)
        };

        match extract_partition(payload_str, partition_str, output_str, progress_cb) {
            Ok(()) => 0,
            Err(e) => {
                set_last_error(format!("Extraction failed: {}", e));
                -1
            }
        }
    });

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in payload_extract_partition".to_string());
            -1
        }
    }
}

/* Extract Partition API (ZIP file) */

/// extract a single partition from a ZIP file containing payload.bin
///
/// @param zip_path Path to the ZIP file containing payload.bin
/// @param partition_name Name of the partition to extract
/// @param output_path Path where the partition image will be written
/// @param callback Optional progress callback (pass NULL for no callback)
/// @param user_data User data passed to callback (can be NULL)
/// @return 0 on success, -1 on failure (check payload_get_last_error())
///
/// this function can be safely called from multiple threads concurrently.
/// each thread can extract a different partition in parallel.
///
/// - pass NULL for callback parameter if you don't want progress updates
/// - the partition_name and warning_message pointers passed to the callback
///   are ONLY valid during the callback execution. Do NOT store these pointers.
/// - if you need to keep the strings, copy them immediately in the callback.
/// - Do NOT call free() on these strings, they are managed by the library.
///
/// - Return 0 from the callback to cancel extraction
/// - Return non-zero to continue
/// - Cancellation may not be immediate
#[unsafe(no_mangle)]
pub extern "C" fn payload_extract_partition_zip(
    zip_path: *const c_char,
    partition_name: *const c_char,
    output_path: *const c_char,
    callback: CProgressCallback, // function pointer (use NULL-equivalent cast from C side)
    user_data: *mut c_void,
) -> i32 {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        // validate inputs
        if zip_path.is_null() {
            set_last_error("zip_path is NULL".to_string());
            return -1;
        }
        if partition_name.is_null() {
            set_last_error("partition_name is NULL".to_string());
            return -1;
        }
        if output_path.is_null() {
            set_last_error("output_path is NULL".to_string());
            return -1;
        }

        let zip_str = unsafe {
            match CStr::from_ptr(zip_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in zip_path: {}", e));
                    return -1;
                }
            }
        };

        let partition_str = unsafe {
            match CStr::from_ptr(partition_name).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in partition_name: {}", e));
                    return -1;
                }
            }
        };

        let output_str = unsafe {
            match CStr::from_ptr(output_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in output_path: {}", e));
                    return -1;
                }
            }
        };

        // check if callback is null by comparing function pointer to null cast
        let progress_cb: Option<ProgressCallback> = if callback as usize == 0 {
            None
        } else {
            let wrapper = Arc::new(CCallbackWrapper {
                callback,
                user_data,
            });

            Some(Box::new(move |progress| wrapper.call(progress)) as ProgressCallback)
        };

        match extract_partition_zip(zip_str, partition_str, output_str, progress_cb) {
            Ok(()) => 0,
            Err(e) => {
                set_last_error(format!("Extraction from ZIP failed: {}", e));
                -1
            }
        }
    });

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in payload_extract_partition_zip".to_string());
            -1
        }
    }
}

/* Extract Partition API (Remote ZIP) */

/// extract a single partition from a remote ZIP file containing payload.bin
///
/// @param url URL to the remote ZIP file
/// @param partition_name Name of the partition to extract
/// @param output_path Path where the partition image will be written
/// @param user_agent Optional user agent string (pass NULL for default)
/// @param cookies Optional cookie string (pass NULL for default)
/// @param callback Optional progress callback (pass NULL for no callback)
/// @param user_data User data passed to callback (can be NULL)
/// @return 0 on success, -1 on failure (check payload_get_last_error())
///
/// this function can be safely called from multiple threads concurrently.
/// each thread can extract a different partition in parallel.
///
/// - pass NULL for callback parameter if you don't want progress updates
/// - the partition_name and warning_message pointers passed to the callback
///   are ONLY valid during the callback execution. Do NOT store these pointers.
/// - if you need to keep the strings, copy them immediately in the callback.
/// - Do NOT call free() on these strings, they are managed by the library.
///
/// - Return 0 from the callback to cancel extraction
/// - Return non-zero to continue
/// - Cancellation may not be immediate
#[cfg(feature = "remote_zip")]
#[unsafe(no_mangle)]
pub extern "C" fn payload_extract_partition_remote_zip(
    url: *const c_char,
    partition_name: *const c_char,
    output_path: *const c_char,
    user_agent: *const c_char,
    cookies: *const c_char,
    callback: CProgressCallback,
    user_data: *mut c_void,
) -> i32 {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        // validate inputs
        if url.is_null() {
            set_last_error("url is NULL".to_string());
            return -1;
        }
        if partition_name.is_null() {
            set_last_error("partition_name is NULL".to_string());
            return -1;
        }
        if output_path.is_null() {
            set_last_error("output_path is NULL".to_string());
            return -1;
        }

        let url_str = unsafe {
            match CStr::from_ptr(url).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in url: {}", e));
                    return -1;
                }
            }
        };

        let partition_str = unsafe {
            match CStr::from_ptr(partition_name).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in partition_name: {}", e));
                    return -1;
                }
            }
        };

        let output_str = unsafe {
            match CStr::from_ptr(output_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in output_path: {}", e));
                    return -1;
                }
            }
        };

        let user_agent_str = if user_agent.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(user_agent).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in user_agent: {}", e));
                        return -1;
                    }
                }
            }
        };

        let cookies_str = if cookies.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(cookies).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in cookies: {}", e));
                        return -1;
                    }
                }
            }
        };

        // check if callback is null by comparing function pointer to null cast
        let progress_cb: Option<ProgressCallback> = if callback as usize == 0 {
            None
        } else {
            let wrapper = Arc::new(CCallbackWrapper {
                callback,
                user_data,
            });

            Some(Box::new(move |progress| wrapper.call(progress)) as ProgressCallback)
        };

        match extract_partition_remote_zip(
            url_str.to_string(),
            partition_str,
            output_str,
            user_agent_str,
            cookies_str,
            progress_cb,
        ) {
            Ok(()) => 0,
            Err(e) => {
                set_last_error(format!("Remote extraction from ZIP failed: {}", e));
                -1
            }
        }
    });

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in payload_extract_partition_remote_zip".to_string());
            -1
        }
    }
}

/* Extract Partition API (Remote .bin) */

/// extract a single partition from a remote payload.bin file (not in ZIP)
///
/// @param url URL to the remote payload.bin file
/// @param partition_name Name of the partition to extract
/// @param output_path Path where the partition image will be written
/// @param user_agent Optional user agent string (pass NULL for default)
/// @param cookies Optional cookie string (pass NULL for default)
/// @param callback Optional progress callback (pass NULL for no callback)
/// @param user_data User data passed to callback (can be NULL)
/// @return 0 on success, -1 on failure (check payload_get_last_error())
///
/// this function can be safely called from multiple threads concurrently.
/// each thread can extract a different partition in parallel.
///
/// - pass NULL for callback parameter if you don't want progress updates
/// - the partition_name and warning_message pointers passed to the callback
///   are ONLY valid during the callback execution. Do NOT store these pointers.
/// - if you need to keep the strings, copy them immediately in the callback.
/// - Do NOT call free() on these strings, they are managed by the library.
///
/// - Return 0 from the callback to cancel extraction
/// - Return non-zero to continue
/// - Cancellation may not be immediate
#[cfg(feature = "remote_zip")]
#[unsafe(no_mangle)]
pub extern "C" fn payload_extract_partition_remote_bin(
    url: *const c_char,
    partition_name: *const c_char,
    output_path: *const c_char,
    user_agent: *const c_char,
    cookies: *const c_char,
    callback: CProgressCallback,
    user_data: *mut c_void,
) -> i32 {
    clear_last_error();

    let result = panic::catch_unwind(|| {
        // validate inputs
        if url.is_null() {
            set_last_error("url is NULL".to_string());
            return -1;
        }
        if partition_name.is_null() {
            set_last_error("partition_name is NULL".to_string());
            return -1;
        }
        if output_path.is_null() {
            set_last_error("output_path is NULL".to_string());
            return -1;
        }

        let url_str = unsafe {
            match CStr::from_ptr(url).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in url: {}", e));
                    return -1;
                }
            }
        };

        let partition_str = unsafe {
            match CStr::from_ptr(partition_name).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in partition_name: {}", e));
                    return -1;
                }
            }
        };

        let output_str = unsafe {
            match CStr::from_ptr(output_path).to_str() {
                Ok(s) => s,
                Err(e) => {
                    set_last_error(format!("Invalid UTF-8 in output_path: {}", e));
                    return -1;
                }
            }
        };

        let user_agent_str = if user_agent.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(user_agent).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in user_agent: {}", e));
                        return -1;
                    }
                }
            }
        };

        let cookies_str = if cookies.is_null() {
            None
        } else {
            unsafe {
                match CStr::from_ptr(cookies).to_str() {
                    Ok(s) => Some(s),
                    Err(e) => {
                        set_last_error(format!("Invalid UTF-8 in cookies: {}", e));
                        return -1;
                    }
                }
            }
        };

        // check if callback is null by comparing function pointer to null cast
        let progress_cb: Option<ProgressCallback> = if callback as usize == 0 {
            None
        } else {
            let wrapper = Arc::new(CCallbackWrapper {
                callback,
                user_data,
            });

            Some(Box::new(move |progress| wrapper.call(progress)) as ProgressCallback)
        };

        match extract_partition_remote_bin(
            url_str.to_string(),
            partition_str,
            output_str,
            user_agent_str,
            cookies_str,
            progress_cb,
        ) {
            Ok(()) => 0,
            Err(e) => {
                set_last_error(format!("Remote extraction from .bin failed: {}", e));
                -1
            }
        }
    });

    match result {
        Ok(code) => code,
        Err(_) => {
            set_last_error("Panic occurred in payload_extract_partition_remote_bin".to_string());
            -1
        }
    }
}

/* Utility Functions */

/// get library version
/// returns a static string, do not free
#[unsafe(no_mangle)]
pub extern "C" fn payload_get_version() -> *const c_char {
    static C_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes();
    C_VERSION.as_ptr() as *const c_char
}

/// initialize the library (optional, but recommended for thread safety)
/// should be called once before any other library functions
/// @return 0 on success, -1 on failure
#[unsafe(no_mangle)]
pub extern "C" fn payload_init() -> i32 {
    // not yet implemented idk
    0
}

/// cleanup library resources
/// should be called once when done using the library
/// no library functions should be called after this
#[unsafe(no_mangle)]
pub extern "C" fn payload_cleanup() {
    // not yet implemented idk
}