summaryrefslogtreecommitdiff
path: root/cleopatre/tools/spidupd/spidupd_host.c
blob: 5b71eed12f3820981cd866d8458ed268674f43a9 (plain)
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
/*
 * tools/spidupd/spidupd_host.c
 *
 * (C) Copyright 2009 SPiDCOM Technologies
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <linux/types.h>
#include <sys/socket.h>
#include <features.h>
#include <linux/if.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>

#include "spidupd_host.h"
#include <openssl/md5.h>
#include <unistd.h>
#include "../../u-boot-1.1.6/include/asm/arch-spc300/image_desc.h"

#define MAX_RETRY       40
#define RESTART_TIMEOUT 200000

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

enum rx_status_t
{
    RX_OK,
    RX_WRONG_PKT,
    RX_TIMEOUT,
    RX_ERROR,
    RX_STATUS_NB
};
typedef enum rx_status_t rx_status_t;

struct connection_t
{
    /** Host MAC address. */
    unsigned char host_addr[ETH_ALEN];
    /** Board MAC address. */
    unsigned char board_addr[ETH_ALEN];
    /** Socket file descriptor. */
    int fd;
};
typedef struct connection_t connection_t;

struct option long_opts[] = {
    {"dev", required_argument, NULL, 'd'},
    {"addr", required_argument, NULL, 'a'},
    {"file", required_argument, NULL, 'f'},
};

static inline void
print_usage (const char *cmd)
{
    fprintf(stderr, "Usage : %s\n"                          \
            "    --dev network device name (eth0...)\n"     \
            "    --addr board MAC address\n"                \
            "    --file file name\n",
            cmd);
}

static inline void
convert_mac_str_to_bin (const char *str, unsigned char addr[ETH_ALEN])
{
    int i;
    char *s, *e;

    s = (char *)str;
    for (i = 0; i < ETH_ALEN; ++i)
    {
        addr[i] = s ? strtoul (s, &e, 16) : 0;
        if (s)
            s = (*e) ? e + 1 : e;
    }
}

static inline void
prepare_mme_header (connection_t *connect, unsigned char *pkt,
                    unsigned short mmtype)
{
    MME_t *hdr;

    hdr = (MME_t *) pkt;

    memcpy (hdr->mme_dest, connect->board_addr, ETH_ALEN);
    memcpy (hdr->mme_src, connect->host_addr, ETH_ALEN);
    hdr->mtype = htons (ETH_P_HPAV);
    hdr->mmv = MME_MMV;
    hdr->mmtype = htommes (mmtype);
}

static connection_t *
create_connection (char *dev_name, unsigned char dest_addr[ETH_ALEN])
{
    struct sockaddr_ll sll;
    struct ifreq ifr;
    connection_t *connect;

    bzero (&sll, sizeof (sll));
    bzero (&ifr, sizeof (ifr));

    /* Create a connection structure. */
    connect = (connection_t *) malloc (sizeof (connection_t));
    if (connect == NULL)
        return NULL;

    /* Create a socket on MME. */
    if ((connect->fd = socket (AF_PACKET, SOCK_RAW, ETH_P_HPAV)) == -1)
    {
        perror ("Error creating raw socket");
        free (connect);
        return NULL;
    }

    /* Get the Interface Index. */
    strncpy ((char *) ifr.ifr_name, dev_name, IFNAMSIZ);
    if ((ioctl (connect->fd, SIOCGIFINDEX, &ifr)) == -1)
    {
        perror ("Error getting Interface index\n");
        close (connect->fd);
        free (connect);
        return NULL;
    }

    /* Bind socket to this interface index. */
    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons (ETH_P_HPAV);

    if ((bind (connect->fd, (struct sockaddr *) &sll, sizeof (sll))) == -1)
    {
        perror ("Error binding raw socket to interface\n");
        close (connect->fd);
        free (connect);
        return NULL;
    }

    /* Get host MAC address. */
    if ((ioctl (connect->fd, SIOCGIFHWADDR, &ifr)) == -1)
    {
        perror ("Error getting Interface MAC address\n");
        close (connect->fd);
        free (connect);
        return NULL;
    }

    /* Fill MAC addresses. */
    memcpy (connect->host_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
    memcpy (connect->board_addr, dest_addr, ETH_ALEN);

    return connect;
}

static inline void
close_connection (connection_t *connect)
{
    close (connect->fd);
    free (connect);
}

static int
get_image_descriptor (char *file, spidcom_image_desc_t *desc)
{
    FILE *img_file;
    ssize_t read_bytes;

    /* Open image file. */
    img_file = fopen (file, "r");

    /* Copy only the descriptor. */
    if ((read_bytes = fread (desc, 1, sizeof (spidcom_image_desc_t),
                             img_file)) != sizeof (spidcom_image_desc_t))
    {
        perror ("fread failed check your file");
        fclose (img_file);
        return -1;
    }

    /* Check file header magic word. */
    if (strcmp (desc->magic, SPIDCOM_IMG_DESC_MAGIC))
    {
        printf ("Error %s isn't a correct image\n", file);
        fclose (img_file);
        return -1;
    }

    return 0;
}

static int
send_packet (connection_t *connect, void *pkt, ssize_t len)
{
    ssize_t sent;

    /* Send the packet. */
    sent = send (connect->fd, pkt, len, 0);

    /* Error with send procedure. */
    if (sent < 0)
    {
        perror ("Error sending a packet");
        return -1;
    }

    /* Error with sent length. */
    if (sent != len)
    {
        printf ("Can only sent %d bytes but expected %d\n", sent, len);
        return -1;
    }

    return 0;
}

static rx_status_t
receive_packet (connection_t *connect, void *pkt,
                size_t max_len, unsigned long timeout, unsigned int type)
{
    int res;
    MME_t *hdr;
    fd_set read_to;
    struct timeval restart_to;
    struct sockaddr_ll packet_info;
    socklen_t packet_info_size = sizeof (packet_info);

    /* Prepare timeout. */
    FD_ZERO (&read_to);
    FD_SET (connect->fd, &read_to);
    restart_to.tv_sec = 0;
    restart_to.tv_usec = timeout;

    /* Wait reception with timeout. */
    res = select (connect->fd + 1, &read_to, NULL, NULL, &restart_to);

    /* Error with waiting procedure. */
    if (res < 0)
    {
        perror ("select failed");
        return RX_ERROR;
    }

    /* Wait until timeout. */
    else if (res == 0)
    {
        return RX_TIMEOUT;
    }

    /* Receive a packet before timeout. */
    else
    {
        /* Get the receive packet. */
        if (recvfrom (connect->fd, pkt, max_len, 0,
                      (struct sockaddr *) &packet_info,
                      &packet_info_size) < 0)
        {
            /* Reception error. */
            perror ("recvfrom failed");
            return RX_ERROR;
        }

        /* Check that the received packet is the expected. */
        hdr = (MME_t *) pkt;
        if (mmetohs (hdr->mmtype) != type)
        {
            return RX_WRONG_PKT;
        }
    }
    return RX_OK;
}

static int
connect_to_server (connection_t *connect, spidcom_image_desc_t *desc)
{
    int result = -1;
    unsigned char *tx_pkt;
    unsigned char *rx_pkt;
    ssize_t tx_pkt_len;
    rx_status_t rx_status;
    VsUpdStartReq_t *start_req;
    VsUpdStartCnf_t *start_cnf;
    unsigned long retry;

    /* Allocate TX and RX buffers for Request and Confirm MME exchange. */
    tx_pkt = (unsigned char *) malloc (PKTSIZE);
    rx_pkt = (unsigned char *) malloc (PKTSIZE);
    start_req = (VsUpdStartReq_t *) (tx_pkt + sizeof (MME_t));
    start_cnf = (VsUpdStartCnf_t *) (rx_pkt + sizeof (MME_t));

    /* Prepare START_REQ MME to send to the server. */
    prepare_mme_header (connect, tx_pkt, VS_UPDATE_START_REQ);

    memcpy (start_req->version, desc->version, sizeof (desc->version));
    start_req->arch = desc->arch;
    start_req->upd_type = desc->type;
    tx_pkt_len = sizeof (MME_t) + sizeof (VsUpdStartReq_t);

    /* Start connection procedure. */
    for (retry = 0 ; retry < MAX_RETRY ; retry++)
    {
        /* Send START_REQ MME. */
        if (send_packet (connect, tx_pkt, tx_pkt_len))
            break;

        /* Wait START_CNF MME. */
        rx_status = receive_packet (connect, rx_pkt, PKTSIZE, RESTART_TIMEOUT,
                                    VS_UPDATE_START_CNF);

        /* We receive a good packet. */
        if (rx_status == RX_OK)
        {
            /* Check the server response and quit whatever the answer. */
            if (start_cnf->start_update == SPIDUPD_SUCCESS)
                result = 0;
            else
                printf ("Cannot start Update procedure (error=%d)\n",
                        start_cnf->start_update);
            break;
        }

        /* There was an internal error during reception. Stop all. */
        else if (rx_status == RX_ERROR)
            break;

        /* We have received a wrong packet or a timeout.
         * Send the START_REQ MME again. */
        else
            continue;
    }

    free (tx_pkt);
    free (rx_pkt);
    return result;
}

static int
upload_to_server (connection_t *connect, char *file_name,
                  unsigned char *md5_sum)
{
    int result;
    unsigned char *tx_pkt;
    unsigned char *rx_pkt;
    ssize_t tx_pkt_min_len;
    ssize_t tx_pkt_data_len;
    rx_status_t rx_status;
    MD5_CTX ctx;
    FILE *img;
    VsUpdTransfReq_t *transfer_req;
    VsUpdTransfCnf_t *transfer_cnf;
    unsigned long block_counter = 0;
    unsigned long retry;

    /* Open the image to upload. */
    if ((img = fopen (file_name, "r")) == NULL)
    {
        perror ("open image file failed");
        return -1;
    }

    /* Allocate TX and RX buffers for Request and Confirm MME exchange. */
    tx_pkt = (unsigned char *) malloc (PKTSIZE);
    rx_pkt = (unsigned char *) malloc (PKTSIZE);
    transfer_req = (VsUpdTransfReq_t *) (tx_pkt + sizeof (MME_t));
    transfer_cnf = (VsUpdTransfCnf_t *) (rx_pkt + sizeof (MME_t));

    /* Prepare TRANSFER_REQ MME header. */
    prepare_mme_header (connect, tx_pkt, VS_UPDATE_TRANSFER_REQ);
    tx_pkt_min_len = sizeof (MME_t) + sizeof (VsUpdTransfReq_t) - sizeof (transfer_req->data);

    /* Prepare MD5 image calculation. */
    MD5_Init (&ctx);

    /* Read image file block by block. */
    while ((tx_pkt_data_len = fread (transfer_req->data, 1,
                                     SPIDUPD_BLOCK_SIZE, img)) > 0)
    {
        /* Calculate MD5. */
        MD5_Update (&ctx, transfer_req->data, tx_pkt_data_len);

        /* Finish TRANSFER_REQ MME to send. */
        transfer_req->block_id = htommel (++block_counter);
        transfer_req->length = htommel (tx_pkt_data_len);

        /* Show upload progression. */
        if ((block_counter % 50) == 0)
            printf (".");

        /* Try to send the block. */
        for (result = -1, retry = 0 ; retry < MAX_RETRY ; retry++)
        {
            /* Send TRANSFER_REQ MME. */
            if (send_packet (connect, tx_pkt,
                             tx_pkt_min_len + tx_pkt_data_len))
                break;

            /* Wait TRANSFER MME. */
            rx_status = receive_packet (connect, rx_pkt, PKTSIZE,
                                        RESTART_TIMEOUT,
                                        VS_UPDATE_TRANSFER_CNF);

            /* We receive a good packet. */
            if (rx_status == RX_OK)
            {
                /* Check the server response. */
                if (transfer_cnf->ack == SPIDUPD_SUCCESS)
                {
                    result = 0;
                    break;
                }
                /* Error on server with the last transfer, restart it. */
                else if (transfer_cnf->next_block == block_counter)
                    continue;
                /* Error on server with another transfer. Stop upload. */
                else
                {
                    printf ("Error on server during block %d transfer\n",
                            transfer_cnf->next_block);
                    break;
                }
            }

            /* There was an internal error during reception. Stop all. */
            else if (rx_status == RX_ERROR)
                break;

            /* We have received a wrong packet or a timeout.
             * Send the START_REQ MME again. */
            else
                continue;
        }
        if (result)
            break;
    }

    /* Finish MD5 image calculation. */
    MD5_Final (md5_sum, &ctx);

    free (tx_pkt);
    free (rx_pkt);
    fclose (img);
    return result;
}

static int
disconnect_from_server (connection_t *connect, unsigned char *md5_sum)
{
    int result = -1;
    unsigned char *tx_pkt;
    unsigned char *rx_pkt;
    ssize_t tx_pkt_len;
    rx_status_t rx_status;
    VsUpdEndReq_t *end_req;
    VsUpdEndCnf_t *end_cnf;
    unsigned long retry;

    /* Allocate TX and RX buffers for Request and Confirm MME exchange. */
    tx_pkt = (unsigned char *) malloc (PKTSIZE);
    rx_pkt = (unsigned char *) malloc (PKTSIZE);
    end_req = (VsUpdEndReq_t *) (tx_pkt + sizeof (MME_t));
    end_cnf = (VsUpdEndCnf_t *) (rx_pkt + sizeof (MME_t));

    /* Prepare END_REQ MME to send to the server. */
    prepare_mme_header (connect, tx_pkt, VS_UPDATE_END_REQ);

    memcpy (end_req->md5_sum, md5_sum, MD5_DIGEST_LENGTH);
    tx_pkt_len = sizeof (MME_t) + sizeof (VsUpdEndReq_t);

    /* Stop connection procedure. */
    for (retry = 0 ; retry < MAX_RETRY ; retry++)
    {
        /* Send END_REQ MME. */
        if (send_packet (connect, tx_pkt, tx_pkt_len))
            break;

        /* Wait END_CNF MME. */
        rx_status = receive_packet (connect, rx_pkt, PKTSIZE, RESTART_TIMEOUT,
                                    VS_UPDATE_END_CNF);

        /* We receive a good packet. */
        if (rx_status == RX_OK)
        {
            /* Check the server response and quit whatever the answer. */
            if (end_cnf->result == SPIDUPD_SUCCESS)
                result = 0;
            else
                printf ("Error on server during end procedure (error=%d)\n",
                        end_cnf->result);
            break;
        }

        /* There was an internal error during reception. Stop all. */
        else if (rx_status == RX_ERROR)
            break;

        /* We have received a wrong packet or a timeout.
         * Send the END_REQ MME again. */
        else
            continue;
    }

    free (tx_pkt);
    free (rx_pkt);
    return result;
}

int
main (int argc, char **argv)
{
    int c, opt_index = 0;
    char device_name[16];
    char file_name[PATH_MAX];
    unsigned char board_addr[ETH_ALEN];
    connection_t *connect;
    unsigned char md5_sum[MD5_DIGEST_LENGTH];
    spidcom_image_desc_t desc;

    /* Check arguments. */
    if (((argc - 1) / 2) != ARRAY_SIZE(long_opts))
    {
        print_usage (argv[0]);
        return -1;
    }

    /* Analyse arguments. */
    while ((c = getopt_long_only (argc, argv, "", long_opts,
                                  &opt_index)) != -1)
    {
        switch (c)
        {
        case 'd':
            /* Store device name. */
            strcpy (device_name, optarg);
            break;
        case 'a':
            /* Store board MAC address. */
            convert_mac_str_to_bin (optarg, board_addr);
            break;
        case 'f':
            /* Store file name to upload. */
            strcpy (file_name, optarg);
            break;
        default:
            print_usage (argv[0]);
            exit (1);
        }
    }

    /* Create + bind connection on asked network device. */
    connect = create_connection (device_name, board_addr);
    if (connect == NULL)
        return -1;

    /* Find Image header for upload informations. */
    if (get_image_descriptor (file_name, &desc))
    {
        close_connection (connect);
        return -1;
    }

    printf ("Connect to server...\n");
    if (connect_to_server (connect, &desc))
    {
        close_connection (connect);
        return -1;
    }
    printf ("done\n");

    printf ("Upload image...\n");
    if (upload_to_server (connect, file_name, md5_sum))
    {
        close_connection (connect);
        return -1;
    }
    printf ("done\n");

    printf ("Disconnect from server...\n");
    if (disconnect_from_server (connect, md5_sum))
    {
        close_connection (connect);
        return -1;
    }
    printf ("done\n");

    close_connection (connect);
    return 0;
}