Debian Codegraph @

utils/swi-update.c

raw
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * swi-update -- Command line tool to update QMI firmware
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * Copyright (C) Copyright 2016 Bjørn Mork <[email protected]>
19 *
20 * crc16 and hdlc parts:
21 * Copyright (C) 2010 Red Hat, Inc.
22 *
23 * parts of this is based on gobi-loader, which is
24 *
25 * "Copyright 2009 Red Hat <[email protected]> - heavily based on work done by
26 * Alexander Shumakovitch <[email protected]>
27 *
28 * Gobi 2000 support provided by Anssi Hannula <[email protected]>"
29 */
30
31 #include <endian.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <getopt.h>
35 #include <limits.h>
36 #include <linux/types.h>
37 #include <malloc.h>
38 #include <stdbool.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/stat.h>
43 #include <sys/select.h>
44 #include <termios.h>
45 #include <unistd.h>
46
47 /* FIXME: endianness - this works on LE for now... */
48
49 #ifndef VERSION
50 #define VERSION "unknown"
51 #endif
52 #define DESCRIPTION "swi-update (" VERSION ")"
53
54 #ifdef DEBUG
55 static bool debug;
56 #define debug(arg...) if (debug) fprintf(stderr, arg)
57 static void print_packet(const char *pfx, void *buf, int len)
58 {
59 int i;
60 unsigned char *p = buf;
61
62 if (!debug)
63 return;
64 fprintf(stderr, "%s: ", pfx);
65 for (i=0; i<len; i++)
66 fprintf(stderr, "%02x ", p[i]);
67 fprintf(stderr, "\n");
68 }
69 #else
70 #define debug(arg...)
71 #define print_packet(pfx, buf, len)
72 #endif /* DEBUG */
73
74
75 #define CHUNK (1024 * 1024)
76
77 /** DLOAD protocol **/
78
79 /*
80 * Most of this is from Josuah Hill's DLOAD tool for iPhone
81 * Some spec is also available in document 80-39912-1 Rev. E DMSS Download Protocol Interface Specification and Operational Description
82 * https://github.com/posixninja/DLOADTool/blob/master/dloadtool/dload.h
83 *
84 * The 0x70 switching command was found by snooping on firmware updates
85 */
86
87 enum dload_cmd {
88 DLOAD_ACK = 0x02, /* Acknowledge receiving a packet */
89 DLOAD_NOP = 0x06, /* No operation, useful for debugging */
90 DLOAD_SDP = 0x70, /* Switch to Streaming DLOAD */
91 };
92
93 /* 0x02 - __u8 cmd only */
94 /* 0x06 - __u8 cmd only */
95
96 struct dload_sdp {
97 __u8 cmd; /* 0x70 */
98 __u16 reserved; /* 0x0000 */
99 } __attribute__ ((packed));
100
101 static struct dload_sdp dload_sdp = {
102 .cmd = 0x70,
103 .reserved = 0,
104 };
105
106 /** Streaming DLOAD protocol **/
107
108 /* from GobiAPI_1.0.40/Core/QDLEnum.h and
109 * GobiAPI_1.0.40/Core/QDLBuffers.h with additional details from USB
110 * snooping
111 */
112 enum qdl_cmd {
113 QDL_CMD_HELLO_REQ = 0x01, /* Hello request */
114 QDL_CMD_HELLO_RSP, /* Hello response */
115 QDL_CMD_ERROR = 0x0d, /* Error report */
116 QDL_CMD_OPEN_UNFRAMED_REQ = 0x25, /* Open unframed image write request */
117 QDL_CMD_OPEN_UNFRAMED_RSP, /* Open unframed image write response */
118 QDL_CMD_WRITE_UNFRAMED_REQ, /* Unframed image write request */
119 QDL_CMD_WRITE_UNFRAMED_RSP, /* Unframed image write response */
120 QDL_CMD_SESSION_DONE_REQ, /* Unframed session done request */
121 QDL_CMD_SESSION_DONE_RSP, /* Unframed session done response */
122 QDL_CMD_DOWNLOAD_REQ, /* Switch to download protocol request */
123 QDL_CMD_SESSION_CLOSE_REQ = 0x2d, /* Close unframed session request */
124 QDL_CMD_GET_IMAGE_PREF_REQ, /* Get image preference request */
125 QDL_CMD_GET_IMAGE_PREF_RSP, /* Get image preference response */
126 };
127
128 enum qdl_error {
129 QDL_ERROR_01 = 1, // 01 Reserved
130 QDL_ERROR_BAD_ADDR, // 02 Invalid destination address
131 QDL_ERROR_BAD_LEN, // 03 Invalid length
132 QDL_ERROR_BAD_PACKET, // 04 Unexpected end of packet
133 QDL_ERROR_BAD_CMD, // 05 Invalid command
134 QDL_ERROR_06, // 06 Reserved
135 QDL_ERROR_OP_FAILED, // 07 Operation failed
136 QDL_ERROR_BAD_FLASH_ID, // 08 Invalid flash intelligent ID
137 QDL_ERROR_BAD_VOLTAGE, // 09 Invalid programming voltage
138 QDL_ERROR_WRITE_FAILED, // 10 Write verify failed
139 QDL_ERROR_11, // 11 Reserved
140 QDL_ERROR_BAD_SPC, // 12 Invalid security code
141 QDL_ERROR_POWERDOWN, // 13 Power-down failed
142 QDL_ERROR_UNSUPPORTED, // 14 NAND flash programming not supported
143 QDL_ERROR_CMD_SEQ, // 15 Command out of sequence
144 QDL_ERROR_CLOSE, // 16 Close failed
145 QDL_ERROR_BAD_FEATURES, // 17 Invalid feature bits
146 QDL_ERROR_SPACE, // 18 Out of space
147 QDL_ERROR_BAD_SECURITY, // 19 Invalid security mode
148 QDL_ERROR_MULTI_UNSUPPORTED, // 20 Multi-image NAND not supported
149 QDL_ERROR_POWEROFF, // 21 Power-off command not supported
150 QDL_ERROR_CMD_UNSUPPORTED, // 22 Command not supported
151 QDL_ERROR_BAD_CRC, // 23 Invalid CRC
152 QDL_ERROR_STATE, // 24 Command received in invalid state
153 QDL_ERROR_TIMEOUT, // 25 Receive timeout
154 QDL_ERROR_IMAGE_AUTH, // 26 Image authentication error
155 };
156
157 /* most of these origin from GobiAPI_1.0.40/Core/QDLEnum.h
158 *
159 * The gobi-loader's snooped magic strings use types
160 * 0x05 => "amss.mbn"
161 * 0x06 => "apps.mbn"
162 * 0x0d => "uqcn.mbn" (Gobi 2000 only)
163 * with no file header data
164 *
165 * The 0x80 type is snooped from the Sierra Wireless firmware
166 * uploaders, using 400 bytes file header data
167 */
168
169 enum qdl_type {
170 QDL_IMAGE_AMSS_MODEM = 0x05, // 05 AMSS modem image
171 QDL_IMAGE_AMSS_APPLICATION, // 06 AMSS application image
172 QDL_IMAGE_AMSS_UQCN = 0x0d, // 13 Provisioning information
173 QDL_IMAGE_DBL = 0x0f, // 15 DBL image
174 QDL_IMAGE_OSBL, // 16 OSBL image
175 QDL_IMAGE_CWE = 0x80, // 128 CWE image
176 };
177
178 static const char *qdl_type2str(__u8 type)
179 {
180 switch (type) {
181 case QDL_IMAGE_AMSS_MODEM:
182 return "AMSS_MODEM";
183 case QDL_IMAGE_AMSS_APPLICATION:
184 return "AMSS_APPLICATION";
185 case QDL_IMAGE_AMSS_UQCN:
186 return "AMSS_UQCN";
187 case QDL_IMAGE_DBL:
188 return "DBL";
189 case QDL_IMAGE_OSBL:
190 return "OSBL";
191 case QDL_IMAGE_CWE:
192 return "CWE";
193 default:
194 return "UNKNOWN";
195 }
196 }
197
198 /* feature bits */
199 #define QDL_FEATURE_GENERIC_UNFRAMED 0x10
200 #define QDL_FEATURE_QDL_UNFRAMED 0x20
201 #define QDL_FEATURE_BAR_MODE 0x40
202
203 struct qdl_hello_req {
204 __u8 cmd; /* 0x01 */
205 char magic[32];
206 __u8 maxver;
207 __u8 minver;
208 __u8 features;
209 } __attribute__ ((packed));
210
211 static struct qdl_hello_req qdl_hello_req = {
212 .cmd = QDL_CMD_HELLO_REQ,
213 .magic = { 'Q', 'C', 'O', 'M', ' ', 'h', 'i', 'g', 'h', ' ', 's', 'p', 'e', 'e', 'd', ' ', 'p', 'r', 'o', 't', 'o', 'c', 'o', 'l', ' ', 'h', 's', 't', },
214 .maxver = 0,
215 .minver = 0,
216 .features = QDL_FEATURE_QDL_UNFRAMED | QDL_FEATURE_GENERIC_UNFRAMED,
217 };
218
219 struct qdl_hello_rsp {
220 __u8 cmd; /* 0x02 */
221 char magic[32];
222 __u8 maxver;
223 __u8 minver;
224 __u32 reserved1;
225 __u32 reserved2;
226 __u8 reserved3;
227 __u16 reserved4;
228 __u16 reserved5;
229 __u8 features;
230 } __attribute__ ((packed));
231
232 struct qdl_err_rsp {
233 __u8 cmd; /* 0x0d */
234 __u32 error;
235 __u8 errortxt;
236 } __attribute__ ((packed));
237
238 struct qdl_ufopen_req {
239 __u8 cmd; /* 0x25 */
240 __u8 type;
241 __u32 length;
242 __u8 windowsize;
243 __u32 chunksize;
244 __u16 reserved;
245 /* The first 400 bytes of the image is appended to the "open
246 * unframed" request on Sierra Wireless modems. This chunk is
247 * not included here as it is not a part of the request.
248 *
249 * The file header inclusion here seems to depend on the file
250 * type
251 */
252 } __attribute__ ((packed));
253
254 struct qdl_ufopen_rsp {
255 __u8 cmd; /* 0x26 */
256 __u16 status;
257 __u8 windowsize;
258 __u32 chunksize;
259 } __attribute__ ((packed));
260
261 /* This request is not HDLC framed, so this "header" includes the crc */
262 struct qdl_ufwrite_req {
263 __u8 cmd; /* 0x27 */
264 __u16 sequence;
265 __u32 reserved;
266 __u32 chunksize;
267 __u16 crc;
268 } __attribute__ ((packed));
269
270 /* the buffer most hold a file chunk + this header */
271 #define BUFSIZE (CHUNK + sizeof(struct qdl_ufwrite_req))
272
273 /* The response is HDLC framed, so the crc is part of the framing */
274 struct qdl_ufwrite_rsp {
275 __u8 cmd; /* 0x28 */
276 __u16 sequence;
277 __u32 reserved;
278 __u16 status;
279 } __attribute__ ((packed));
280
281 /* __u8 0x29 - cmd only */
282
283 struct qdl_ufclose_rsp {
284 __u8 cmd; /* 0x2a */
285 __u16 status;
286 __u8 type;
287 __u8 errortxt;
288 } __attribute__ ((packed));
289
290 /* __u8 0x2d - cmd only */
291 /* __u8 0x2e - cmd only */
292
293 struct qdl_imagepref_rsp {
294 __u8 cmd; /* 0x2f */
295 __u8 entries;
296 struct {
297 __u8 type;
298 char id[16];
299 } image[];
300 } __attribute__ ((packed));
301
302 /*
303 * crc16 and HDLC escape code borrowed from modemmanager/libqcdm
304 * Copyright (C) 2010 Red Hat, Inc.
305 */
306
307 /* Table of CRCs for each possible byte, with a generator polynomial of 0x8408 */
308 static const __u16 crc_table[256] = {
309 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
310 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
311 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
312 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
313 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
314 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
315 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
316 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
317 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
318 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
319 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
320 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
321 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
322 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
323 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
324 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
325 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
326 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
327 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
328 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
329 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
330 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
331 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
332 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
333 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
334 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
335 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
336 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
337 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
338 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
339 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
340 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
341 };
342
343 /* Calculate the CRC for a buffer using a seed of 0xffff */
344 static __u16 crc16(const char *buffer, size_t len)
345 {
346 __u16 crc = 0xffff;
347
348 while (len--)
349 crc = crc_table[(crc ^ *buffer++) & 0xff] ^ (crc >> 8);
350 return ~crc;
351 }
352
353 #define CONTROL 0x7e
354 #define ESCAPE 0x7d
355 #define MASK 0x20
356
357 static size_t escape(const char *in, size_t inlen, char *out, size_t outlen)
358 {
359 size_t i, j;
360
361 for (i = 0, j = 0; i < inlen; i++) {
362 if (in[i] == CONTROL || in[i] == ESCAPE) {
363 out[j++] = ESCAPE;
364 if (j < outlen)
365 out[j++] = in[i] ^ MASK;
366 } else {
367 out[j++] = in[i];
368 }
369 if (j >= outlen)
370 return 0; /* failed to enscape - buffer too small */
371 }
372 return j;
373 }
374
375 static size_t unescape(const char *in, size_t inlen, char *out, size_t outlen)
376 {
377 size_t i, j = 0;
378 bool escaping = false;
379
380 for (i = 0; i < inlen; i++) {
381 if (j >= outlen) {
382 debug("i=%zu, j=%zu, inlen=%zu, outlen=%zu\n", i, j, inlen, outlen);
383 return 0;
384 }
385 if (escaping) {
386 out[j++] = in[i] ^ MASK;
387 escaping = false;
388 } else if (in[i] == ESCAPE) {
389 escaping = true;
390 } else {
391 out[j++] = in[i];
392 }
393 }
394 return j;
395 }
396
397 /* copy a possibly escaped single byte to out */
398 static size_t escape_byte(__u8 byte, char *out, size_t outlen)
399 {
400 size_t j = 0;
401
402 if (byte == CONTROL || byte == ESCAPE) {
403 out[j++] = ESCAPE;
404 byte ^= MASK;
405 }
406 out[j++] = byte;
407 return j;
408 }
409
410 static size_t hdlc_frame(const char *in, size_t inlen, char *out, size_t outlen)
411 {
412 __u16 crc;
413 size_t j = 0;
414
415 out[j++] = CONTROL;
416 j += escape(in, inlen, &out[j], outlen - j);
417 crc = crc16(in, inlen);
418 j += escape_byte(crc & 0xff, &out[j], outlen - j);
419 j += escape_byte(crc >> 8 & 0xff, &out[j], outlen - j);
420 out[j++] = CONTROL;
421
422 if (j < inlen)
423 return 0; /* FIXME */
424
425 return j;
426 }
427
428 static size_t hdlc_unframe(const char *in, size_t inlen, char *out, size_t outlen)
429 {
430 __u16 crc;
431 size_t j, i = inlen;
432
433 /* the first control char is optional */
434 if (*in == CONTROL) {
435 in++;
436 i--;
437 }
438 if (in[i - 1] == CONTROL)
439 i--;
440
441 j = unescape(in, i, out, outlen);
442 if (j < 2) {
443 debug("unescape failed: j = %zu\n", j);
444 return 0;
445 }
446 j -= 2; /* remove the crc */
447
448 /* verify the crc */
449 crc = crc16(out, j);
450 if (crc != ((unsigned char)out[j] | (unsigned char)out[j + 1] << 8)) {
451 debug("crc failed: 0x%04x != 0x%04x\n", crc, out[j] | out[j + 1] << 8);
452 return 0;
453 }
454 return j;
455 }
456
457 /* should the unframed open request include a file header? */
458 static inline size_t hdrlen(__u8 type)
459 {
460 switch (type) {
461 case QDL_IMAGE_CWE:
462 return 400;
463 default:
464 return 0;
465 }
466 }
467
468 /* some image types contain trailing garbage - from gobi-loader */
469 static inline size_t imglen(__u8 type, size_t len)
470 {
471 switch (type) {
472 case QDL_IMAGE_AMSS_MODEM:
473 return len - 8;
474 default:
475 return len;
476 }
477 }
478
479 static size_t create_ufopen_req(char *in, size_t filelen, __u8 type)
480 {
481 struct qdl_ufopen_req *req = (void *)in;
482
483 req->cmd = QDL_CMD_OPEN_UNFRAMED_REQ;
484 req->type = type;
485 req ->windowsize = 1; /* snooped */
486 req->length = imglen(type, filelen);
487 req->chunksize = imglen(type, filelen) - hdrlen(type);
488 return sizeof(struct qdl_ufopen_req);
489 }
490
491 static size_t create_ufwrite_req(char *out, size_t chunksize, int sequence)
492 {
493 struct qdl_ufwrite_req *req = (void *)out;
494
495 req->cmd = QDL_CMD_WRITE_UNFRAMED_REQ;
496 req->sequence = sequence;
497 req->reserved = 0;
498 req->chunksize = chunksize;
499 req->crc = crc16(out, sizeof(*req) - 2);
500 return sizeof(*req);
501 }
502
503 static int parse_sdp_hello(const char *in, size_t inlen)
504 {
505 struct qdl_hello_rsp *r;
506 char buf[sizeof(*r) + sizeof(__u16)];
507 char magicbuf[33] = {0};
508 size_t ret;
509
510 r = (struct qdl_hello_rsp *)buf;
511 ret = hdlc_unframe(in, inlen, buf, sizeof(buf));
512 if (ret == sizeof(*r) && r->cmd == QDL_CMD_HELLO_RSP) {
513 memcpy(magicbuf, r->magic, r->maxver <= 5 ? 24 : 32);
514 debug("magic: '%s'\nmaxver: %u\nminver: %u\nfeatures: 0x%02x\n", magicbuf, r->maxver, r->minver, r->features);
515 return 0;
516 }
517 return -1; /* unexpected error */
518 }
519
520 static const char *sdperr2str(__u32 err)
521 {
522 switch (err) {
523 case QDL_ERROR_01:
524 return "Reserved";
525 case QDL_ERROR_BAD_ADDR:
526 return "Invalid destination address";
527 case QDL_ERROR_BAD_LEN:
528 return "Invalid length";
529 case QDL_ERROR_BAD_PACKET:
530 return "Unexpected end of packet";
531 case QDL_ERROR_BAD_CMD:
532 return "Invalid command";
533 case QDL_ERROR_06:
534 return "Reserved";
535 case QDL_ERROR_OP_FAILED:
536 return "Operation failed";
537 case QDL_ERROR_BAD_FLASH_ID:
538 return "Invalid flash intelligent ID";
539 case QDL_ERROR_BAD_VOLTAGE:
540 return "Invalid programming voltage";
541 case QDL_ERROR_WRITE_FAILED:
542 return "Write verify failed";
543 case QDL_ERROR_11:
544 return "Reserved";
545 case QDL_ERROR_BAD_SPC:
546 return "Invalid security code";
547 case QDL_ERROR_POWERDOWN:
548 return "Power-down failed";
549 case QDL_ERROR_UNSUPPORTED:
550 return "NAND flash programming not supported";
551 case QDL_ERROR_CMD_SEQ:
552 return "Command out of sequence";
553 case QDL_ERROR_CLOSE:
554 return "Close failed";
555 case QDL_ERROR_BAD_FEATURES:
556 return "Invalid feature bits";
557 case QDL_ERROR_SPACE:
558 return "Out of space";
559 case QDL_ERROR_BAD_SECURITY:
560 return "Invalid security mode";
561 case QDL_ERROR_MULTI_UNSUPPORTED:
562 return "Multi-image NAND not supported";
563 case QDL_ERROR_POWEROFF:
564 return "Power-off command not supported";
565 case QDL_ERROR_CMD_UNSUPPORTED:
566 return "Command not supported";
567 case QDL_ERROR_BAD_CRC:
568 return "Invalid CRC";
569 case QDL_ERROR_STATE:
570 return "Command received in invalid state";
571 case QDL_ERROR_TIMEOUT:
572 return "Receive timeout";
573 case QDL_ERROR_IMAGE_AUTH:
574 return "Image authentication error";
575 default:
576 return "Unknown error";
577 }
578 }
579
580 static int parse_sdp_err(const char *in, size_t inlen, bool silent)
581 {
582 struct qdl_err_rsp *r;
583 char buf[sizeof(*r) + sizeof(__u16)];
584 size_t ret;
585
586 r = (struct qdl_err_rsp *)buf;
587 ret = hdlc_unframe(in, inlen, buf, sizeof(buf));
588 if (ret == sizeof(*r) && r->cmd == QDL_CMD_ERROR) {
589 if (!silent)
590 fprintf(stderr, "SDP error %d (%d): %s\n", r->error, r->errortxt, sdperr2str(r->error));
591 return -r->error;
592 }
593 return -1; /* not an proper error frame */
594 }
595
596 static int parse_ufopen(const char *in, size_t inlen)
597 {
598 struct qdl_ufopen_rsp *r;
599 char buf[sizeof(*r) + sizeof(__u16)];
600 size_t ret;
601
602 r = (struct qdl_ufopen_rsp *)buf;
603 ret = hdlc_unframe(in, inlen, buf, sizeof(buf));
604 if (ret != sizeof(*r) || r->cmd != QDL_CMD_OPEN_UNFRAMED_RSP)
605 return -1;
606 debug("status=%d, windowsize=%d, chunksize=%d\n", r->status, r->windowsize, r->chunksize);
607 return -r->status;
608 }
609
610 static int parse_ufwrite(const char *in, size_t inlen)
611 {
612 struct qdl_ufwrite_rsp *r;
613 char buf[sizeof(*r) + sizeof(__u16)];
614 size_t ret;
615
616 r = (struct qdl_ufwrite_rsp *)buf;
617 ret = hdlc_unframe(in, inlen, buf, sizeof(buf));
618 if (ret != sizeof(*r) || r->cmd != QDL_CMD_WRITE_UNFRAMED_RSP)
619 return -1;
620 if (r->status) {
621 fprintf(stderr, "seq 0x%04x status=%d\n", r->sequence, r->status);
622 return -r->status;
623 }
624 debug("ack: %d\n", r->sequence);
625 return r->sequence;
626 }
627
628 static int parse_ufdone(const char *in, size_t inlen)
629 {
630 struct qdl_ufclose_rsp *r;
631 char buf[sizeof(*r) + sizeof(__u16)];
632 size_t ret;
633
634 r = (struct qdl_ufclose_rsp *)buf;
635 ret = hdlc_unframe(in, inlen, buf, sizeof(buf));
636 if (ret != sizeof(*r) || r->cmd != QDL_CMD_SESSION_DONE_RSP)
637 return -1;
638 debug("UF close: status=%d, type=%d, errortxt=%d\n", r->status, r->type, r->errortxt);
639 return -r->status;
640 }
641
642 /* read and parse QDL if available. Will return unless data is
643 * available withing 5 ms
644 */
645 static int read_and_parse(int fd, bool silent)
646 {
647 char *end, *p, rbuf[512];
648 int rlen, framelen, ret = 0;
649 fd_set rd;
650 struct timeval tv = { .tv_sec = 1, .tv_usec = 0, };
651
652 FD_ZERO(&rd);
653 FD_SET(fd, &rd);
654 if (select(fd + 1, &rd, NULL, NULL, &tv) <= 0) {
655 debug("timeout: no data read\n");
656 return 0;
657 }
658
659 rlen = read(fd, rbuf, sizeof(rbuf));
660 if (rlen <= 0)
661 return rlen;
662 print_packet("read", rbuf, rlen);
663
664 p = rbuf;
665 while (rlen > 0 && (end = memchr(p + 1, CONTROL, rlen - 1)) != NULL) {
666 end++;
667 framelen = end - p;
668 switch (p[1]) {
669 case QDL_CMD_ERROR:
670 ret = parse_sdp_err(p, framelen, silent);
671 break;
672 case QDL_CMD_HELLO_RSP: /* == DLOAD_ACK */
673 if (framelen != 5)
674 ret = parse_sdp_hello(p, framelen);
675 else
676 debug("Got DLOAD_ACK\n");
677 break;
678 case QDL_CMD_OPEN_UNFRAMED_RSP:
679 ret = parse_ufopen(p, framelen);
680 break;
681 case QDL_CMD_WRITE_UNFRAMED_RSP:
682 ret = parse_ufwrite(p, framelen);
683 break;
684 case QDL_CMD_SESSION_DONE_RSP:
685 ret = parse_ufdone(p, framelen);
686 break;
687 default:
688 fprintf(stderr, "Unsupported response code: 0x%02x\n", p[1]);
689 }
690 if (ret < 0)
691 return ret;
692 p = end;
693 rlen -= framelen;
694 }
695 return ret;
696 }
697
698 static int write_hdlc(int fd, const char *in, size_t inlen)
699 {
700 char wbuf[512];
701 int wlen;
702
703 wlen = hdlc_frame(in, inlen, wbuf, sizeof(wbuf));
704 if (wlen > 0) {
705 if (write(fd, wbuf, wlen) < 0)
706 fprintf(stderr, "error writing HDLC");
707 else
708 print_packet("write", wbuf, wlen);
709 } else {
710 debug("hdlc_frame() returned %d\n", wlen);
711 }
712 return wlen;
713 }
714
715 static int serial_open(const char *dev)
716 {
717 struct termios terminal_data;
718 int fd;
719
720 /* FIXME: verify that the serial device is a Sierra Wireless device in QDL mode */
721 fd = open(dev, O_RDWR | O_NOCTTY);
722 if (fd > 0) {
723 tcgetattr(fd, &terminal_data);
724 cfmakeraw(&terminal_data);
725 tcsetattr(fd, TCSANOW, &terminal_data);
726 }
727 debug("opened %s\n", dev);
728 return fd;
729 }
730
731 /* Sierra Wireless CWE file header
732 * Note: 32bit numbers are big endian
733 */
734 struct cwehdr {
735 char reserved1[256];
736 __u32 crc; /* 32bit CRC of "reserved1" field */
737 __u32 rev; /* header revision */
738 __u32 val; /* CRC validity indicator */
739 char type[4]; /* ASCII - not null terminated */
740 char product[4]; /* ASCII - not null terminated */
741 __u32 imgsize; /* image size */
742 __u32 imgcrc; /* 32bit CRC of the image */
743 char version[84]; /* ASCII - null terminated */
744 char date[8]; /* ASCII - null terminated */
745 __u32 compat; /* backward compatibility */
746 char reserved2[20];
747 };
748
749 static int verify_cwehdr(char *buf)
750 {
751 struct cwehdr *h = (void *)buf;
752 char tmp[5];
753
754 fprintf(stderr, " CWE revision: %d\n", be32toh(h->rev));
755 memcpy(tmp, h->type, 4);
756 tmp[4] = 0;
757 fprintf(stderr, " type: %s\n", tmp);
758 memcpy(tmp, h->product, 4);
759 tmp[4] = 0;
760 fprintf(stderr, " product: %s\n", tmp);
761 fprintf(stderr, " image size: %d\n", be32toh(h->imgsize));
762 fprintf(stderr, " version: %s\n", h->version);
763 fprintf(stderr, " date: %s\n", h->date);
764 return 0;
765 }
766
767 /* guessing image type based on the well known Gobi 1k and 2k
768 * filenames, and assumes anything else is a CWE image
769 *
770 * This is based on the types in gobi-loader's snooped magic strings:
771 * 0x05 => "amss.mbn"
772 * 0x06 => "apps.mbn"
773 * 0x0d => "uqcn.mbn" (Gobi 2000 only)
774 */
775 static __u8 filename2type(const char *filename)
776 {
777 char *base = strrchr(filename, '/');
778
779 if (!base)
780 base = (char *)filename;
781 if (!strcasecmp(base, "amss.mbn"))
782 return QDL_IMAGE_AMSS_MODEM;
783 if (!strcasecmp(base, "apps.mbn"))
784 return QDL_IMAGE_AMSS_APPLICATION;
785 if (!strcasecmp(base, "uqcn.mbn"))
786 return QDL_IMAGE_AMSS_UQCN;
787 return QDL_IMAGE_CWE;
788 }
789
790 static int download_image(int serfd, char *buf, const char *image)
791 {
792 int imgfd = -1, ret = 0, seq = 0;
793 size_t chunksize, rlen, filelen;
794 struct stat img_data;
795 __u8 type = filename2type(image);
796
797 /* FIXME: verify that this image matches the modem */
798 imgfd = open(image, O_RDONLY);
799 if (imgfd < 0) {
800 fprintf(stderr, "Cannot open %s: %d\n", image, imgfd);
801 ret = imgfd;
802 goto out;
803 }
804 fstat(imgfd, &img_data);
805 if (imglen(type, img_data.st_size) < hdrlen(type)) {
806 fprintf(stderr, "%s is too short\n", image);
807 ret = -1;
808 goto out;
809 }
810
811 fprintf(stderr, "Downloading %s image '%s'\n", qdl_type2str(type), image);
812
813 /* send open request */
814 rlen = create_ufopen_req(buf, img_data.st_size, type);
815 if (hdrlen(type) > 0) {
816 ret = -1;
817 if (hdrlen(type) + rlen > BUFSIZE)
818 goto out;
819 if (read(imgfd, buf + rlen, hdrlen(type)) != hdrlen(type))
820 goto out;
821 if (type == QDL_IMAGE_CWE)
822 verify_cwehdr(buf + rlen);
823 }
824 write_hdlc(serfd, buf, rlen + hdrlen(type));
825
826 /* read ufopen response - FIXME: act on errors! */
827 if (read_and_parse(serfd, false) < 0)
828 goto out;
829
830 filelen = imglen(type, img_data.st_size) - hdrlen(type);
831 /* remaining data to send */
832 while (filelen > 0) {
833 fd_set wr;
834 struct timeval tv = { .tv_sec = 2, .tv_usec = 0, };
835
836 chunksize = CHUNK;
837 if (chunksize > filelen)
838 chunksize = filelen;
839
840 debug("write #%d (%zu)...", seq, chunksize);
841 rlen = create_ufwrite_req(buf, chunksize, seq++);
842 rlen += read(imgfd, buf + rlen, CHUNK);
843 filelen -= chunksize;
844
845 FD_ZERO(&wr);
846 FD_SET(serfd, &wr);
847 if (select(serfd + 1, NULL, &wr, NULL, &tv) <= 0)
848 goto out;
849 if (write(serfd, buf, rlen) < 0) {
850 fprintf(stderr, "error writing data");
851 goto out;
852 }
853 ret = read_and_parse(serfd, false);
854 if (ret < 0)
855 goto out;
856 }
857
858 debug("finished writing\n");
859
860 /* This may take a considerable amount of time */
861 fprintf(stderr, "\nWaiting for ack");
862 while (ret != seq - 1) {
863 fprintf(stderr, ".");
864 sleep(3);
865 ret = read_and_parse(serfd, false);
866 }
867 fprintf(stderr, "\n");
868
869 out:
870 if (imgfd >= 0)
871 close(imgfd);
872 return ret;
873 }
874
875 static struct option main_options[] = {
876 { "help", 0, 0, 'h' },
877 { "serial", 1, 0, 's' },
878 { "debug", 0, 0, 'd' },
879 { 0, 0, 0, 0 }
880 };
881
882 static void usage(const char *prog)
883 {
884 fprintf(stderr,
885 "\n%s: %s [ --help ]"
886 #ifdef DEBUG
887 " [--debug] "
888 #endif
889 "--serial <device> <image> [image2] [image3]\n",
890 __func__, prog);
891 }
892
893 int main(int argc, char *argv[])
894 {
895 int opt, serfd = -1, ret = 0, version;
896 char *buffer = NULL;
897
898 fprintf(stderr, "%s\n", DESCRIPTION);
899 while ((opt = getopt_long(argc, argv, "i:s:m:dvh", main_options, NULL)) != -1) {
900 switch(opt) {
901 case 's':
902 serfd = serial_open(optarg);
903 break;
904 #ifdef DEBUG
905 case 'd':
906 debug = true;
907 break;
908 #endif
909 case 'h':
910 usage(argv[0]);
911 return 0;
912 }
913 }
914
915 buffer = malloc(BUFSIZE);
916 if (!buffer) {
917 ret = -ENOMEM;
918 goto err;
919 }
920
921
922 /* FIXME: should do the following for a complete image upload*
923 *
924 * For CWE images:
925 * - verify image and retrive model/version data for next step if applicable
926 * - if application mode:
927 * + verify qmi model/version matching image
928 * + check usb sysfs (serial++) to match against bootloader mode
929 * + switch to bootloader mode
930 * + wait for QDL device to appear
931 *
932 * For all images:
933 * - verify that the QDL device is the correct one (check serial etc)
934 *
935 * NON WORKING:
936 * - allow multiple images to be uploaded in one run
937 * How do we do this properly?
938 */
939
940 /* need at least one firmware filename */
941 if (optind == argc) {
942 usage(argv[0]);
943 return -1;
944 }
945
946 if (serfd < 0)
947 return serfd;
948
949 /* switch to SDP - this is required for some modems like MC7710 */
950 write_hdlc(serfd, (const char *)&dload_sdp, sizeof(dload_sdp));
951 ret = read_and_parse(serfd, true);
952
953 /* the modem could already be in SDP mode, so ignore "unsupported" errors */
954 if (ret < 0 && ret != -QDL_ERROR_CMD_UNSUPPORTED)
955 goto err;
956
957 /* attempt to probe supported protocol version
958 * Newer modems like Sierra Wireless MC7710 must use '6' for both fields
959 * Gobi2000 modems like HP un2420 must use '5' for both fields
960 * Gobi1000 modems must use '4' for both fields
961 */
962 for (version = 4; version < 7; version++) {
963 qdl_hello_req.minver = version;
964 qdl_hello_req.maxver = version;
965 write_hdlc(serfd, (const char *)&qdl_hello_req, sizeof(qdl_hello_req));
966 ret = read_and_parse(serfd, true);
967 if (!ret)
968 break;
969 }
970 if (ret < 0) {
971 fprintf(stderr, "Unable to detect QDL version\n");
972 goto err;
973 }
974 fprintf(stderr, "Got QDL version: %u\n", version);
975
976 /* download all images */
977 while (optind < argc && ret >= 0)
978 ret = download_image(serfd, buffer, argv[optind++]);
979
980 /* close unframed session */
981 buffer[0] = QDL_CMD_SESSION_DONE_REQ;
982 write_hdlc(serfd, buffer, 1);
983
984 /* read close response */
985 if (!read_and_parse(serfd, false))
986 fprintf(stderr, "Success!\n");
987
988 /* terminate SDP session */
989 fprintf(stderr, "Terminating session - rebooting modem...\n");
990 buffer[0] = QDL_CMD_SESSION_CLOSE_REQ;
991 write_hdlc(serfd, buffer, 1);
992
993 /* no response? */
994 read_and_parse(serfd, false);
995
996 err:
997 if (serfd > 0)
998 close(serfd);
999 free(buffer);
1000 return ret;
1001 }