Introduce samsungtools to decrypt samsung firmware
[maemo-rb.git] / utils / samsungtools / fwdecrypt.c
blob67dfb315c2d8e26e1fc8a3b005cbf7c62945dfa5
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2012 Amaury Pouly
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "samsung.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <getopt.h>
27 static bool g_debug = false;
28 static char *g_out_prefix = NULL;
30 static void usage(void)
32 printf("Usage: fwdecrypt [options] firmware\n");
33 printf("Options:\n");
34 printf(" -o <prefix>\tSet output file\n");
35 printf(" -f/--force\tForce to continue on errors\n");
36 printf(" -?/--help\tDisplay this message\n");
37 printf(" -d/--debug\tDisplay debug messages\n");
38 exit(1);
41 static int s_read(void *user, int offset, void *buf, int size)
43 FILE *f = user;
44 if(fseek(f, offset, SEEK_SET) != 0)
45 return 0;
46 return fread(buf, 1, size, f);
49 static void s_printf(void *user, bool error, const char *fmt, ...)
51 if(!g_debug && !error)
52 return;
53 (void) user;
54 va_list args;
55 va_start(args, fmt);
56 vprintf(fmt, args);
57 va_end(args);
60 int main(int argc, char **argv)
62 if(argc <= 1)
63 usage();
65 while(1)
67 static struct option long_options[] =
69 {"help", no_argument, 0, '?'},
70 {"debug", no_argument, 0, 'd'},
71 {0, 0, 0, 0}
74 int c = getopt_long(argc, argv, "?do:", long_options, NULL);
75 if(c == -1)
76 break;
77 switch(c)
79 case -1:
80 break;
81 case 'd':
82 g_debug = true;
83 break;
84 case '?':
85 usage();
86 break;
87 case 'o':
88 g_out_prefix = optarg;
89 break;
90 default:
91 abort();
95 if(optind != argc - 1)
96 usage();
98 FILE *f = fopen(argv[optind], "rb");
99 if(f == NULL)
101 printf("Cannot open file for reading: %m\n");
102 return 1;
105 enum samsung_error_t err;
106 struct samsung_firmware_t *fw = samsung_read(s_read, s_printf,
107 f, &err);
108 if(fw == NULL || err != SAMSUNG_SUCCESS)
110 printf("Error reading firmware: %d\n", err);
111 samsung_free(fw);
112 return 1;
114 fclose(f);
116 if(g_out_prefix)
118 f = fopen(g_out_prefix, "wb");
119 if(f == NULL)
121 printf("Cannot open file for writing: %m\n");
122 return 2;
124 fwrite(fw->data, 1, fw->data_size, f);
125 fclose(f);
128 samsung_free(fw);
130 return 0;