summaryrefslogtreecommitdiff
path: root/cleopatre/tools/spidupd/spidupd_host.c
blob: 14ff98974232dbabd8179e3deb3abb54a74f181d (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
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
/*
 * 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
 *
 * Author(s):
 * Drasko DRASKOVIC, drasko.draskovic@spidcom.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <features.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <inttypes.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"

/** Host PC MAC address */
#define SRC_ETHER_ADDR	"00:11:95:dc:d1:3f"
/** Board MAC address */
#define DST_ETHER_ADDR	"00:50:c2:38:00:0B"

/** MME Ethertype (SPiDCOM Update) */
#define PROT_SPIDUPD            0x88E1
/** server response timeout in seconds */
#define SRV_CNF_TIMEOUT         1
/** arbitrary chosen error code for server timeout event */
#define SRV_TIMEOUT_ERR_CODE    -111

/** Number of retries in case of server response timeout */
#define MAX_TMO_RETRY           5
/** Wait a little longer for UPDATE_END_CNF, because it takes time to write flash */
#define MAX_TMO_END_RETRY       120
/** Number of retries in case of server not ack the package */
#define MAX_PKT_RETRY           5

/**
 * Convert a byte into a string in hexadecimal.
 * \param  str  string result
 * \param  ptr  bytes to convert
 * \param  len  number of bytes
 * \param  delim  delimiter inserted between each byte
 */
static void
sprintf_hex (unsigned char *str, const unsigned char *ptr,
             int len, unsigned char delim)
{
    static const unsigned char __hexdigits[] = "0123456789ABCDEF";
    int i, j = 0;
    for (i = 0; i < len; i++)
    {
        if (i)
            str[j++] = delim;
        str[j++] = __hexdigits[ptr[i] >> 4];
        str[j++] = __hexdigits[ptr[i] & 0x0F];
    }
    str[j] = 0;
}

/**
 * Set a timeout for the socket connection.
 * \param  rawsock  socket fd
 * \param  milliseconds  timeout in ms
 * \return  error code
 */
int
SetSocketTimeout (int rawsock, int milliseconds)
{
    struct timeval tv;

    tv.tv_sec = milliseconds / 1000;
    tv.tv_usec = (milliseconds % 1000) * 1000;

    return setsockopt (rawsock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv,
                       sizeof tv);
}

/**
 * Get the MAC address of a device (eth0...).
 * \param  device  device name
 * \param  rawsock  socket fd
 * \param  our_addr  MAC address result
 * \return  error code
 */
int
GetMacAddr (char *device, int rawsock, unsigned char our_addr[6])
{
    int i = 0;
    struct ifreq ifr;

    strcpy (ifr.ifr_name, device);
    ioctl (rawsock, SIOCGIFHWADDR, &ifr);

    for (i = 0; i < 6; i++)
    {
        our_addr[i] = (unsigned char) ifr.ifr_hwaddr.sa_data[i];
    }

    return 0;
}

/**
 * Socket creation.
 * \param  protocol_to_sniff  protocol to sniff
 * \return  error code
 */
int
CreateRawSocket (int protocol_to_sniff)
{
    int rawsock;

    if ((rawsock =
         socket (PF_PACKET, SOCK_RAW, htons (protocol_to_sniff))) == -1)
    {
        perror ("Error creating raw socket: ");
        exit (-1);
    }

    return rawsock;
}

/**
 * Bind a socket.
 * \param  device  device interface
 * \param  rawsock  socket fd
 * \param  protocol  protocol to bind
 * \return  error code
 */
int
BindRawSocketToInterface (char *device, int rawsock, int protocol)
{
    struct sockaddr_ll sll;
    struct ifreq ifr;

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

    /* First Get the Interface Index  */
    strncpy ((char *) ifr.ifr_name, device, IFNAMSIZ);
    if ((ioctl (rawsock, SIOCGIFINDEX, &ifr)) == -1)
    {
        printf ("Error getting Interface index !\n");
        exit (-1);
    }


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


    if ((bind (rawsock, (struct sockaddr *) &sll, sizeof (sll))) == -1)
    {
        perror ("Error binding raw socket to interface\n");
        exit (-1);
    }

    return 1;
}

/**
 * Send a packet.
 * \param  rawsock  socket fd
 * \param  pkt  packet to send
 * \param  pkt_len  packet length
 * \return  error code
 */
int
SendRawPacket (int rawsock, unsigned char *pkt, int pkt_len)
{
    int sent = 0;

    /* A simple write on the socket ..thats all it takes ! */
    if ((sent = write (rawsock, pkt, pkt_len)) != pkt_len)
    {
        /* Error */
        printf ("Could only send %d bytes of packet of length %d\n", sent,
                pkt_len);
        return 0;
    }

    return 1;
}

/**
 * Create an Ethernet header.
 * \param  pkt  buffer for header result
 * \param  src_mac  MAC address source
 * \param  dst_mac  MAC address destination
 * \param  protocol  Ethernet type
 */
void
CreateEthernetHeader (unsigned char *pkt, char *src_mac, char *dst_mac,
                      int protocol)
{
    struct ethhdr *ethernet_header;

    ethernet_header = (struct ethhdr *) pkt;

    /* copy the Src mac addr */
    memcpy (ethernet_header->h_source, (void *) ether_aton (src_mac), 6);

    /* copy the Dst mac addr */
    memcpy (ethernet_header->h_dest, (void *) ether_aton (dst_mac), 6);

    /* copy the protocol */
    ethernet_header->h_proto = htons (protocol);
}

/**
 * Print a packet
 * \param  packet  packet to print
 * \param  len  length to print
 */
void
PrintPacketInHex (unsigned char *packet, int len)
{
    unsigned char *p = packet;

    printf ("\n\n---------Packet---Starts----\n\n");

    while (len--)
    {
        printf ("%.2x ", *p);
        p++;
    }

    printf ("\n\n--------Packet---Ends-----\n\n");

}

void
PrintInHex (char *mesg, unsigned char *p, int len)
{
    printf (mesg);

    while (len--)
    {
        printf ("%.2X ", *p);
        p++;
    }

}

/**
 * Ethernet header parser
 * \param  packet  packet to parse
 * \param  len  length to parse
 */
void
ParseEthernetHeader (unsigned char *packet, int len)
{
    struct ethhdr *ethernet_header;

    if (len > sizeof (struct ethhdr))
    {
        ethernet_header = (struct ethhdr *) packet;

        /* First set of 6 bytes are Destination MAC */

        PrintInHex ("Destination MAC: ", ethernet_header->h_dest, 6);
        printf ("\n");

        /* Second set of 6 bytes are Source MAC */

        PrintInHex ("Source MAC: ", ethernet_header->h_source, 6);
        printf ("\n");

        /* Last 2 bytes in the Ethernet header are the protocol it carries */

        PrintInHex ("Protocol: ", (void *) &ethernet_header->h_proto, 2);
        printf ("\n");


    }
    else
    {
        printf ("Packet size too small !\n");
    }
}

/**
 * Listern on socket.
 * \param  raw  socket to listen
 * \return  error code
 */
int
ListenSocket (int raw)
{
    unsigned char *packet_buffer, *pkt_start;
    int len;
    struct sockaddr_ll packet_info;
    int packet_info_size = sizeof (packet_info);
    MME_t *s;
    int res;

    fd_set readset;
    struct timeval srv_cnf_timeout;

    int rc;

    MsUpdStartCnf_t *ms_update_start_cnf;
    MsUpdTransfCnf_t *ms_update_transfer_cnf;
    MsUpdEndCnf_t *ms_update_end_cnf;

    packet_buffer = (unsigned char *) calloc (PKTSIZE, sizeof (char));
    pkt_start = packet_buffer;

    /* check for socket timeout */
    FD_ZERO (&readset);
    FD_SET (raw, &readset);
    srv_cnf_timeout.tv_sec = SRV_CNF_TIMEOUT;
    srv_cnf_timeout.tv_usec = 0;

    /* readset fd_set is containing only our socket, so no need to check with FD_ISSET() */
    res = select (raw + 1, &readset, NULL, NULL, &srv_cnf_timeout);
    if (res < 0)
    {
        perror ("select() failed");
    }
    else if (res == 0)  /* timeout */
    {
        //printf("Server response timeout.\n");
        rc = SRV_TIMEOUT_ERR_CODE;
    }
    else        /* everything is cool, socket is ready for reading */
    {

        if ((len =
             recvfrom (raw, packet_buffer, PKTSIZE, 0,
                       (struct sockaddr *) &packet_info,
                       &packet_info_size)) < 0)
        {
            perror ("Recv from returned error: ");
            exit (-1);
        }
        else
        {
            /* Packet has been received successfully !! */
            //PrintPacketInHex(packet_buffer, len);
        }

        s = (MME_t *) packet_buffer;
        packet_buffer += MME_HDR_SIZE;

        switch (mmetohs (s->mmtype))
        {
        case MS_UPDATE_START_CNF:
            ms_update_start_cnf = (MsUpdStartCnf_t *) packet_buffer;
            rc = ms_update_start_cnf->start_update;
            break;

        case MS_UPDATE_TRANSFER_CNF:
            ms_update_transfer_cnf = (MsUpdTransfCnf_t *) packet_buffer;
            rc = ms_update_transfer_cnf->ack;
            break;

        case MS_UPDATE_END_CNF:
            ms_update_end_cnf = (MsUpdEndCnf_t *) packet_buffer;
            rc = ms_update_end_cnf->result;
            break;

          deafault:
            break;
        }
    }

    return rc;
}

/**
 * Main program.
 * \param  argc  number of arguments
 * \param  argv  argument list
 * \return  error code
 *
 * argv[1] is the device e.g. eth0
 */
int
main (int argc, char **argv)
{
    int raw;
    unsigned char *packet;
    unsigned char *pkt_start;
    int ethhdr_len;
    int pkt_len = 0;
    int data_len = 0;
    unsigned char our_mac[6];
    unsigned char our_mac_string[18];
    unsigned char board_mac_string[18];
    MME_t *s;
    unsigned char tmp_buffer[SPIDUPD_BLOCK_SIZE];
    FILE *pImgFile;
    int block_counter = 0;
    unsigned char md5_sum[16];
    MD5_CTX ctx;
    int read_bytes;
    int i;
    int pkt_retry = 0;
    int tmo_retry = 0;
    int res;
    spidcom_image_desc_t desc;

    static MsUpdStartReq_t *ms_update_start_req;
    static MsUpdTransfReq_t *ms_update_transfer_req;
    static MsUpdEndReq_t *ms_update_end_req;

    if (argc != 3)
    {
        perror ("Wrong parameters: spidupd_test <iface> <img_name>");
        exit (1);
    }

    /* Create the raw socket */
    raw = CreateRawSocket (ETH_P_ALL);

    /* Bind raw socket to interface */
    BindRawSocketToInterface (argv[1], raw, ETH_P_ALL);

    /* create Ethernet header */
    GetMacAddr (argv[1], raw, our_mac);
    sprintf_hex (our_mac_string, our_mac, 6, ':');
    //strcpy(board_mac_string, (const char *)argv[2]);

    /* allocate packet */
    packet = (unsigned char *) calloc (PKTSIZE, sizeof (char));

    /* record the start position of the packet pointer */
    pkt_start = packet;

    //CreateEthernetHeader(packet, our_mac_string, board_mac_string, PROT_SPIDUPD);
    CreateEthernetHeader (packet, SRC_ETHER_ADDR, DST_ETHER_ADDR,
                          PROT_SPIDUPD);
    ethhdr_len = sizeof (struct ethhdr);

    /* zero-ot image descriptor struct */
    memset (&desc, 0, sizeof (spidcom_image_desc_t));

    /* file image desc struct */
    //pImgFile = fopen("linux-kernel-2.6.25.10-arm", "r");
    pImgFile = fopen (argv[2], "r");

    read_bytes = fread (&desc, 1, sizeof (spidcom_image_desc_t), pImgFile);

    /* --- MESSAGES --- */

    /*
     * MS_UPDATE_START_REQ
     */
    s = (MME_t *) packet;
    s->mmv = MME_MMV;
    s->mmtype = htommes (MS_UPDATE_START_REQ);

    s++;        /*skip the header */
    packet = (unsigned char *) s;

    ms_update_start_req = (MsUpdStartReq_t *) packet;
    memcpy (ms_update_start_req->version, (&desc)->version,
            sizeof ((&desc)->version));
    ms_update_start_req->arch = (&desc)->arch;
    ms_update_start_req->upd_type = (&desc)->type;

    /* go to the end of message... */
    packet += sizeof (MsUpdStartReq_t);

    /*Detertermine total packet length */
    pkt_len = packet - pkt_start;

    /* Position packet pointer to strt of the packet */
    packet = pkt_start;


    /* if packet is not acknowledged ot it is timed out,
     * try several times to re-send same packet */
    printf ("Requesting update start... ");
    fflush (stdout);
    tmo_retry = MAX_TMO_RETRY;
    //while (tmo_retry > 0)
    /* correction - client waits with infinite timeout    */
    while (1)
    {
        if (!SendRawPacket (raw, packet, pkt_len))
        {
            perror ("Error sending packet");
        }
        else
            //printf("Requested update start...");

        if ((res = ListenSocket (raw)) == SRV_TIMEOUT_ERR_CODE)
        {
            //tmo_retry--;
            continue;
        }
        else if (res != SPIDUPD_SUCCESS)
        {
            printf ("Error - Cannot start update.\n");
            exit (-1);
        }
        else    /* success */
        {
            printf ("OK\n");
            break;
        }
    }

    if (tmo_retry == 0)
    {
        printf ("\nTimeout error : no response from the server.\n");
        exit (-1);
    }

    /*
     * MS_UPDATE_TRANSFER_REQ
     */
    rewind (pImgFile);
    read_bytes = fread (tmp_buffer, 1, SPIDUPD_BLOCK_SIZE, pImgFile);

    /* init md5 context before we start calculating md5_sum
     * we will need md5 sum to send in the end */
    MD5_Init (&ctx);

    printf ("Uploading Linux image :\n");

    do
    {
        /* We are about to send new block */
        block_counter++;

        /* reset packet data, but keep the eth header */
        packet = pkt_start;
        memset (packet + ethhdr_len, 0, PKTSIZE - ethhdr_len);
        /* form new message */
        s = (MME_t *) packet;
        s->mmv = MME_MMV;
        s->mmtype = htommes (MS_UPDATE_TRANSFER_REQ);

        s++;    /*skip the header */
        packet = (unsigned char *) s;

        ms_update_transfer_req = (MsUpdTransfReq_t *) packet;
        ms_update_transfer_req->block_id = htommel (block_counter);
        ms_update_transfer_req->length = htommel (read_bytes);

        for (i = 0; i < read_bytes; i++)
        {
            ms_update_transfer_req->data[i] = tmp_buffer[i];
        }

        /* update md5 context */
        MD5_Update (&ctx, ms_update_transfer_req->data, read_bytes);


        /* go to the end of message... */
        packet += MME_HDR_SIZE + 2 * sizeof (int) + read_bytes;

        /*Detertermine total packet length */
        pkt_len = packet - pkt_start;

        /* Position packet pointer to strt of the packet */
        packet = pkt_start;

        /* if packet is not acknowledged ot it is timed out,
         * try several times to re-send same packet */
        tmo_retry = MAX_TMO_RETRY;
        pkt_retry = MAX_PKT_RETRY;
        while ((tmo_retry > 0) && (pkt_retry > 0))
        {
            if (!SendRawPacket (raw, packet, pkt_len))
            {
                perror ("Error sending packet");
            }
            else
            {
                if ((block_counter % 50) == 0)
                {
                    printf ("#");
                    fflush (stdout);
                }

                if ((block_counter % 2500) == 0)
                {
                    putchar ('\n');
                    fflush (stdout);
                }
            }

            if ((res = ListenSocket (raw)) == SRV_TIMEOUT_ERR_CODE)
            {
                tmo_retry--;
                continue;
            }
            else if (res != SPIDUPD_SUCCESS)
            {
                printf ("Packet not acknowledged. ");

                pkt_retry--;
                continue;
            }
            else        /* success */
            {
                break;
            }
        }

        if (tmo_retry == 0)
        {
            printf ("timeout error : no response from the server.\n");
            exit (-1);
        }

        if (pkt_retry == 0)
        {
            printf ("Maximum number of packet retries exceeded.\n");
            exit (-1);
        }

    }
    while ((read_bytes =
            fread (tmp_buffer, 1, SPIDUPD_BLOCK_SIZE, pImgFile)) > 0);

    printf ("\nDone.\n");

    /* Get final md5 */
    MD5_Final (md5_sum, &ctx);

    fclose (pImgFile);


    /*
     * MS_UPDATE_END_REQ
     */

    /* reset packet data, but keep the eth header */
    packet = pkt_start;
    memset (packet + ethhdr_len, 0, PKTSIZE - ethhdr_len);
    /* form new message */
    s = (MME_t *) packet;
    s->mmv = MME_MMV;
    s->mmtype = htommes (MS_UPDATE_END_REQ);

    s++;        /* skip the header */
    packet = (unsigned char *) s;

    ms_update_end_req = (MsUpdEndReq_t *) packet;
    memcpy (ms_update_end_req->md5_sum, md5_sum, 16);


    /* go to the end of message... */
    packet += sizeof (MsUpdEndReq_t);

    /* Detertermine total packet length */
    pkt_len = packet - pkt_start;

    /* Position packet pointer to strt of tyhe packet,
     * and send the packet */
    packet = pkt_start;

    /* if packet is not timed-out try several times to re-send same packet */
    printf ("Waiting on the server to burn image on flash :\n");
    fflush (stdout);
    tmo_retry = MAX_TMO_END_RETRY;
    while (tmo_retry > 0)
    {
        if (!SendRawPacket (raw, packet, pkt_len))
        {
            perror ("Error sending packet");
        }
        else
            //printf ("UPD_END_REQ sent : ");


        if ((res = ListenSocket (raw)) == SRV_TIMEOUT_ERR_CODE)
        {
            printf (">");
            fflush (stdout);
            tmo_retry--;
            continue;
        }
        else if (res != SPIDUPD_SUCCESS)
        {
            printf ("Error - Cannot finish update.\n");
            exit (-1);
        }
        else    /* success */
        {
            printf ("| Done.\n");
            break;
        }
    }

    if (tmo_retry == 0)
    {
        printf ("Timeout error : no response from the server.\n");
        exit (-1);
    }

    /* if we came this far, image was well updated */
    printf ("\nImage has been sucesfully updated.\n\n");

    /* --- END OF MESSAGES --- */

    /* Free the ethernet_header back to the heavenly heap */
    free (packet);

    close (raw);

    return 0;
}