lsquic_version.c revision 10c492f0
1/* Copyright (c) 2017 - 2018 LiteSpeed Technologies Inc.  See LICENSE. */
2#include <string.h>
3
4#include "lsquic.h"
5#include "lsquic_int_types.h"
6#include "lsquic_version.h"
7
8
9static const unsigned char version_tags[N_LSQVER][4] =
10{
11    [LSQVER_035] = { 'Q', '0', '3', '5', },
12    [LSQVER_037] = { 'Q', '0', '3', '7', },
13    [LSQVER_038] = { 'Q', '0', '3', '8', },
14    [LSQVER_039] = { 'Q', '0', '3', '9', },
15    [LSQVER_041] = { 'Q', '0', '4', '1', },
16};
17
18
19uint32_t
20lsquic_ver2tag (unsigned version)
21{
22    lsquic_ver_tag_t tag;
23    if (version < N_LSQVER)
24    {
25        memcpy(&tag, version_tags[version], 4);
26        return tag;
27    }
28    else
29        return 0;
30}
31
32
33enum lsquic_version
34lsquic_tag2ver (uint32_t ver_tag)
35{
36    unsigned n;
37    for (n = 0; n < sizeof(version_tags) / sizeof(version_tags[0]); ++n)
38        if (0 == memcmp(version_tags[n], &ver_tag, sizeof(ver_tag)))
39            return n;
40    return -1;
41}
42
43
44enum lsquic_version
45lsquic_str2ver (const char *str, size_t len)
46{
47    uint32_t tag;
48
49    if (len == sizeof(tag) && 'Q' == str[0])
50    {
51        memcpy(&tag, str, sizeof(tag));
52        return lsquic_tag2ver(tag);
53    }
54    else
55        return -1;
56}
57
58
59const char *const lsquic_ver2str[N_LSQVER] = {
60    [LSQVER_035] = "Q035",
61    [LSQVER_037] = "Q037",
62    [LSQVER_038] = "Q038",
63    [LSQVER_039] = "Q039",
64    [LSQVER_041] = "Q041",
65};
66
67
68int
69gen_ver_tags (unsigned char *buf, size_t bufsz, unsigned version_bitmask)
70{
71    unsigned n;
72    lsquic_ver_tag_t tag;
73    unsigned char *p = buf;
74    unsigned char *const pend = p + bufsz;
75    for (n = 0; version_bitmask; ++n)
76    {
77        if (version_bitmask & (1 << n))
78        {
79            if (p + 4 > pend)
80                return -1;
81            version_bitmask &= ~(1 << n);
82            tag = lsquic_ver2tag(n);
83            if (0 == tag)
84                return -1;
85            memcpy(p, &tag, 4);
86            p += 4;
87        }
88    }
89    return p - buf;
90}
91