softwarecontainer  0.18.0-739e8d7 2017-05-04
networkgatewayfunctions.cpp
1 /*
2  * Copyright (C) 2017 Pelagicore AB
3  *
4  * Permission to use, copy, modify, and/or distribute this software for
5  * any purpose with or without fee is hereby granted, provided that the
6  * above copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
9  * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
10  * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
11  * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
12  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
13  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
14  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15  * SOFTWARE.
16  *
17  * For further information see LICENSE
18  */
19 
20 #include <arpa/inet.h>
21 
22 #include "gateway/gateway.h"
23 #include "networkgatewayfunctions.h"
24 #include "networkgateway.h"
25 
26 namespace softwarecontainer {
27 
28 uint32_t NetworkGatewayFunctions::generateIP(const uint32_t netmask,
29  const std::string gatewayIP,
30  const int32_t containerID)
31 {
32  log_debug() << "Generating ip-address";
33  // IP generation is designed for Ipv4 in case of transition to IPv6 it should be revised
34  uint32_t internetAddress;
35 
36  /*
37  * Netmask is used for determining range of IP address assignment. maskBits variable represents
38  * bit-count for creating IP range starting from least significant bit of m_gateway. Since an
39  * ipv4 address consist of 32 bits, maskBits shall not be greater than 32. Since bit 0 and
40  * bit 31 cannot give a range but a single exact value, those will not be accepted as a maskBits.
41  */
42  if (netmask > 31 || netmask < 1) {
43  throw IPAllocationError("inappropriate netmask : " + netmask);
44  }
45 
46  // value of m_netmask interprets maskBits to a mask integer to calculate range.
47  uint32_t maskBits = (1L << (32 - netmask)) - 1;
48 
49  if ( 1 != inet_pton(AF_INET, gatewayIP.c_str(), &internetAddress)) {
50  throw IPAllocationError(gatewayIP + " does not represent a valid network address");
51  }
52  internetAddress = ntohl(internetAddress);
53 
54  //Check if generated IP address is in range of available IP addresses
55  if ((internetAddress | maskBits) < (internetAddress + containerID + 1)) {
56  throw IPAllocationError("There is no suitable IP address for this container.");
57  }
58 
59  //IP address is generated by adding 1 to container ID for provide uniqueness
60  internetAddress += (containerID + 1);
61  internetAddress = htonl(internetAddress);
62  return internetAddress;
63 }
64 
65 
66 } // namespace softwarecontainer
uint32_t generateIP(const uint32_t netmask, const std::string gatewayIP, const int32_t containerID)
Generate IP address for the container.
Developers guide to adding a config item: