summaryrefslogtreecommitdiff
path: root/cleopatre/application/libmme/src/mme.c
blob: 1e66cbd963c1c05dfcc620ea4c167b63e7472ea7 (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
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
/* SPC300 bundle {{{
 *
 * Copyright (C) 2009 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    application/libmme/src/mme.c
 * \brief   MME management library
 * \ingroup libmme
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <inttypes.h>
#include <syslog.h>

#include "libmme.h"

/**
 * Create a MME message context. This context is used to build the MME message step by step.<br>
 * The provided buffer must be enough large to contain all the final payload.<br>
 * The MME payload can be bigger than an ethernet payload, as the fragmentation is managed by the 'send' function.
 *
 * \param  ctx MME context to fill with init value
 * \param  mmtype type of MME message (must be in official type list)
 * \param  buffer the buffer to put the payload
 * \param  length  the buffer length
 * \return error type (MME_SUCCESS if success)
 */

mme_error_t
mme_init (mme_ctx_t *ctx, const mme_type_t mmtype, unsigned char *buffer, const unsigned int length)
{
    /* protect from null pointers */
    if (ctx == NULL || buffer == NULL)
        return MME_ERROR_GEN;

    ctx->buffer     =   buffer;
    ctx->mmtype     =   mmtype;
    ctx->length     =   length;
    ctx->head       =   0;
    ctx->tail       =   0;

    ctx->status     =   MME_STATUS_OK;

    return MME_SUCCESS;
}

/** Get the current MME payload length
 *
 * \param ctx MME context to get the payload length
 * \param length the returned length
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 */

mme_error_t
mme_get_length (mme_ctx_t *ctx, unsigned int *length)
{
    /* protect from null pointers */
    if (ctx == NULL || length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    *length = ctx->tail - ctx->head;
    return MME_SUCCESS;
}

/** Get the remaining free space to add payload
 *
 * \param ctx MME context to get the remaining space
 * \param length the remaining space
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 */

mme_error_t
mme_get_free_space (mme_ctx_t *ctx, unsigned int *length)
{
    /* protect from null pointers */
    if (ctx == NULL || length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    *length = ctx->length - (ctx->tail - ctx->head);
    return MME_SUCCESS;
}


/**
 * Push data at the beginning of the MME payload. Data are inserted between the start of buffer and the current payload data.<br>
 * MME data tail and length are updated.<br>
 * If there is not enough free place to push data, an error is returned and the remaining free space length is returned.
 *
 * \param  ctx MME context where to push data
 * \param  data data to be pushed into payload
 * \param  length length of data to push
 * \param  result_length length of data really pushed
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 * \return MME_ERROR_SPACE: not enough available space
 */

mme_error_t
mme_push (mme_ctx_t *ctx, const void *data, unsigned int length, unsigned int *result_length)
{
    int free = 0;
    int delta = 0;

    /* protect from null pointers */
    if (ctx == NULL || data == NULL || result_length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    free = ctx->length - (ctx->tail - ctx->head);
    if (length > free)
    {
        *result_length = free;
        return MME_ERROR_SPACE;
    }

    *result_length = length;

    /* make place in front, if needed */
    if (length > ctx->head)
    {
        /*
         *             *length
         *  .-----------^-----------.
         *  |---------|xxxxxxxxxxxxx|--------------------|---------------------|
         * buff      head                              tail                 ctx->length
         *             \_______________  _______________/
         *                             \/
         *                           pyload
         *
         * we have to shift right our payload for this difference delta marked with 'x'
         * in order for *length bytes to fit in from beginning of the buffer
         */
        delta = length - ctx->head;
        memmove (ctx->buffer + ctx->head + delta, ctx->buffer + ctx->head, ctx->tail - ctx->head);

        /* update head and tail pointers (offsets) */
        ctx->head += delta;
        ctx->tail += delta;
    }

    ctx->head -= length;    /* place head pointer to where copy chould start from */
    memcpy (ctx->buffer + ctx->head, data, length);

    return MME_SUCCESS;
}

/**
 * Put data at the end of MME payload. MME data tail and length are updated<br>
 * If there is not enough free place to put data, an error is returned and the remaining free space length is returned.
 *
 * \param  ctx MME context where to put data
 * \param  data data to put at the end of MME payload
 * \param  length length of data to put
 * \param  result_length length of data really put
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 * \return MME_ERROR_SPACE: not enough available space
 */

mme_error_t
mme_put (mme_ctx_t *ctx, const void *data, unsigned int length, unsigned int *result_length)
{
    int free = 0;
    int delta = 0;

    /* protect from null pointers */
    if (ctx == NULL || data == NULL || result_length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    free = ctx->length - (ctx->tail - ctx->head);
    if (length > free)
    {
        *result_length = free;
        return MME_ERROR_SPACE;
    }

    *result_length = length;

    /* make place after payload, if needed */
    if (length > ctx->length - ctx->tail)
    {
        /*
         *                                       *length
         *                           .---------------^-----------------.
         *  |-----------|------------|xxxxxxx|-------------------------|
         * buff        head                 tail                    ctx->length
         *               \________  ________/
         *                        \/
         *                      payload
         *
         * we have to shift left our payload for this difference delta marked with 'x'
         * in order for *length bytes to fit in from beginning of the buffer
         */
        delta = length - (ctx->length - ctx->tail);
        memmove ((unsigned char *) (ctx->buffer + ctx->head - delta), (unsigned char *) (ctx->buffer + ctx->head), ctx->tail - ctx->head);

        /* update head and tail pointers (offsets) */
        ctx->head -= delta;
        ctx->tail -= delta;
    }

    memcpy ((unsigned char *) (ctx->buffer + ctx->tail), (unsigned char *) data, length);
    ctx->tail += length;

    return MME_SUCCESS;
}

/**
 * Pull (get) data from beginning of MME payload. MME data head and length are updated<br>
 * If there is not enough data to pull, an error is returned and the remaining payload length is returned.
 *
 * \param  ctx MME context where to get data
 * \param  data buffer where to get data from the beginning of MME payload
 * \param  length length of data to pull
 * \param result_length length of data pulled; if there is not enough data into the MME to fit the length, the remaining data length is returned
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 */

mme_error_t
mme_pull (mme_ctx_t *ctx, void *data, unsigned int length, unsigned int *result_length)
{
    /* protect from null pointers */
    if (ctx == NULL || data == NULL || result_length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    /* check if it is demanded more data than we have in payload */
    if (length > ctx->tail - ctx->head)
    {
        *result_length = ctx->tail - ctx->head;
        return MME_ERROR_ENOUGH;
    }

    *result_length = length;

    memcpy (data, (unsigned char *) (ctx->buffer + ctx->head), length);
    ctx->head += length;

    return MME_SUCCESS;
}

/**
 * Pop (get) data from the end of MME payload. MME data tail and length are updated<br>
 * If there is not enough data to pull, an error is returned and the remaining payload length is returned.
 *
 * \param  ctx MME context where to get data
 * \param  data buffer where to get data from the end of MME payload
 * \param  length length of data to pull
 * \param result_length length of data gotten; if there is not enough data into the MME to fit the length, the remaining data length is returned
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 * \return MME_ERROR_SPACE: not enough available space
 */

mme_error_t
mme_pop (mme_ctx_t *ctx, void *data, unsigned int length, unsigned int *result_length)
{
    /* protect from null pointers */
    if (ctx == NULL || data == NULL || result_length == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    /* check if it is demanded more data than we have in payload */
    if (length > ctx->tail - ctx->head)
    {
        *result_length = ctx->tail - ctx->head;
        return MME_ERROR_ENOUGH;
    }

    *result_length = length;

    memcpy (data, (unsigned char *) (ctx->buffer + ctx->tail - length), length);
    ctx->tail -= length;

    return MME_SUCCESS;
}

static int
_get_iface_mac_addr (int sock, char *iface, unsigned char *mac_addr)
{
    struct ifreq ifr;

    memset (&ifr, 0x0, sizeof (ifr));
    /* Get the interface Index  */
    strncpy (ifr.ifr_name, iface, IFNAMSIZ);
    if ((ioctl (sock, SIOCGIFINDEX, &ifr)) < 0)
    {
        return -1;
    }
    if (ioctl (sock, SIOCGIFHWADDR, &ifr) < 0)
    {
        return -1;
    }
    memcpy (mac_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
    return 0;
}

/**
 * Send MME to network interface and wait for confirm MME; this is a synchronous transmit and receive transaction
 * (function waits for answer MME before returning). If no answer packet is received before MME_CONFIRM_TIMEOUT,
 * error is returned.<br>
 * As MME are level 2 and IP routing does not apply, the network interface where to send data packet must be selected inside
 * iface paramater. For instance : "eth0", "br0", ...<br>
 * If an MME needs to be fragmented, the sending process is in charge to manage the fragmentation. The same as reassembling
 * the fragmented MME confirm.<br>
 * 3 types of communication can be done :
 * <ul><li>MME_SEND_REQ_CNF : request and confirm transaction
 * <li> MME_SEND_CNF : confirm only (no answer expected)
 * <li>MME_SEND_IND_RSP : indicate and response transaction
 * <li>MME_SEND_IND : indicate only (no answer expected)
 * </ul>
 *
 * \param  ctx MME context to send
 * \param  type transaction type
 * \param  iface selected communication interface; if NULL, "br0" if remote destination, "lo" if local
 * \param  dest destination MAC address in binary format (6 bytes)
 * \param  confirm_ctx MME context given to put the received MME answer packet. A adapted buffer must have been provided.
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 */

mme_error_t
mme_send (mme_ctx_t *ctx, mme_send_type_t type, char *iface, unsigned char *dest, mme_ctx_t *confirm_ctx)
{
    int raw;
    struct sockaddr_ll sll;
    struct ifreq ifr;
    MME_t *mh;
    unsigned char src_mac[6] = {0};     /* MAC of chosen interface */
    unsigned char *pkt;
    unsigned char pkt_holder[PKTSIZE] = {0};
    int pkt_len;
    int sent;
    unsigned short nbpkt = 0;
    fd_set fds;
    int fo;      /* current fragment offset */
    int fs;      /* current fragment size */
    struct sockaddr_ll pkt_info;
    int last_pkt = 0;
    unsigned short hfmi;    /* fmi in host byte order */
    struct timeval timeout; /* When we should time out */
    struct timeval now;
    struct timeval waittime;
    int res;
    unsigned int len, result_len;
    int i;
    int pkt_nfo_sz = sizeof (pkt_info);
    mme_error_t ret;
    int pkt_cnt = 0;
    char *iface_real;

    /* protect from null pointers */
    if (ctx == NULL || confirm_ctx == NULL || dest == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    /*
     * #####################
     * #    SEND
     * #####################
     */

    /*
     * --- Create the raw socket ---
     */
    if ((raw = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_HPAV))) == -1)
    {
        perror ("Error creating raw socket: ");
        return MME_ERROR_GEN;
    }

    memset (&sll, 0x0, sizeof (sll));
    memset (&ifr, 0x0, sizeof (ifr));

    /* get the bridge mac-address */
    _get_iface_mac_addr (raw, MME_IFACE_BRIDGE, src_mac);

    /* check for real interface to use */
    if (NULL == iface)
    {
        /* let libmme guess the right interface */
        if (!memcmp (src_mac, dest, ETH_ALEN))
        {
            /* this is a local request */
            iface_real = MME_IFACE_LOOPBACK;
        }
        else
        {
            /* this is a request to remote product */
            iface_real = MME_IFACE_BRIDGE;
        }
    }
    else
    {
        /* keep the same interface */
        iface_real = iface;
    }

    /* Get index of needed interface  */
    strncpy (ifr.ifr_name, iface_real, IFNAMSIZ);
    if ((ioctl (raw, SIOCGIFINDEX, &ifr)) == -1)
    {
        printf ("%s: Error getting %s index !\n", __FUNCTION__, iface_real);
        close (raw);
        return MME_ERROR_GEN;
    }

    /* Bind our raw socket to this interface */
    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons (ETH_P_HPAV);
    if ((bind (raw, (struct sockaddr *)&sll, sizeof (sll)))== -1)
    {
        perror ("Error binding raw socket to interface\n");
        close (raw);
        return MME_ERROR_GEN;
    }

    /*
     * --- Create MME header ---
     */

    mh = (MME_t *)pkt_holder;
    /* copy the Src mac addr */
    memcpy (mh->mme_src, (void *)src_mac, 6);
    /* copy the Dst mac addr */
    memcpy (mh->mme_dest, (void *)dest, 6);
    /* copy the protocol */
    mh->mtype = htons (MME_TYPE);
    /* set default mme version */
    mh->mmv = MME_VERSION;
    /* set mmtype */
    mh->mmtype = ctx->mmtype;
    mh->fmi = 0;

    /* calculate number of mme packets needed */
    nbpkt = (ctx->tail - ctx->head) / (PKTSIZE - sizeof (MME_t));
    if (nbpkt == 0 || (ctx->tail - ctx->head) % (PKTSIZE - sizeof (MME_t)) > 0)
    {
        nbpkt++;
    }
    /* set fragmentation info, nb of fragments */
    hfmi = nbpkt - 1;

    /* initialize fragment offset to the begining of the payload*/
    fo = ctx->head;

    /* prepare and send out packets */
    for (i=0; i<nbpkt; i++)
    {
        /*
         * --- Set per-message fragmentation info, current fragment number ---
         */
        /* clear out higher bits, keep only bits 0-3 */
        hfmi &= 0x0f;
        /* set bits 4-7 to a new value */
        hfmi |= i << 4 ;

        /* We now have correct hfmi, so we can set our pkg field (in network byteorder) */
        mh->fmi = hfmi;

        /*
         * --- Append payload ---
         */
        /* skip the MME header */
        pkt = pkt_holder + sizeof (MME_t);
        /* calculate the size of the current fragment */
        fs = (ctx->tail - fo < PKTSIZE - sizeof (MME_t)) ? ctx->tail - fo : PKTSIZE - sizeof (MME_t);
        /* copy the content into packet buffer */
        memcpy (pkt, ctx->buffer + fo, fs);
        /* update fo */
        fo += fs;
        /* zero-pad the rest if last packet fs < MME_MIN_SIZE, which is minimum size for mme packet */
        if (fs < MME_MIN_SIZE)
        {
            memset (ctx->buffer + fo, 0x0, MME_MIN_SIZE - fs);
            fs = MME_MIN_SIZE;
        }

        /*
         * --- Send raw packet ---
         */
        /* initialize pkt pointer to the start of the send buffer */
        pkt = pkt_holder;

        /* determine the size of whole packet (header + data) */
        pkt_len = sizeof (MME_t) + fs;
        if ((sent = write (raw, pkt, pkt_len)) != pkt_len)
        {
            perror ("string error\n");
            /* Error */
            syslog (LOG_WARNING, "%s: Could only send %d bytes of packet of length %d", __FUNCTION__, sent, pkt_len);
            close (raw);
            return MME_ERROR_GEN;
        }
    } /* for */

    /* we should exit here if we do not have to wait on response */
    if (type == MME_SEND_CNF || type == MME_SEND_IND)
    {
        /* if we had to send a .CNF or .IND only we have finished,
         * beacuse these MME messages does not require response */
        close (raw);
        return MME_SUCCESS;
    }

    /*
     * #####################
     * #    RECEIVE
     * #####################
     */

    /* Calculate into 'timeout' when we should time out */
    gettimeofday (&timeout, 0);
    timeout.tv_sec += MME_TOUT;

    /* initialize packet counter */
    pkt_cnt = 0;

    do  /* receive the payload, packet by packet */
    {
        /* rewind pkt pointer to begining of the packet holder */
        pkt = pkt_holder;

        for (;;)  /* try to receive until we get response from our proper server */
        {
            /* Force timeout if we ran out of time */
            gettimeofday (&now, 0);
            if (timercmp (&now, &timeout, >) != 0)
            {
                printf ("Server response timeout.\n");
                close (raw);
                return MME_ERROR_TIMEOUT;
            }

            /* Calculate into 'waittime' how long to wait */
            timersub (&timeout, &now, &waittime); /* wait = timeout - now */

            /* Init fds with 'sock' as the only fd */
            FD_ZERO (&fds);
            FD_SET (raw, &fds);

            /* fds fd_set is containing only our socket, so no need to check with FD_ISSET() */
            res = select (raw + 1, &fds, NULL, NULL, &waittime);

            if (res < 0)
            {
                perror ("select() failed");
                close (raw);
                return MME_ERROR_GEN;
            }
            else if (res == 0)  /* timeout */
            {
                printf ("Server response timeout.\n");
                close (raw);
                return MME_ERROR_TIMEOUT;
            }

            if ((len = recvfrom (raw, pkt, PKTSIZE, 0, (struct sockaddr*)&pkt_info, (socklen_t *)&pkt_nfo_sz)) < 0)
            {
                perror ("Recv from returned error: ");
                close (raw);
                return MME_ERROR_TXRX;
            }

            mh =  (MME_t *)pkt;
            hfmi = mh->fmi;

            /* check if response came from the our proper server, and if it is,
             * check if correspondent response was sent (REQ/CNF or IND/RSP);
             * by HP AV standard difference is in LSB, i.e. if REQ LSBs are ...00,
             * CNF will be ...01, IND ...10 and RSP ...11 */
            if (memcmp (pkt_info.sll_addr, dest, 6) == 0    &&      /* we received packet from correct source */
                (mh->mmtype == confirm_ctx->mmtype) &&             /* we received type that we expect */
                 hfmi >> 4 == pkt_cnt )                             /* packets are coming in the right order */

            {
                break;  /* good answer - go out and process the package */
            }
        } /* for */

        /* check if the packet we received is the last one */
        if (hfmi >> 4 == (hfmi & 0x0f))
            last_pkt = 1;

        /* skip the MME header */
        pkt += sizeof (MME_t);
        len -= sizeof (MME_t);

        /* copy the packet into the receive buffer */
        ret = mme_put (confirm_ctx, pkt, len, &result_len);
        if (ret != MME_SUCCESS)
        {
            close (raw);
            return ret;
        }

        pkt_cnt++;

    } while (!last_pkt);

    close (raw);
    return MME_SUCCESS;
}

/**
 * Wait for an MME request and call an user function to build and send the answer.<br>
 * As MME are level 2 and IP routing does not apply, the network interface where to listen to data packet must be selected inside
 * iface paramater. For instance : "eth0", "br0", ...<br>
 * If a received MME is fragmented, the receive process re-assemble it before delivering.<br>
 * When received MME has been processed and put into a MME context, the user function is called with the context in parameter.
 *
 * \param  ctx context to receive the MME data
 * \param  iface interface where to listen to the MME; if NULL, iface is guessed according to source
 * \param  source buffer where is provided the source MAC address of received MME
 * \param  listen_cb callback function used when MME packet is received.
 * \param  tout timeout in seconds after which listening expires.
 * \return error type (MME_SUCCESS if success)
 * \return MME_ERROR_NOT_INIT: context not initialized
 */

mme_error_t
mme_listen (mme_ctx_t *ctx, char *iface, unsigned char *source, mme_listen_cb_t listen_cb, unsigned int tout)
{
    int sock_iface, sock_lo;
    struct sockaddr_ll sll;
    struct ifreq ifr;
    MME_t *mh;
    unsigned char *pkt;
    unsigned char pkt_holder[PKTSIZE] = {0};
    fd_set fds;
    struct sockaddr_ll pkt_info;
    int last_pkt = 0;
    unsigned short hfmi;    /* fmi in host byte order */
    struct timeval timeout; /* When we should time out */
    struct timeval now;
    struct timeval waittime;
    int res;
    unsigned int len, result_len;
    int pkt_nfo_sz = sizeof (pkt_info);
    mme_error_t ret;
    int pkt_cnt = 0;            /* to indicate if we recive packets in
                                 * correct order */

    /* protect from null pointers */
    if (ctx == NULL || source == NULL)
        return MME_ERROR_GEN;
    /* check if ctx has been inititalized */
    if (ctx->status == MME_STATUS_INIT)
        return MME_ERROR_NOT_INIT;

    /*
     * --- Create the iface socket ---
     */
    if ((sock_iface = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_HPAV))) < 0)
    {
        perror ("Error creating sock_iface socket: ");
        return MME_ERROR_GEN;
    }

    memset (&sll, 0x0, sizeof (sll));
    memset (&ifr, 0x0, sizeof (ifr));

    if (NULL == iface)
    {
        strncpy (ifr.ifr_name, MME_IFACE_BRIDGE, IFNAMSIZ);
    }
    else
    {
        strncpy (ifr.ifr_name, iface, IFNAMSIZ);
    }

    /* get iface index */
    if ((ioctl (sock_iface, SIOCGIFINDEX, &ifr)) == -1)
    {
        printf ("%s: Error getting %s index\n", __FUNCTION__, iface);
        close (sock_iface);
        return MME_ERROR_GEN;
    }

    /* Bind socket to this interface */
    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons (ETH_P_HPAV);
    if ((bind (sock_iface, (struct sockaddr *)&sll, sizeof (sll)))== -1)
    {
        perror ("Error binding iface to interface: ");
        close (sock_iface);
        return MME_ERROR_GEN;
    }

    /* create loopback socket */
    if ((sock_lo = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_HPAV))) < 0)
    {
        perror ("Error creating loopback socket: ");
        close (sock_iface);
        return MME_ERROR_GEN;
    }

    memset (&sll, 0x0, sizeof (sll));
    memset (&ifr, 0x0, sizeof (ifr));

    if (NULL == iface)
    {
        /* Get the loopback Interface Index  */
        strncpy (ifr.ifr_name, MME_IFACE_LOOPBACK, IFNAMSIZ);
        /* get iface index */
        if ((ioctl (sock_lo, SIOCGIFINDEX, &ifr)) == -1)
        {
            perror ("Error getting loopback index: ");
            close (sock_iface);
            close (sock_lo);
            return MME_ERROR_GEN;
        }

        /* Bind socket to this interface */
        sll.sll_family = AF_PACKET;
        sll.sll_ifindex = ifr.ifr_ifindex;
        sll.sll_protocol = htons (ETH_P_HPAV);
        if ((bind (sock_lo, (struct sockaddr *)&sll, sizeof (sll)))== -1)
        {
            perror ("Error binding loopback socket to interface\n");
            close (sock_iface);
            close (sock_lo);
            return MME_ERROR_GEN;
        }
    }

    /* Calculate into 'timeout' when we should time out */
    gettimeofday (&timeout, 0);
    timeout.tv_sec += (tout != 0) ? tout : MME_TOUT;

    /* initialize packet counter */
    pkt_cnt = 0;

    do  /* receive the payload packages */
    {
        /* rewind pkt pointer to begining of the packet holder */
        pkt = pkt_holder;

        for(;;)  /* listen until we get package from our proper source */
        {
            /* Force timeout if we ran out of time */
            gettimeofday (&now, 0);
            if (timercmp (&now, &timeout, >) != 0)
            {
                printf ("Server indication timeout.\n");
                close (sock_iface);
                close (sock_lo);
                return MME_ERROR_TIMEOUT;
            }

            /* Calculate into 'waittime' how long to wait */
            timersub (&timeout, &now, &waittime); /* wait = timeout - now */

            /* Init fds with 'sock' as the only fd */
            FD_ZERO (&fds);
            FD_SET (sock_iface, &fds);
            if (NULL == iface)
            {
                FD_SET (sock_lo, &fds);
            }

            res = select (sock_iface + 2, &fds, NULL, NULL, &waittime);
            if (res < 0)
            {
                perror ("select() failed");
                close (sock_iface);
                close (sock_lo);
                return MME_ERROR_GEN;
            }
            else if (res == 0)  /* timeout */
            {
                printf ("Server indication timeout.\n");
                close(sock_iface);
                close(sock_lo);
                return MME_ERROR_TIMEOUT;
            }

            if (FD_ISSET (sock_iface, &fds))
            {
                if ((len = recvfrom (sock_iface, pkt, PKTSIZE, 0, (struct sockaddr*)&pkt_info, (socklen_t *)&pkt_nfo_sz) ) < 0 )
                {
                    perror ("Recv from returned error: ");
                    close (sock_iface);
                    close (sock_lo);
                    return MME_ERROR_TXRX;
                }
            }
            else
            {
                if ((len = recvfrom (sock_lo, pkt, PKTSIZE, 0, (struct sockaddr*)&pkt_info, (socklen_t *)&pkt_nfo_sz) ) < 0 )
                {
                    perror ("Recv from loopback returned error: ");
                    close (sock_iface);
                    close (sock_lo);
                    return MME_ERROR_TXRX;
                }
            }

            mh =  (MME_t *)pkt;
            hfmi = mh->fmi;

            /* check if indication came from the good source, and if it is,
             * check if cooresponds to our prepared response (REQ/CNF or IND/RSP);
             * by HP AV standard difference is in LSB, i.e. if REQ LSBs are ...00,
             * CNF will be ...01, IND ...10 and RSP ...11
             * REQ is always CNF - 1, IND is RSP - 1 */
            if (memcmp (pkt_info.sll_addr, source, ETH_ALEN) == 0  &&      /* we received packet from correct source */
                (mh->mmtype == ctx->mmtype) &&                     /* waited MME type */
                hfmi >> 4 == pkt_cnt)                              /* packets are coming in the right order */
            {
                break;  /* good answer - go out and process the package */
            }
        } /* for */

        /* check if the packet we received is the last one */
        if (hfmi >> 4 == (hfmi & 0x0f))
            last_pkt = 1;

        /* skip the MME header */
        pkt += sizeof (MME_t);
        len -= sizeof (MME_t);

        /* copy the packet into the receive buffer */
        ret = mme_put (ctx, pkt, len, &result_len);
        if (ret != MME_SUCCESS)
        {
            close (sock_iface);
            close (sock_lo);
            return ret;
        }

        pkt_cnt++;

    } while (!last_pkt);

    /* and now whe we assembled the message, call the processing function */
    if (listen_cb != NULL)
    {
        ret = listen_cb (ctx, iface, source);
        if (ret != MME_SUCCESS)
        {
            close (sock_iface);
            close (sock_lo);
            return ret;
        }
    }

    close (sock_iface);
    close (sock_lo);
    return MME_SUCCESS;
}