mysql_lease_mgr.cc 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. // Copyright (C) 2012-2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp/duid.h>
  17. #include <dhcp/hwaddr.h>
  18. #include <dhcpsrv/dhcpsrv_log.h>
  19. #include <dhcpsrv/mysql_lease_mgr.h>
  20. #include <boost/static_assert.hpp>
  21. #include <mysqld_error.h>
  22. #include <iostream>
  23. #include <iomanip>
  24. #include <sstream>
  25. #include <string>
  26. #include <time.h>
  27. using namespace isc;
  28. using namespace isc::dhcp;
  29. using namespace std;
  30. /// @file
  31. ///
  32. /// This file holds the implementation of the Lease Manager using MySQL. The
  33. /// implementation uses MySQL's C API, as it comes as standard with the MySQL
  34. /// client libraries.
  35. ///
  36. /// In general, each of the database access methods corresponds to one SQL
  37. /// statement. To avoid the overhead of parsing a statement every time it is
  38. /// used, when the database is opened "prepared statements" are created -
  39. /// essentially doing the SQL parsing up front. Every time a method is used
  40. /// to access data, the corresponding prepared statement is referenced. Each
  41. /// prepared statement contains a set of placeholders for data, each
  42. /// placeholder being for:
  43. ///
  44. /// - data being added to the database (as in adding or updating a lease)
  45. /// - data being retrieved from the database (as in getting lease information)
  46. /// - selection criteria used to determine which records to update/retrieve.
  47. ///
  48. /// All such data is associated with the prepared statment using an array of
  49. /// MYSQL_BIND structures. Each element in the array corresponds to one
  50. /// parameter in the prepared statement - the first element in the array is
  51. /// associated with the first parameter, the second element with the second
  52. /// parameter etc.
  53. ///
  54. /// Within this file, the setting up of the MYSQL_BIND arrays for data being
  55. /// passed to and retrieved from the database is handled in the
  56. /// isc::dhcp::MySqlLease4Exchange and isc::dhcp::MySqlLease6Exchange classes.
  57. /// The classes also hold intermediate variables required for exchanging some
  58. /// of the data.
  59. ///
  60. /// With these exchange objects in place, many of the methods follow similar
  61. /// logic:
  62. /// - Set up the MYSQL_BIND array for data being transferred to/from the
  63. /// database. For data being transferred to the database, some of the
  64. /// data is extracted from the lease to intermediate variables, whilst
  65. /// in other cases the MYSQL_BIND arrays point to the data in the lease.
  66. /// - Set up the MYSQL_BIND array for the data selection parameters.
  67. /// - Bind these arrays to the prepared statement.
  68. /// - Execute the statement.
  69. /// - If there is output, copy the data from the bound variables to the output
  70. /// lease object.
  71. namespace {
  72. ///@{
  73. /// @brief Maximum size of database fields
  74. ///
  75. /// The following constants define buffer sizes for variable length database
  76. /// fields. The values should be greater than or equal to the length set in
  77. /// the schema definition.
  78. ///
  79. /// The exception is the length of any VARCHAR fields: buffers for these should
  80. /// be set greater than or equal to the length of the field plus 1: this allows
  81. /// for the insertion of a trailing null whatever data is returned.
  82. /// @brief Maximum size of an IPv6 address represented as a text string.
  83. ///
  84. /// This is 32 hexadecimal characters written in 8 groups of four, plus seven
  85. /// colon separators.
  86. const size_t ADDRESS6_TEXT_MAX_LEN = 39;
  87. /// @brief MySQL True/False constants
  88. ///
  89. /// Declare typed values so as to avoid problems of data conversion. These
  90. /// are local to the file but are given the prefix MLM (MySql Lease Manager) to
  91. /// avoid any likely conflicts with variables in header files named TRUE or
  92. /// FALSE.
  93. const my_bool MLM_FALSE = 0; ///< False value
  94. const my_bool MLM_TRUE = 1; ///< True value
  95. /// @brief Maximum length of the hostname stored in DNS.
  96. ///
  97. /// This length is restricted by the length of the domain-name carried
  98. /// in the Client FQDN %Option (see RFC4702 and RFC4704).
  99. const size_t HOSTNAME_MAX_LEN = 255;
  100. ///@}
  101. /// @brief MySQL Selection Statements
  102. ///
  103. /// Each statement is associated with an index, which is used to reference the
  104. /// associated prepared statement.
  105. struct TaggedStatement {
  106. MySqlLeaseMgr::StatementIndex index;
  107. const char* text;
  108. };
  109. TaggedStatement tagged_statements[] = {
  110. {MySqlLeaseMgr::DELETE_LEASE4,
  111. "DELETE FROM lease4 WHERE address = ?"},
  112. {MySqlLeaseMgr::DELETE_LEASE6,
  113. "DELETE FROM lease6 WHERE address = ?"},
  114. {MySqlLeaseMgr::GET_LEASE4_ADDR,
  115. "SELECT address, hwaddr, client_id, "
  116. "valid_lifetime, expire, subnet_id, "
  117. "fqdn_fwd, fqdn_rev, hostname "
  118. "FROM lease4 "
  119. "WHERE address = ?"},
  120. {MySqlLeaseMgr::GET_LEASE4_CLIENTID,
  121. "SELECT address, hwaddr, client_id, "
  122. "valid_lifetime, expire, subnet_id, "
  123. "fqdn_fwd, fqdn_rev, hostname "
  124. "FROM lease4 "
  125. "WHERE client_id = ?"},
  126. {MySqlLeaseMgr::GET_LEASE4_CLIENTID_SUBID,
  127. "SELECT address, hwaddr, client_id, "
  128. "valid_lifetime, expire, subnet_id, "
  129. "fqdn_fwd, fqdn_rev, hostname "
  130. "FROM lease4 "
  131. "WHERE client_id = ? AND subnet_id = ?"},
  132. {MySqlLeaseMgr::GET_LEASE4_HWADDR,
  133. "SELECT address, hwaddr, client_id, "
  134. "valid_lifetime, expire, subnet_id, "
  135. "fqdn_fwd, fqdn_rev, hostname "
  136. "FROM lease4 "
  137. "WHERE hwaddr = ?"},
  138. {MySqlLeaseMgr::GET_LEASE4_HWADDR_SUBID,
  139. "SELECT address, hwaddr, client_id, "
  140. "valid_lifetime, expire, subnet_id, "
  141. "fqdn_fwd, fqdn_rev, hostname "
  142. "FROM lease4 "
  143. "WHERE hwaddr = ? AND subnet_id = ?"},
  144. {MySqlLeaseMgr::GET_LEASE6_ADDR,
  145. "SELECT address, duid, valid_lifetime, "
  146. "expire, subnet_id, pref_lifetime, "
  147. "lease_type, iaid, prefix_len, "
  148. "fqdn_fwd, fqdn_rev, hostname "
  149. "FROM lease6 "
  150. "WHERE address = ? AND lease_type = ?"},
  151. {MySqlLeaseMgr::GET_LEASE6_DUID_IAID,
  152. "SELECT address, duid, valid_lifetime, "
  153. "expire, subnet_id, pref_lifetime, "
  154. "lease_type, iaid, prefix_len, "
  155. "fqdn_fwd, fqdn_rev, hostname "
  156. "FROM lease6 "
  157. "WHERE duid = ? AND iaid = ? AND lease_type = ?"},
  158. {MySqlLeaseMgr::GET_LEASE6_DUID_IAID_SUBID,
  159. "SELECT address, duid, valid_lifetime, "
  160. "expire, subnet_id, pref_lifetime, "
  161. "lease_type, iaid, prefix_len, "
  162. "fqdn_fwd, fqdn_rev, hostname "
  163. "FROM lease6 "
  164. "WHERE duid = ? AND iaid = ? AND subnet_id = ? "
  165. "AND lease_type = ?"},
  166. {MySqlLeaseMgr::GET_VERSION,
  167. "SELECT version, minor FROM schema_version"},
  168. {MySqlLeaseMgr::INSERT_LEASE4,
  169. "INSERT INTO lease4(address, hwaddr, client_id, "
  170. "valid_lifetime, expire, subnet_id, "
  171. "fqdn_fwd, fqdn_rev, hostname) "
  172. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"},
  173. {MySqlLeaseMgr::INSERT_LEASE6,
  174. "INSERT INTO lease6(address, duid, valid_lifetime, "
  175. "expire, subnet_id, pref_lifetime, "
  176. "lease_type, iaid, prefix_len, "
  177. "fqdn_fwd, fqdn_rev, hostname) "
  178. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"},
  179. {MySqlLeaseMgr::UPDATE_LEASE4,
  180. "UPDATE lease4 SET address = ?, hwaddr = ?, "
  181. "client_id = ?, valid_lifetime = ?, expire = ?, "
  182. "subnet_id = ?, fqdn_fwd = ?, fqdn_rev = ?, "
  183. "hostname = ? "
  184. "WHERE address = ?"},
  185. {MySqlLeaseMgr::UPDATE_LEASE6,
  186. "UPDATE lease6 SET address = ?, duid = ?, "
  187. "valid_lifetime = ?, expire = ?, subnet_id = ?, "
  188. "pref_lifetime = ?, lease_type = ?, iaid = ?, "
  189. "prefix_len = ?, fqdn_fwd = ?, fqdn_rev = ?, "
  190. "hostname = ? "
  191. "WHERE address = ?"},
  192. // End of list sentinel
  193. {MySqlLeaseMgr::NUM_STATEMENTS, NULL}
  194. };
  195. }; // Anonymous namespace
  196. namespace isc {
  197. namespace dhcp {
  198. /// @brief Common MySQL and Lease Data Methods
  199. ///
  200. /// The MySqlLease4Exchange and MySqlLease6Exchange classes provide the
  201. /// functionaility to set up binding information between variables in the
  202. /// program and data extracted from the database. This class is the common
  203. /// base to both of them, containing some common methods.
  204. class MySqlLeaseExchange {
  205. public:
  206. /// @brief Set error indicators
  207. ///
  208. /// Sets the error indicator for each of the MYSQL_BIND elements. It points
  209. /// the "error" field within an element of the input array to the
  210. /// corresponding element of the passed error array.
  211. ///
  212. /// @param bind Array of BIND elements
  213. /// @param error Array of error elements. If there is an error in getting
  214. /// data associated with one of the "bind" elements, the
  215. /// corresponding element in the error array is set to MLM_TRUE.
  216. /// @param count Size of each of the arrays.
  217. void setErrorIndicators(MYSQL_BIND* bind, my_bool* error, size_t count) {
  218. for (size_t i = 0; i < count; ++i) {
  219. error[i] = MLM_FALSE;
  220. bind[i].error = reinterpret_cast<char*>(&error[i]);
  221. }
  222. }
  223. /// @brief Return columns in error
  224. ///
  225. /// If an error is returned from a fetch (in particular, a truncated
  226. /// status), this method can be called to get the names of the fields in
  227. /// error. It returns a string comprising the names of the fields
  228. /// separated by commas. In the case of there being no error indicators
  229. /// set, it returns the string "(None)".
  230. ///
  231. /// @param error Array of error elements. An element is set to MLM_TRUE
  232. /// if the corresponding column in the database is the source of
  233. /// the error.
  234. /// @param names Array of column names, the same size as the error array.
  235. /// @param count Size of each of the arrays.
  236. std::string getColumnsInError(my_bool* error, std::string* names,
  237. size_t count) {
  238. std::string result = "";
  239. // Accumulate list of column names
  240. for (size_t i = 0; i < count; ++i) {
  241. if (error[i] == MLM_TRUE) {
  242. if (!result.empty()) {
  243. result += ", ";
  244. }
  245. result += names[i];
  246. }
  247. }
  248. if (result.empty()) {
  249. result = "(None)";
  250. }
  251. return (result);
  252. }
  253. };
  254. /// @brief Exchange MySQL and Lease4 Data
  255. ///
  256. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  257. /// describe the parameters in the prepared statements. Where information is
  258. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  259. /// structure is identical. This class handles the creation of that array.
  260. ///
  261. /// Owing to the MySQL API, the process requires some intermediate variables
  262. /// to hold things like data length etc. This object holds those variables.
  263. ///
  264. /// @note There are no unit tests for this class. It is tested indirectly
  265. /// in all MySqlLeaseMgr::xxx4() calls where it is used.
  266. class MySqlLease4Exchange : public MySqlLeaseExchange {
  267. /// @brief Set number of database columns for this lease structure
  268. static const size_t LEASE_COLUMNS = 9;
  269. public:
  270. /// @brief Constructor
  271. ///
  272. /// The initialization of the variables here is only to satisfy cppcheck -
  273. /// all variables are initialized/set in the methods before they are used.
  274. MySqlLease4Exchange() : addr4_(0), hwaddr_length_(0), client_id_length_(0),
  275. fqdn_fwd_(false), fqdn_rev_(false), hostname_length_(0) {
  276. memset(hwaddr_buffer_, 0, sizeof(hwaddr_buffer_));
  277. memset(client_id_buffer_, 0, sizeof(client_id_buffer_));
  278. memset(hostname_buffer_, 0, sizeof(hostname_buffer_));
  279. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  280. // Set the column names (for error messages)
  281. columns_[0] = "address";
  282. columns_[1] = "hwaddr";
  283. columns_[2] = "client_id";
  284. columns_[3] = "valid_lifetime";
  285. columns_[4] = "expire";
  286. columns_[5] = "subnet_id";
  287. columns_[6] = "fqdn_fwd";
  288. columns_[7] = "fqdn_rev";
  289. columns_[8] = "hostname";
  290. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  291. }
  292. /// @brief Create MYSQL_BIND objects for Lease4 Pointer
  293. ///
  294. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  295. /// the database.
  296. ///
  297. /// @param lease Lease object to be added to the database. None of the
  298. /// fields in the lease are modified - the lease data is only read.
  299. ///
  300. /// @return Vector of MySQL BIND objects representing the data to be added.
  301. std::vector<MYSQL_BIND> createBindForSend(const Lease4Ptr& lease) {
  302. // Store lease object to ensure it remains valid.
  303. lease_ = lease;
  304. // Initialize prior to constructing the array of MYSQL_BIND structures.
  305. // It sets all fields, including is_null, to zero, so we need to set
  306. // is_null only if it should be true. This gives up minor performance
  307. // benefit while being safe approach. For improved readability, the
  308. // code that explicitly sets is_null is there, but is commented out.
  309. memset(bind_, 0, sizeof(bind_));
  310. // Set up the structures for the various components of the lease4
  311. // structure.
  312. // Address: uint32_t
  313. // The address in the Lease structure is an IOAddress object. Convert
  314. // this to an integer for storage.
  315. addr4_ = static_cast<uint32_t>(lease_->addr_);
  316. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  317. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  318. bind_[0].is_unsigned = MLM_TRUE;
  319. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  320. // reasons, see memset() above
  321. // hwaddr: varbinary(128)
  322. // For speed, we avoid copying the data into temporary storage and
  323. // instead extract it from the lease structure directly.
  324. hwaddr_length_ = lease_->hwaddr_.size();
  325. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  326. bind_[1].buffer = reinterpret_cast<char*>(&(lease_->hwaddr_[0]));
  327. bind_[1].buffer_length = hwaddr_length_;
  328. bind_[1].length = &hwaddr_length_;
  329. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  330. // reasons, see memset() above
  331. // client_id: varbinary(128)
  332. if (lease_->client_id_) {
  333. client_id_ = lease_->client_id_->getClientId();
  334. client_id_length_ = client_id_.size();
  335. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  336. bind_[2].buffer = reinterpret_cast<char*>(&client_id_[0]);
  337. bind_[2].buffer_length = client_id_length_;
  338. bind_[2].length = &client_id_length_;
  339. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  340. // reasons, see memset() above
  341. } else {
  342. bind_[2].buffer_type = MYSQL_TYPE_NULL;
  343. // According to http://dev.mysql.com/doc/refman/5.5/en/
  344. // c-api-prepared-statement-data-structures.html, the other
  345. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  346. // but let's set them to some sane values in case earlier versions
  347. // didn't have that assumption.
  348. client_id_null_ = MLM_TRUE;
  349. bind_[2].buffer = NULL;
  350. bind_[2].is_null = &client_id_null_;
  351. }
  352. // valid lifetime: unsigned int
  353. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  354. bind_[3].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  355. bind_[3].is_unsigned = MLM_TRUE;
  356. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  357. // reasons, see memset() above
  358. // expire: timestamp
  359. // The lease structure holds the client last transmission time (cltt_)
  360. // For convenience for external tools, this is converted to lease
  361. // expiry time (expire). The relationship is given by:
  362. //
  363. // expire = cltt_ + valid_lft_
  364. //
  365. // @todo Handle overflows - a large enough valid_lft_ could cause
  366. // an overflow on a 32-bit system.
  367. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  368. expire_);
  369. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  370. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  371. bind_[4].buffer_length = sizeof(expire_);
  372. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  373. // reasons, see memset() above
  374. // subnet_id: unsigned int
  375. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  376. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  377. bind_[5].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  378. bind_[5].is_unsigned = MLM_TRUE;
  379. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  380. // reasons, see memset() above
  381. // fqdn_fwd: boolean
  382. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  383. bind_[6].buffer = reinterpret_cast<char*>(&lease_->fqdn_fwd_);
  384. bind_[6].is_unsigned = MLM_TRUE;
  385. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  386. // reasons, see memset() above
  387. // fqdn_rev: boolean
  388. bind_[7].buffer_type = MYSQL_TYPE_TINY;
  389. bind_[7].buffer = reinterpret_cast<char*>(&lease_->fqdn_rev_);
  390. bind_[7].is_unsigned = MLM_TRUE;
  391. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  392. // reasons, see memset() above
  393. // hostname: varchar(255)
  394. bind_[8].buffer_type = MYSQL_TYPE_VARCHAR;
  395. bind_[8].buffer = const_cast<char*>(lease_->hostname_.c_str());
  396. bind_[8].buffer_length = lease_->hostname_.length();
  397. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  398. // reasons, see memset() above
  399. // Add the error flags
  400. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  401. // .. and check that we have the numbers correct at compile time.
  402. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  403. // Add the data to the vector. Note the end element is one after the
  404. // end of the array.
  405. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  406. }
  407. /// @brief Create BIND array to receive data
  408. ///
  409. /// Creates a MYSQL_BIND array to receive Lease4 data from the database.
  410. /// After data is successfully received, getLeaseData() can be used to copy
  411. /// it to a Lease6 object.
  412. ///
  413. std::vector<MYSQL_BIND> createBindForReceive() {
  414. // Initialize MYSQL_BIND array.
  415. // It sets all fields, including is_null, to zero, so we need to set
  416. // is_null only if it should be true. This gives up minor performance
  417. // benefit while being safe approach. For improved readability, the
  418. // code that explicitly sets is_null is there, but is commented out.
  419. memset(bind_, 0, sizeof(bind_));
  420. // address: uint32_t
  421. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  422. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  423. bind_[0].is_unsigned = MLM_TRUE;
  424. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  425. // reasons, see memset() above
  426. // hwaddr: varbinary(20)
  427. hwaddr_length_ = sizeof(hwaddr_buffer_);
  428. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  429. bind_[1].buffer = reinterpret_cast<char*>(hwaddr_buffer_);
  430. bind_[1].buffer_length = hwaddr_length_;
  431. bind_[1].length = &hwaddr_length_;
  432. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  433. // reasons, see memset() above
  434. // client_id: varbinary(128)
  435. client_id_length_ = sizeof(client_id_buffer_);
  436. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  437. bind_[2].buffer = reinterpret_cast<char*>(client_id_buffer_);
  438. bind_[2].buffer_length = client_id_length_;
  439. bind_[2].length = &client_id_length_;
  440. bind_[2].is_null = &client_id_null_;
  441. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  442. // reasons, see memset() above
  443. // lease_time: unsigned int
  444. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  445. bind_[3].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  446. bind_[3].is_unsigned = MLM_TRUE;
  447. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  448. // reasons, see memset() above
  449. // expire: timestamp
  450. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  451. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  452. bind_[4].buffer_length = sizeof(expire_);
  453. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  454. // reasons, see memset() above
  455. // subnet_id: unsigned int
  456. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  457. bind_[5].buffer = reinterpret_cast<char*>(&subnet_id_);
  458. bind_[5].is_unsigned = MLM_TRUE;
  459. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  460. // reasons, see memset() above
  461. // fqdn_fwd: boolean
  462. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  463. bind_[6].buffer = reinterpret_cast<char*>(&fqdn_fwd_);
  464. bind_[6].is_unsigned = MLM_TRUE;
  465. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  466. // reasons, see memset() above
  467. // fqdn_rev: boolean
  468. bind_[7].buffer_type = MYSQL_TYPE_TINY;
  469. bind_[7].buffer = reinterpret_cast<char*>(&fqdn_rev_);
  470. bind_[7].is_unsigned = MLM_TRUE;
  471. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  472. // reasons, see memset() above
  473. // hostname: varchar(255)
  474. hostname_length_ = sizeof(hostname_buffer_);
  475. bind_[8].buffer_type = MYSQL_TYPE_STRING;
  476. bind_[8].buffer = reinterpret_cast<char*>(hostname_buffer_);
  477. bind_[8].buffer_length = hostname_length_;
  478. bind_[8].length = &hostname_length_;
  479. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  480. // reasons, see memset() above
  481. // Add the error flags
  482. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  483. // .. and check that we have the numbers correct at compile time.
  484. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  485. // Add the data to the vector. Note the end element is one after the
  486. // end of the array.
  487. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  488. }
  489. /// @brief Copy Received Data into Lease6 Object
  490. ///
  491. /// Called after the MYSQL_BIND array created by createBindForReceive()
  492. /// has been used, this copies data from the internal member variables
  493. /// into a Lease4 objec.
  494. ///
  495. /// @return Lease4Ptr Pointer to a Lease6 object holding the relevant
  496. /// data.
  497. Lease4Ptr getLeaseData() {
  498. // Convert times received from the database to times for the lease
  499. // structure
  500. time_t cltt = 0;
  501. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  502. if (client_id_null_==MLM_TRUE) {
  503. // There's no client-id, so we pass client-id_length_ set to 0
  504. client_id_length_ = 0;
  505. }
  506. // Hostname is passed to Lease4 as a string object. We have to create
  507. // it from the buffer holding hostname and the buffer length.
  508. std::string hostname(hostname_buffer_,
  509. hostname_buffer_ + hostname_length_);
  510. // note that T1 and T2 are not stored
  511. return (Lease4Ptr(new Lease4(addr4_, hwaddr_buffer_, hwaddr_length_,
  512. client_id_buffer_, client_id_length_,
  513. valid_lifetime_, 0, 0, cltt, subnet_id_,
  514. fqdn_fwd_, fqdn_rev_, hostname)));
  515. }
  516. /// @brief Return columns in error
  517. ///
  518. /// If an error is returned from a fetch (in particular, a truncated
  519. /// status), this method can be called to get the names of the fields in
  520. /// error. It returns a string comprising the names of the fields
  521. /// separated by commas. In the case of there being no error indicators
  522. /// set, it returns the string "(None)".
  523. ///
  524. /// @return Comma-separated list of columns in error, or the string
  525. /// "(None)".
  526. std::string getErrorColumns() {
  527. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  528. }
  529. private:
  530. // Note: All array lengths are equal to the corresponding variable in the
  531. // schema.
  532. // Note: Arrays are declared fixed length for speed of creation
  533. uint32_t addr4_; ///< IPv4 address
  534. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  535. std::string columns_[LEASE_COLUMNS];///< Column names
  536. my_bool error_[LEASE_COLUMNS]; ///< Error array
  537. std::vector<uint8_t> hwaddr_; ///< Hardware address
  538. uint8_t hwaddr_buffer_[HWAddr::MAX_HWADDR_LEN];
  539. ///< Hardware address buffer
  540. unsigned long hwaddr_length_; ///< Hardware address length
  541. std::vector<uint8_t> client_id_; ///< Client identification
  542. uint8_t client_id_buffer_[ClientId::MAX_CLIENT_ID_LEN];
  543. ///< Client ID buffer
  544. unsigned long client_id_length_; ///< Client ID address length
  545. my_bool client_id_null_; ///< Is Client ID null?
  546. MYSQL_TIME expire_; ///< Lease expiry time
  547. Lease4Ptr lease_; ///< Pointer to lease object
  548. uint32_t subnet_id_; ///< Subnet identification
  549. uint32_t valid_lifetime_; ///< Lease time
  550. my_bool fqdn_fwd_; ///< Has forward DNS update been
  551. ///< performed
  552. my_bool fqdn_rev_; ///< Has reverse DNS update been
  553. ///< performed
  554. char hostname_buffer_[HOSTNAME_MAX_LEN];
  555. ///< Client hostname
  556. unsigned long hostname_length_; ///< Client hostname length
  557. };
  558. /// @brief Exchange MySQL and Lease6 Data
  559. ///
  560. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  561. /// describe the parameters in the prepared statements. Where information is
  562. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  563. /// structure is identical. This class handles the creation of that array.
  564. ///
  565. /// Owing to the MySQL API, the process requires some intermediate variables
  566. /// to hold things like data length etc. This object holds those variables.
  567. ///
  568. /// @note There are no unit tests for this class. It is tested indirectly
  569. /// in all MySqlLeaseMgr::xxx6() calls where it is used.
  570. class MySqlLease6Exchange : public MySqlLeaseExchange {
  571. /// @brief Set number of database columns for this lease structure
  572. static const size_t LEASE_COLUMNS = 12;
  573. public:
  574. /// @brief Constructor
  575. ///
  576. /// The initialization of the variables here is nonly to satisfy cppcheck -
  577. /// all variables are initialized/set in the methods before they are used.
  578. MySqlLease6Exchange() : addr6_length_(0), duid_length_(0),
  579. fqdn_fwd_(false), fqdn_rev_(false),
  580. hostname_length_(0) {
  581. memset(addr6_buffer_, 0, sizeof(addr6_buffer_));
  582. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  583. memset(hostname_buffer_, 0, sizeof(hostname_buffer_));
  584. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  585. // Set the column names (for error messages)
  586. columns_[0] = "address";
  587. columns_[1] = "duid";
  588. columns_[2] = "valid_lifetime";
  589. columns_[3] = "expire";
  590. columns_[4] = "subnet_id";
  591. columns_[5] = "pref_lifetime";
  592. columns_[6] = "lease_type";
  593. columns_[7] = "iaid";
  594. columns_[8] = "prefix_len";
  595. columns_[9] = "fqdn_fwd";
  596. columns_[10] = "fqdn_rev";
  597. columns_[11] = "hostname";
  598. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  599. }
  600. /// @brief Create MYSQL_BIND objects for Lease6 Pointer
  601. ///
  602. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  603. /// the database.
  604. ///
  605. /// @param lease Lease object to be added to the database.
  606. ///
  607. /// @return Vector of MySQL BIND objects representing the data to be added.
  608. std::vector<MYSQL_BIND> createBindForSend(const Lease6Ptr& lease) {
  609. // Store lease object to ensure it remains valid.
  610. lease_ = lease;
  611. // Ensure bind_ array clear for constructing the MYSQL_BIND structures
  612. // for this lease.
  613. // It sets all fields, including is_null, to zero, so we need to set
  614. // is_null only if it should be true. This gives up minor performance
  615. // benefit while being safe approach. For improved readability, the
  616. // code that explicitly sets is_null is there, but is commented out.
  617. memset(bind_, 0, sizeof(bind_));
  618. // address: varchar(39)
  619. addr6_ = lease_->addr_.toText();
  620. addr6_length_ = addr6_.size();
  621. // In the following statement, the string is being read. However, the
  622. // MySQL C interface does not use "const", so the "buffer" element
  623. // is declared as "char*" instead of "const char*". To resolve this,
  624. // the "const" is discarded. (Note that the address of addr6_.c_str()
  625. // is guaranteed to be valid until the next non-const operation on
  626. // addr6_.)
  627. //
  628. // The const_cast could be avoided by copying the string to a writeable
  629. // buffer and storing the address of that in the "buffer" element.
  630. // However, this introduces a copy operation (with additional overhead)
  631. // purely to get round the structures introduced by design of the
  632. // MySQL interface (which uses the area pointed to by "buffer" as input
  633. // when specifying query parameters and as output when retrieving data).
  634. // For that reason, "const_cast" has been used.
  635. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  636. bind_[0].buffer = const_cast<char*>(addr6_.c_str());
  637. bind_[0].buffer_length = addr6_length_;
  638. bind_[0].length = &addr6_length_;
  639. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  640. // reasons, see memset() above
  641. // duid: varchar(128)
  642. duid_ = lease_->duid_->getDuid();
  643. duid_length_ = duid_.size();
  644. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  645. bind_[1].buffer = reinterpret_cast<char*>(&(duid_[0]));
  646. bind_[1].buffer_length = duid_length_;
  647. bind_[1].length = &duid_length_;
  648. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  649. // reasons, see memset() above
  650. // valid lifetime: unsigned int
  651. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  652. bind_[2].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  653. bind_[2].is_unsigned = MLM_TRUE;
  654. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  655. // reasons, see memset() above
  656. // expire: timestamp
  657. // The lease structure holds the client last transmission time (cltt_)
  658. // For convenience for external tools, this is converted to lease
  659. /// expiry time (expire). The relationship is given by:
  660. //
  661. // expire = cltt_ + valid_lft_
  662. //
  663. // @todo Handle overflows
  664. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  665. expire_);
  666. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  667. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  668. bind_[3].buffer_length = sizeof(expire_);
  669. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  670. // reasons, see memset() above
  671. // subnet_id: unsigned int
  672. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  673. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  674. bind_[4].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  675. bind_[4].is_unsigned = MLM_TRUE;
  676. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  677. // reasons, see memset() above
  678. // pref_lifetime: unsigned int
  679. // Can use lease_->preferred_lft_ directly as it is of type uint32_t.
  680. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  681. bind_[5].buffer = reinterpret_cast<char*>(&lease_->preferred_lft_);
  682. bind_[5].is_unsigned = MLM_TRUE;
  683. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  684. // reasons, see memset() above
  685. // lease_type: tinyint
  686. // Must convert to uint8_t as lease_->type_ is a LeaseType variable.
  687. lease_type_ = lease_->type_;
  688. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  689. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  690. bind_[6].is_unsigned = MLM_TRUE;
  691. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  692. // reasons, see memset() above
  693. // iaid: unsigned int
  694. // Can use lease_->iaid_ directly as it is of type uint32_t.
  695. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  696. bind_[7].buffer = reinterpret_cast<char*>(&lease_->iaid_);
  697. bind_[7].is_unsigned = MLM_TRUE;
  698. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  699. // reasons, see memset() above
  700. // prefix_len: unsigned tinyint
  701. // Can use lease_->prefixlen_ directly as it is uint32_t.
  702. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  703. bind_[8].buffer = reinterpret_cast<char*>(&lease_->prefixlen_);
  704. bind_[8].is_unsigned = MLM_TRUE;
  705. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  706. // reasons, see memset() above
  707. // fqdn_fwd: boolean
  708. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  709. bind_[9].buffer = reinterpret_cast<char*>(&lease_->fqdn_fwd_);
  710. bind_[9].is_unsigned = MLM_TRUE;
  711. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  712. // reasons, see memset() above
  713. // fqdn_rev: boolean
  714. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  715. bind_[10].buffer = reinterpret_cast<char*>(&lease_->fqdn_rev_);
  716. bind_[10].is_unsigned = MLM_TRUE;
  717. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  718. // reasons, see memset() above
  719. // hostname: varchar(255)
  720. bind_[11].buffer_type = MYSQL_TYPE_VARCHAR;
  721. bind_[11].buffer = const_cast<char*>(lease_->hostname_.c_str());
  722. bind_[11].buffer_length = lease_->hostname_.length();
  723. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  724. // reasons, see memset() above
  725. // Add the error flags
  726. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  727. // .. and check that we have the numbers correct at compile time.
  728. BOOST_STATIC_ASSERT(11 < LEASE_COLUMNS);
  729. // Add the data to the vector. Note the end element is one after the
  730. // end of the array.
  731. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  732. }
  733. /// @brief Create BIND array to receive data
  734. ///
  735. /// Creates a MYSQL_BIND array to receive Lease6 data from the database.
  736. /// After data is successfully received, getLeaseData() is used to copy
  737. /// it to a Lease6 object.
  738. ///
  739. /// @return Vector of MySQL BIND objects passed to the MySQL data retrieval
  740. /// functions.
  741. std::vector<MYSQL_BIND> createBindForReceive() {
  742. // Initialize MYSQL_BIND array.
  743. // It sets all fields, including is_null, to zero, so we need to set
  744. // is_null only if it should be true. This gives up minor performance
  745. // benefit while being safe approach. For improved readability, the
  746. // code that explicitly sets is_null is there, but is commented out.
  747. memset(bind_, 0, sizeof(bind_));
  748. // address: varchar(39)
  749. // A Lease6_ address has a maximum of 39 characters. The array is
  750. // one byte longer than this to guarantee that we can always null
  751. // terminate it whatever is returned.
  752. addr6_length_ = sizeof(addr6_buffer_) - 1;
  753. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  754. bind_[0].buffer = addr6_buffer_;
  755. bind_[0].buffer_length = addr6_length_;
  756. bind_[0].length = &addr6_length_;
  757. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  758. // reasons, see memset() above
  759. // client_id: varbinary(128)
  760. duid_length_ = sizeof(duid_buffer_);
  761. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  762. bind_[1].buffer = reinterpret_cast<char*>(duid_buffer_);
  763. bind_[1].buffer_length = duid_length_;
  764. bind_[1].length = &duid_length_;
  765. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  766. // reasons, see memset() above
  767. // lease_time: unsigned int
  768. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  769. bind_[2].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  770. bind_[2].is_unsigned = MLM_TRUE;
  771. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  772. // reasons, see memset() above
  773. // expire: timestamp
  774. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  775. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  776. bind_[3].buffer_length = sizeof(expire_);
  777. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  778. // reasons, see memset() above
  779. // subnet_id: unsigned int
  780. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  781. bind_[4].buffer = reinterpret_cast<char*>(&subnet_id_);
  782. bind_[4].is_unsigned = MLM_TRUE;
  783. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  784. // reasons, see memset() above
  785. // pref_lifetime: unsigned int
  786. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  787. bind_[5].buffer = reinterpret_cast<char*>(&pref_lifetime_);
  788. bind_[5].is_unsigned = MLM_TRUE;
  789. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  790. // reasons, see memset() above
  791. // lease_type: tinyint
  792. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  793. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  794. bind_[6].is_unsigned = MLM_TRUE;
  795. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  796. // reasons, see memset() above
  797. // iaid: unsigned int
  798. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  799. bind_[7].buffer = reinterpret_cast<char*>(&iaid_);
  800. bind_[7].is_unsigned = MLM_TRUE;
  801. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  802. // reasons, see memset() above
  803. // prefix_len: unsigned tinyint
  804. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  805. bind_[8].buffer = reinterpret_cast<char*>(&prefixlen_);
  806. bind_[8].is_unsigned = MLM_TRUE;
  807. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  808. // reasons, see memset() above
  809. // fqdn_fwd: boolean
  810. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  811. bind_[9].buffer = reinterpret_cast<char*>(&fqdn_fwd_);
  812. bind_[9].is_unsigned = MLM_TRUE;
  813. // bind_[9].is_null = &MLM_FALSE; // commented out for performance
  814. // reasons, see memset() above
  815. // fqdn_rev: boolean
  816. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  817. bind_[10].buffer = reinterpret_cast<char*>(&fqdn_rev_);
  818. bind_[10].is_unsigned = MLM_TRUE;
  819. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  820. // reasons, see memset() above
  821. // hostname: varchar(255)
  822. hostname_length_ = sizeof(hostname_buffer_);
  823. bind_[11].buffer_type = MYSQL_TYPE_STRING;
  824. bind_[11].buffer = reinterpret_cast<char*>(hostname_buffer_);
  825. bind_[11].buffer_length = hostname_length_;
  826. bind_[11].length = &hostname_length_;
  827. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  828. // reasons, see memset() above
  829. // Add the error flags
  830. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  831. // .. and check that we have the numbers correct at compile time.
  832. BOOST_STATIC_ASSERT(11 < LEASE_COLUMNS);
  833. // Add the data to the vector. Note the end element is one after the
  834. // end of the array.
  835. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  836. }
  837. /// @brief Copy Received Data into Lease6 Object
  838. ///
  839. /// Called after the MYSQL_BIND array created by createBindForReceive()
  840. /// has been used, this copies data from the internal member variables
  841. /// into a Lease6 object.
  842. ///
  843. /// @return Lease6Ptr Pointer to a Lease6 object holding the relevant
  844. /// data.
  845. ///
  846. /// @throw isc::BadValue Unable to convert Lease Type value in database
  847. Lease6Ptr getLeaseData() {
  848. // The address buffer is declared larger than the buffer size passed
  849. // to the access function so that we can always append a null byte.
  850. // Create the IOAddress object corresponding to the received data.
  851. addr6_buffer_[addr6_length_] = '\0';
  852. std::string address = addr6_buffer_;
  853. isc::asiolink::IOAddress addr(address);
  854. // Set the lease type in a variable of the appropriate data type, which
  855. // has been initialized with an arbitrary (but valid) value.
  856. Lease::Type type = Lease::TYPE_NA;
  857. switch (lease_type_) {
  858. case Lease::TYPE_NA:
  859. type = Lease::TYPE_NA;
  860. break;
  861. case Lease::TYPE_TA:
  862. type = Lease::TYPE_TA;
  863. break;
  864. case Lease::TYPE_PD:
  865. type = Lease::TYPE_PD;
  866. break;
  867. default:
  868. isc_throw(BadValue, "invalid lease type returned (" <<
  869. static_cast<int>(lease_type_) << ") for lease with "
  870. << "address " << address << ". Only 0, 1, or 2 are "
  871. << "allowed.");
  872. }
  873. // Set up DUID,
  874. DuidPtr duid_ptr(new DUID(duid_buffer_, duid_length_));
  875. // Hostname is passed to Lease6 as a string object, so we have to
  876. // create it from the hostname buffer and length.
  877. std::string hostname(hostname_buffer_,
  878. hostname_buffer_ + hostname_length_);
  879. // Create the lease and set the cltt (after converting from the
  880. // expire time retrieved from the database).
  881. Lease6Ptr result(new Lease6(type, addr, duid_ptr, iaid_,
  882. pref_lifetime_, valid_lifetime_, 0, 0,
  883. subnet_id_, fqdn_fwd_, fqdn_rev_,
  884. hostname, prefixlen_));
  885. time_t cltt = 0;
  886. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  887. result->cltt_ = cltt;
  888. return (result);
  889. }
  890. /// @brief Return columns in error
  891. ///
  892. /// If an error is returned from a fetch (in particular, a truncated
  893. /// status), this method can be called to get the names of the fields in
  894. /// error. It returns a string comprising the names of the fields
  895. /// separated by commas. In the case of there being no error indicators
  896. /// set, it returns the string "(None)".
  897. ///
  898. /// @return Comma-separated list of columns in error, or the string
  899. /// "(None)".
  900. std::string getErrorColumns() {
  901. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  902. }
  903. private:
  904. // Note: All array lengths are equal to the corresponding variable in the
  905. // schema.
  906. // Note: arrays are declared fixed length for speed of creation
  907. std::string addr6_; ///< String form of address
  908. char addr6_buffer_[ADDRESS6_TEXT_MAX_LEN + 1]; ///< Character
  909. ///< array form of V6 address
  910. unsigned long addr6_length_; ///< Length of the address
  911. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  912. std::string columns_[LEASE_COLUMNS];///< Column names
  913. std::vector<uint8_t> duid_; ///< Client identification
  914. uint8_t duid_buffer_[DUID::MAX_DUID_LEN]; ///< Buffer form of DUID
  915. unsigned long duid_length_; ///< Length of the DUID
  916. my_bool error_[LEASE_COLUMNS]; ///< Error indicators
  917. MYSQL_TIME expire_; ///< Lease expiry time
  918. uint32_t iaid_; ///< Identity association ID
  919. Lease6Ptr lease_; ///< Pointer to lease object
  920. uint8_t lease_type_; ///< Lease type
  921. uint8_t prefixlen_; ///< Prefix length
  922. uint32_t pref_lifetime_; ///< Preferred lifetime
  923. uint32_t subnet_id_; ///< Subnet identification
  924. uint32_t valid_lifetime_; ///< Lease time
  925. my_bool fqdn_fwd_; ///< Has forward DNS update been
  926. ///< performed
  927. my_bool fqdn_rev_; ///< Has reverse DNS update been
  928. ///< performed
  929. char hostname_buffer_[HOSTNAME_MAX_LEN];
  930. ///< Client hostname
  931. unsigned long hostname_length_; ///< Client hostname length
  932. };
  933. /// @brief Fetch and Release MySQL Results
  934. ///
  935. /// When a MySQL statement is expected, to fetch the results the function
  936. /// mysql_stmt_fetch() must be called. As well as getting data, this
  937. /// allocates internal state. Subsequent calls to mysql_stmt_fetch can be
  938. /// made, but when all the data is retrieved, mysql_stmt_free_result must be
  939. /// called to free up the resources allocated.
  940. ///
  941. /// Created prior to the first fetch, this class's destructor calls
  942. /// mysql_stmt_free_result, so eliminating the need for an explicit release
  943. /// in the method calling mysql_stmt_free_result. In this way, it guarantees
  944. /// that the resources are released even if the MySqlLeaseMgr method concerned
  945. /// exits via an exception.
  946. class MySqlFreeResult {
  947. public:
  948. /// @brief Constructor
  949. ///
  950. /// Store the pointer to the statement for which data is being fetched.
  951. ///
  952. /// Note that according to the MySQL documentation, mysql_stmt_free_result
  953. /// only releases resources if a cursor has been allocated for the
  954. /// statement. This implies that it is a no-op if none have been. Either
  955. /// way, any error from mysql_stmt_free_result is ignored. (Generating
  956. /// an exception is not much help, as it will only confuse things if the
  957. /// method calling mysql_stmt_fetch is exiting via an exception.)
  958. MySqlFreeResult(MYSQL_STMT* statement) : statement_(statement)
  959. {}
  960. /// @brief Destructor
  961. ///
  962. /// Frees up fetch context if a fetch has been successfully executed.
  963. ~MySqlFreeResult() {
  964. (void) mysql_stmt_free_result(statement_);
  965. }
  966. private:
  967. MYSQL_STMT* statement_; ///< Statement for which results are freed
  968. };
  969. // MySqlLeaseMgr Constructor and Destructor
  970. MySqlLeaseMgr::MySqlLeaseMgr(const LeaseMgr::ParameterMap& parameters)
  971. : LeaseMgr(parameters) {
  972. // Open the database.
  973. openDatabase();
  974. // Enable autocommit. To avoid a flush to disk on every commit, the global
  975. // parameter innodb_flush_log_at_trx_commit should be set to 2. This will
  976. // cause the changes to be written to the log, but flushed to disk in the
  977. // background every second. Setting the parameter to that value will speed
  978. // up the system, but at the risk of losing data if the system crashes.
  979. my_bool result = mysql_autocommit(mysql_, 1);
  980. if (result != 0) {
  981. isc_throw(DbOperationError, mysql_error(mysql_));
  982. }
  983. // Prepare all statements likely to be used.
  984. prepareStatements();
  985. // Create the exchange objects for use in exchanging data between the
  986. // program and the database.
  987. exchange4_.reset(new MySqlLease4Exchange());
  988. exchange6_.reset(new MySqlLease6Exchange());
  989. }
  990. MySqlLeaseMgr::~MySqlLeaseMgr() {
  991. // Free up the prepared statements, ignoring errors. (What would we do
  992. // about them? We're destroying this object and are not really concerned
  993. // with errors on a database connection that is about to go away.)
  994. for (int i = 0; i < statements_.size(); ++i) {
  995. if (statements_[i] != NULL) {
  996. (void) mysql_stmt_close(statements_[i]);
  997. statements_[i] = NULL;
  998. }
  999. }
  1000. // There is no need to close the database in this destructor: it is
  1001. // closed in the destructor of the mysql_ member variable.
  1002. }
  1003. // Time conversion methods.
  1004. //
  1005. // Note that the MySQL TIMESTAMP data type (used for "expire") converts data
  1006. // from the current timezone to UTC for storage, and from UTC to the current
  1007. // timezone for retrieval.
  1008. //
  1009. // This causes no problems providing that:
  1010. // a) cltt is given in local time
  1011. // b) We let the system take care of timezone conversion when converting
  1012. // from a time read from the database into a local time.
  1013. void
  1014. MySqlLeaseMgr::convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  1015. MYSQL_TIME& expire) {
  1016. // Calculate expiry time.
  1017. // @TODO: handle overflows
  1018. time_t expire_time = cltt + valid_lifetime;
  1019. // Convert to broken-out time
  1020. struct tm expire_tm;
  1021. (void) localtime_r(&expire_time, &expire_tm);
  1022. // Place in output expire structure.
  1023. expire.year = expire_tm.tm_year + 1900;
  1024. expire.month = expire_tm.tm_mon + 1; // Note different base
  1025. expire.day = expire_tm.tm_mday;
  1026. expire.hour = expire_tm.tm_hour;
  1027. expire.minute = expire_tm.tm_min;
  1028. expire.second = expire_tm.tm_sec;
  1029. expire.second_part = 0; // No fractional seconds
  1030. expire.neg = my_bool(0); // Not negative
  1031. }
  1032. void
  1033. MySqlLeaseMgr::convertFromDatabaseTime(const MYSQL_TIME& expire,
  1034. uint32_t valid_lifetime, time_t& cltt) {
  1035. // Copy across fields from MYSQL_TIME structure.
  1036. struct tm expire_tm;
  1037. memset(&expire_tm, 0, sizeof(expire_tm));
  1038. expire_tm.tm_year = expire.year - 1900;
  1039. expire_tm.tm_mon = expire.month - 1;
  1040. expire_tm.tm_mday = expire.day;
  1041. expire_tm.tm_hour = expire.hour;
  1042. expire_tm.tm_min = expire.minute;
  1043. expire_tm.tm_sec = expire.second;
  1044. expire_tm.tm_isdst = -1; // Let the system work out about DST
  1045. // Convert to local time
  1046. cltt = mktime(&expire_tm) - valid_lifetime;
  1047. }
  1048. // Open the database using the parameters passed to the constructor.
  1049. void
  1050. MySqlLeaseMgr::openDatabase() {
  1051. // Set up the values of the parameters
  1052. const char* host = "localhost";
  1053. string shost;
  1054. try {
  1055. shost = getParameter("host");
  1056. host = shost.c_str();
  1057. } catch (...) {
  1058. // No host. Fine, we'll use "localhost"
  1059. }
  1060. const char* user = NULL;
  1061. string suser;
  1062. try {
  1063. suser = getParameter("user");
  1064. user = suser.c_str();
  1065. } catch (...) {
  1066. // No user. Fine, we'll use NULL
  1067. }
  1068. const char* password = NULL;
  1069. string spassword;
  1070. try {
  1071. spassword = getParameter("password");
  1072. password = spassword.c_str();
  1073. } catch (...) {
  1074. // No password. Fine, we'll use NULL
  1075. }
  1076. const char* name = NULL;
  1077. string sname;
  1078. try {
  1079. sname = getParameter("name");
  1080. name = sname.c_str();
  1081. } catch (...) {
  1082. // No database name. Throw a "NoName" exception
  1083. isc_throw(NoDatabaseName, "must specified a name for the database");
  1084. }
  1085. // Set options for the connection:
  1086. //
  1087. // Automatic reconnection: after a period of inactivity, the client will
  1088. // disconnect from the database. This option causes it to automatically
  1089. // reconnect when another operation is about to be done.
  1090. my_bool auto_reconnect = MLM_TRUE;
  1091. int result = mysql_options(mysql_, MYSQL_OPT_RECONNECT, &auto_reconnect);
  1092. if (result != 0) {
  1093. isc_throw(DbOpenError, "unable to set auto-reconnect option: " <<
  1094. mysql_error(mysql_));
  1095. }
  1096. // Set SQL mode options for the connection: SQL mode governs how what
  1097. // constitutes insertable data for a given column, and how to handle
  1098. // invalid data. We want to ensure we get the strictest behavior and
  1099. // to reject invalid data with an error.
  1100. const char *sql_mode = "SET SESSION sql_mode ='STRICT_ALL_TABLES'";
  1101. result = mysql_options(mysql_, MYSQL_INIT_COMMAND, sql_mode);
  1102. if (result != 0) {
  1103. isc_throw(DbOpenError, "unable to set SQL mode options: " <<
  1104. mysql_error(mysql_));
  1105. }
  1106. // Open the database.
  1107. //
  1108. // The option CLIENT_FOUND_ROWS is specified so that in an UPDATE,
  1109. // the affected rows are the number of rows found that match the
  1110. // WHERE clause of the SQL statement, not the rows changed. The reason
  1111. // here is that MySQL apparently does not update a row if data has not
  1112. // changed and so the "affected rows" (retrievable from MySQL) is zero.
  1113. // This makes it hard to distinguish whether the UPDATE changed no rows
  1114. // because no row matching the WHERE clause was found, or because a
  1115. // row was found but no data was altered.
  1116. MYSQL* status = mysql_real_connect(mysql_, host, user, password, name,
  1117. 0, NULL, CLIENT_FOUND_ROWS);
  1118. if (status != mysql_) {
  1119. isc_throw(DbOpenError, mysql_error(mysql_));
  1120. }
  1121. }
  1122. // Prepared statement setup. The textual form of an SQL statement is stored
  1123. // in a vector of strings (text_statements_) and is used in the output of
  1124. // error messages. The SQL statement is also compiled into a "prepared
  1125. // statement" (stored in statements_), which avoids the overhead of compilation
  1126. // during use. As prepared statements have resources allocated to them, the
  1127. // class destructor explicitly destroys them.
  1128. void
  1129. MySqlLeaseMgr::prepareStatement(StatementIndex index, const char* text) {
  1130. // Validate that there is space for the statement in the statements array
  1131. // and that nothing has been placed there before.
  1132. if ((index >= statements_.size()) || (statements_[index] != NULL)) {
  1133. isc_throw(InvalidParameter, "invalid prepared statement index (" <<
  1134. static_cast<int>(index) << ") or indexed prepared " <<
  1135. "statement is not null");
  1136. }
  1137. // All OK, so prepare the statement
  1138. text_statements_[index] = std::string(text);
  1139. statements_[index] = mysql_stmt_init(mysql_);
  1140. if (statements_[index] == NULL) {
  1141. isc_throw(DbOperationError, "unable to allocate MySQL prepared "
  1142. "statement structure, reason: " << mysql_error(mysql_));
  1143. }
  1144. int status = mysql_stmt_prepare(statements_[index], text, strlen(text));
  1145. if (status != 0) {
  1146. isc_throw(DbOperationError, "unable to prepare MySQL statement <" <<
  1147. text << ">, reason: " << mysql_error(mysql_));
  1148. }
  1149. }
  1150. void
  1151. MySqlLeaseMgr::prepareStatements() {
  1152. // Allocate space for all statements
  1153. statements_.clear();
  1154. statements_.resize(NUM_STATEMENTS, NULL);
  1155. text_statements_.clear();
  1156. text_statements_.resize(NUM_STATEMENTS, std::string(""));
  1157. // Created the MySQL prepared statements for each DML statement.
  1158. for (int i = 0; tagged_statements[i].text != NULL; ++i) {
  1159. prepareStatement(tagged_statements[i].index,
  1160. tagged_statements[i].text);
  1161. }
  1162. }
  1163. // Add leases to the database. The two public methods accept a lease object
  1164. // (either V4 of V6), bind the contents to the appropriate prepared
  1165. // statement, then call common code to execute the statement.
  1166. bool
  1167. MySqlLeaseMgr::addLeaseCommon(StatementIndex stindex,
  1168. std::vector<MYSQL_BIND>& bind) {
  1169. // Bind the parameters to the statement
  1170. int status = mysql_stmt_bind_param(statements_[stindex], &bind[0]);
  1171. checkError(status, stindex, "unable to bind parameters");
  1172. // Execute the statement
  1173. status = mysql_stmt_execute(statements_[stindex]);
  1174. if (status != 0) {
  1175. // Failure: check for the special case of duplicate entry. If this is
  1176. // the case, we return false to indicate that the row was not added.
  1177. // Otherwise we throw an exception.
  1178. if (mysql_errno(mysql_) == ER_DUP_ENTRY) {
  1179. return (false);
  1180. }
  1181. checkError(status, stindex, "unable to execute");
  1182. }
  1183. // Insert succeeded
  1184. return (true);
  1185. }
  1186. bool
  1187. MySqlLeaseMgr::addLease(const Lease4Ptr& lease) {
  1188. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1189. DHCPSRV_MYSQL_ADD_ADDR4).arg(lease->addr_.toText());
  1190. // Create the MYSQL_BIND array for the lease
  1191. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1192. // ... and drop to common code.
  1193. return (addLeaseCommon(INSERT_LEASE4, bind));
  1194. }
  1195. bool
  1196. MySqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  1197. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1198. DHCPSRV_MYSQL_ADD_ADDR6).arg(lease->addr_.toText())
  1199. .arg(lease->type_);
  1200. // Create the MYSQL_BIND array for the lease
  1201. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1202. // ... and drop to common code.
  1203. return (addLeaseCommon(INSERT_LEASE6, bind));
  1204. }
  1205. // Extraction of leases from the database.
  1206. //
  1207. // All getLease() methods ultimately call getLeaseCollection(). This
  1208. // binds the input parameters passed to it with the appropriate prepared
  1209. // statement and executes the statement. It then gets the results from the
  1210. // database. getlease() methods that expect a single result back call it
  1211. // with the "single" parameter set true: this causes an exception to be
  1212. // generated if multiple records can be retrieved from the result set. (Such
  1213. // an occurrence either indicates corruption in the database, or that an
  1214. // assumption that a query can only return a single record is incorrect.)
  1215. // Methods that require a collection of records have "single" set to the
  1216. // default value of false. The logic is the same for both Lease4 and Lease6
  1217. // objects, so the code is templated.
  1218. //
  1219. // Methods that require a collection of objects access this method through
  1220. // two interface methods (also called getLeaseCollection()). These are
  1221. // short enough as to be defined in the header file: all they do is to supply
  1222. // the appropriate MySqlLeaseXExchange object depending on the type of the
  1223. // LeaseCollection objects passed to them.
  1224. //
  1225. // Methods that require a single object to be returned access the method
  1226. // through two interface methods (called getLease()). As well as supplying
  1227. // the appropriate exchange object, they convert between lease collection
  1228. // holding zero or one leases into an appropriate Lease object.
  1229. template <typename Exchange, typename LeaseCollection>
  1230. void MySqlLeaseMgr::getLeaseCollection(StatementIndex stindex,
  1231. MYSQL_BIND* bind,
  1232. Exchange& exchange,
  1233. LeaseCollection& result,
  1234. bool single) const {
  1235. // Bind the selection parameters to the statement
  1236. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1237. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1238. // Set up the MYSQL_BIND array for the data being returned and bind it to
  1239. // the statement.
  1240. std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
  1241. status = mysql_stmt_bind_result(statements_[stindex], &outbind[0]);
  1242. checkError(status, stindex, "unable to bind SELECT clause parameters");
  1243. // Execute the statement
  1244. status = mysql_stmt_execute(statements_[stindex]);
  1245. checkError(status, stindex, "unable to execute");
  1246. // Ensure that all the lease information is retrieved in one go to avoid
  1247. // overhead of going back and forth between client and server.
  1248. status = mysql_stmt_store_result(statements_[stindex]);
  1249. checkError(status, stindex, "unable to set up for storing all results");
  1250. // Set up the fetch "release" object to release resources associated
  1251. // with the call to mysql_stmt_fetch when this method exits, then
  1252. // retrieve the data.
  1253. MySqlFreeResult fetch_release(statements_[stindex]);
  1254. int count = 0;
  1255. while ((status = mysql_stmt_fetch(statements_[stindex])) == 0) {
  1256. try {
  1257. result.push_back(exchange->getLeaseData());
  1258. } catch (const isc::BadValue& ex) {
  1259. // Rethrow the exception with a bit more data.
  1260. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  1261. text_statements_[stindex] << ">");
  1262. }
  1263. if (single && (++count > 1)) {
  1264. isc_throw(MultipleRecords, "multiple records were found in the "
  1265. "database where only one was expected for query "
  1266. << text_statements_[stindex]);
  1267. }
  1268. }
  1269. // How did the fetch end?
  1270. if (status == 1) {
  1271. // Error - unable to fetch results
  1272. checkError(status, stindex, "unable to fetch results");
  1273. } else if (status == MYSQL_DATA_TRUNCATED) {
  1274. // Data truncated - throw an exception indicating what was at fault
  1275. isc_throw(DataTruncated, text_statements_[stindex]
  1276. << " returned truncated data: columns affected are "
  1277. << exchange->getErrorColumns());
  1278. }
  1279. }
  1280. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1281. Lease4Ptr& result) const {
  1282. // Create appropriate collection object and get all leases matching
  1283. // the selection criteria. The "single" paraeter is true to indicate
  1284. // that the called method should throw an exception if multiple
  1285. // matching records are found: this particular method is called when only
  1286. // one or zero matches is expected.
  1287. Lease4Collection collection;
  1288. getLeaseCollection(stindex, bind, exchange4_, collection, true);
  1289. // Return single record if present, else clear the lease.
  1290. if (collection.empty()) {
  1291. result.reset();
  1292. } else {
  1293. result = *collection.begin();
  1294. }
  1295. }
  1296. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1297. Lease6Ptr& result) const {
  1298. // Create appropriate collection object and get all leases matching
  1299. // the selection criteria. The "single" paraeter is true to indicate
  1300. // that the called method should throw an exception if multiple
  1301. // matching records are found: this particular method is called when only
  1302. // one or zero matches is expected.
  1303. Lease6Collection collection;
  1304. getLeaseCollection(stindex, bind, exchange6_, collection, true);
  1305. // Return single record if present, else clear the lease.
  1306. if (collection.empty()) {
  1307. result.reset();
  1308. } else {
  1309. result = *collection.begin();
  1310. }
  1311. }
  1312. // Basic lease access methods. Obtain leases from the database using various
  1313. // criteria.
  1314. Lease4Ptr
  1315. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
  1316. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1317. DHCPSRV_MYSQL_GET_ADDR4).arg(addr.toText());
  1318. // Set up the WHERE clause value
  1319. MYSQL_BIND inbind[1];
  1320. memset(inbind, 0, sizeof(inbind));
  1321. uint32_t addr4 = static_cast<uint32_t>(addr);
  1322. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1323. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1324. inbind[0].is_unsigned = MLM_TRUE;
  1325. // Get the data
  1326. Lease4Ptr result;
  1327. getLease(GET_LEASE4_ADDR, inbind, result);
  1328. return (result);
  1329. }
  1330. Lease4Collection
  1331. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr) const {
  1332. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1333. DHCPSRV_MYSQL_GET_HWADDR).arg(hwaddr.toText());
  1334. // Set up the WHERE clause value
  1335. MYSQL_BIND inbind[1];
  1336. memset(inbind, 0, sizeof(inbind));
  1337. // As "buffer" is "char*" - even though the data is being read - we need
  1338. // to cast away the "const"ness as well as reinterpreting the data as
  1339. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1340. // local variable, but as the data is only being read, this introduces
  1341. // an unnecessary copy).
  1342. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1343. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1344. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1345. inbind[0].buffer = reinterpret_cast<char*>(data);
  1346. inbind[0].buffer_length = hwaddr_length;
  1347. inbind[0].length = &hwaddr_length;
  1348. // Get the data
  1349. Lease4Collection result;
  1350. getLeaseCollection(GET_LEASE4_HWADDR, inbind, result);
  1351. return (result);
  1352. }
  1353. Lease4Ptr
  1354. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr, SubnetID subnet_id) const {
  1355. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1356. DHCPSRV_MYSQL_GET_SUBID_HWADDR)
  1357. .arg(subnet_id).arg(hwaddr.toText());
  1358. // Set up the WHERE clause value
  1359. MYSQL_BIND inbind[2];
  1360. memset(inbind, 0, sizeof(inbind));
  1361. // As "buffer" is "char*" - even though the data is being read - we need
  1362. // to cast away the "const"ness as well as reinterpreting the data as
  1363. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1364. // local variable, but as the data is only being read, this introduces
  1365. // an unnecessary copy).
  1366. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1367. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1368. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1369. inbind[0].buffer = reinterpret_cast<char*>(data);
  1370. inbind[0].buffer_length = hwaddr_length;
  1371. inbind[0].length = &hwaddr_length;
  1372. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1373. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1374. inbind[1].is_unsigned = MLM_TRUE;
  1375. // Get the data
  1376. Lease4Ptr result;
  1377. getLease(GET_LEASE4_HWADDR_SUBID, inbind, result);
  1378. return (result);
  1379. }
  1380. Lease4Collection
  1381. MySqlLeaseMgr::getLease4(const ClientId& clientid) const {
  1382. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1383. DHCPSRV_MYSQL_GET_CLIENTID).arg(clientid.toText());
  1384. // Set up the WHERE clause value
  1385. MYSQL_BIND inbind[1];
  1386. memset(inbind, 0, sizeof(inbind));
  1387. std::vector<uint8_t> client_data = clientid.getClientId();
  1388. unsigned long client_data_length = client_data.size();
  1389. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1390. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1391. inbind[0].buffer_length = client_data_length;
  1392. inbind[0].length = &client_data_length;
  1393. // Get the data
  1394. Lease4Collection result;
  1395. getLeaseCollection(GET_LEASE4_CLIENTID, inbind, result);
  1396. return (result);
  1397. }
  1398. Lease4Ptr
  1399. MySqlLeaseMgr::getLease4(const ClientId&, const HWAddr&, SubnetID) const {
  1400. /// This function is currently not implemented because allocation engine
  1401. /// searches for the lease using HW address or client identifier.
  1402. /// It never uses both parameters in the same time. We need to
  1403. /// consider if this function is needed at all.
  1404. isc_throw(NotImplemented, "The MySqlLeaseMgr::getLease4 function was"
  1405. " called, but it is not implemented");
  1406. }
  1407. Lease4Ptr
  1408. MySqlLeaseMgr::getLease4(const ClientId& clientid, SubnetID subnet_id) const {
  1409. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1410. DHCPSRV_MYSQL_GET_SUBID_CLIENTID)
  1411. .arg(subnet_id).arg(clientid.toText());
  1412. // Set up the WHERE clause value
  1413. MYSQL_BIND inbind[2];
  1414. memset(inbind, 0, sizeof(inbind));
  1415. std::vector<uint8_t> client_data = clientid.getClientId();
  1416. unsigned long client_data_length = client_data.size();
  1417. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1418. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1419. inbind[0].buffer_length = client_data_length;
  1420. inbind[0].length = &client_data_length;
  1421. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1422. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1423. inbind[1].is_unsigned = MLM_TRUE;
  1424. // Get the data
  1425. Lease4Ptr result;
  1426. getLease(GET_LEASE4_CLIENTID_SUBID, inbind, result);
  1427. return (result);
  1428. }
  1429. Lease6Ptr
  1430. MySqlLeaseMgr::getLease6(Lease::Type lease_type,
  1431. const isc::asiolink::IOAddress& addr) const {
  1432. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1433. DHCPSRV_MYSQL_GET_ADDR6).arg(addr.toText())
  1434. .arg(lease_type);
  1435. // Set up the WHERE clause value
  1436. MYSQL_BIND inbind[2];
  1437. memset(inbind, 0, sizeof(inbind));
  1438. std::string addr6 = addr.toText();
  1439. unsigned long addr6_length = addr6.size();
  1440. // See the earlier description of the use of "const_cast" when accessing
  1441. // the address for an explanation of the reason.
  1442. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1443. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1444. inbind[0].buffer_length = addr6_length;
  1445. inbind[0].length = &addr6_length;
  1446. // LEASE_TYPE
  1447. inbind[1].buffer_type = MYSQL_TYPE_TINY;
  1448. inbind[1].buffer = reinterpret_cast<char*>(&lease_type);
  1449. inbind[1].is_unsigned = MLM_TRUE;
  1450. Lease6Ptr result;
  1451. getLease(GET_LEASE6_ADDR, inbind, result);
  1452. return (result);
  1453. }
  1454. Lease6Collection
  1455. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1456. const DUID& duid, uint32_t iaid) const {
  1457. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1458. DHCPSRV_MYSQL_GET_IAID_DUID).arg(iaid).arg(duid.toText())
  1459. .arg(lease_type);
  1460. // Set up the WHERE clause value
  1461. MYSQL_BIND inbind[3];
  1462. memset(inbind, 0, sizeof(inbind));
  1463. // In the following statement, the DUID is being read. However, the
  1464. // MySQL C interface does not use "const", so the "buffer" element
  1465. // is declared as "char*" instead of "const char*". To resolve this,
  1466. // the "const" is discarded before the uint8_t* is cast to char*.
  1467. //
  1468. // Note that the const_cast could be avoided by copying the DUID to
  1469. // a writeable buffer and storing the address of that in the "buffer"
  1470. // element. However, this introduces a copy operation (with additional
  1471. // overhead) purely to get round the structures introduced by design of
  1472. // the MySQL interface (which uses the area pointed to by "buffer" as
  1473. // input when specifying query parameters and as output when retrieving
  1474. // data). For that reason, "const_cast" has been used.
  1475. const vector<uint8_t>& duid_vector = duid.getDuid();
  1476. unsigned long duid_length = duid_vector.size();
  1477. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1478. inbind[0].buffer = reinterpret_cast<char*>(
  1479. const_cast<uint8_t*>(&duid_vector[0]));
  1480. inbind[0].buffer_length = duid_length;
  1481. inbind[0].length = &duid_length;
  1482. // IAID
  1483. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1484. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1485. inbind[1].is_unsigned = MLM_TRUE;
  1486. // LEASE_TYPE
  1487. inbind[2].buffer_type = MYSQL_TYPE_TINY;
  1488. inbind[2].buffer = reinterpret_cast<char*>(&lease_type);
  1489. inbind[2].is_unsigned = MLM_TRUE;
  1490. // ... and get the data
  1491. Lease6Collection result;
  1492. getLeaseCollection(GET_LEASE6_DUID_IAID, inbind, result);
  1493. return (result);
  1494. }
  1495. Lease6Collection
  1496. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1497. const DUID& duid, uint32_t iaid,
  1498. SubnetID subnet_id) const {
  1499. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1500. DHCPSRV_MYSQL_GET_IAID_SUBID_DUID)
  1501. .arg(iaid).arg(subnet_id).arg(duid.toText())
  1502. .arg(lease_type);
  1503. // Set up the WHERE clause value
  1504. MYSQL_BIND inbind[4];
  1505. memset(inbind, 0, sizeof(inbind));
  1506. // See the earlier description of the use of "const_cast" when accessing
  1507. // the DUID for an explanation of the reason.
  1508. const vector<uint8_t>& duid_vector = duid.getDuid();
  1509. unsigned long duid_length = duid_vector.size();
  1510. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1511. inbind[0].buffer = reinterpret_cast<char*>(
  1512. const_cast<uint8_t*>(&duid_vector[0]));
  1513. inbind[0].buffer_length = duid_length;
  1514. inbind[0].length = &duid_length;
  1515. // IAID
  1516. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1517. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1518. inbind[1].is_unsigned = MLM_TRUE;
  1519. // Subnet ID
  1520. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  1521. inbind[2].buffer = reinterpret_cast<char*>(&subnet_id);
  1522. inbind[2].is_unsigned = MLM_TRUE;
  1523. // LEASE_TYPE
  1524. inbind[3].buffer_type = MYSQL_TYPE_TINY;
  1525. inbind[3].buffer = reinterpret_cast<char*>(&lease_type);
  1526. inbind[3].is_unsigned = MLM_TRUE;
  1527. // ... and get the data
  1528. Lease6Collection result;
  1529. getLeaseCollection(GET_LEASE6_DUID_IAID_SUBID, inbind, result);
  1530. return (result);
  1531. }
  1532. // Update lease methods. These comprise common code that handles the actual
  1533. // update, and type-specific methods that set up the parameters for the prepared
  1534. // statement depending on the type of lease.
  1535. template <typename LeasePtr>
  1536. void
  1537. MySqlLeaseMgr::updateLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind,
  1538. const LeasePtr& lease) {
  1539. // Bind the parameters to the statement
  1540. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1541. checkError(status, stindex, "unable to bind parameters");
  1542. // Execute
  1543. status = mysql_stmt_execute(statements_[stindex]);
  1544. checkError(status, stindex, "unable to execute");
  1545. // See how many rows were affected. The statement should only update a
  1546. // single row.
  1547. int affected_rows = mysql_stmt_affected_rows(statements_[stindex]);
  1548. if (affected_rows == 0) {
  1549. isc_throw(NoSuchLease, "unable to update lease for address " <<
  1550. lease->addr_ << " as it does not exist");
  1551. } else if (affected_rows > 1) {
  1552. // Should not happen - primary key constraint should only have selected
  1553. // one row.
  1554. isc_throw(DbOperationError, "apparently updated more than one lease "
  1555. "that had the address " << lease->addr_);
  1556. }
  1557. }
  1558. void
  1559. MySqlLeaseMgr::updateLease4(const Lease4Ptr& lease) {
  1560. const StatementIndex stindex = UPDATE_LEASE4;
  1561. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1562. DHCPSRV_MYSQL_UPDATE_ADDR4).arg(lease->addr_.toText());
  1563. // Create the MYSQL_BIND array for the data being updated
  1564. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1565. // Set up the WHERE clause and append it to the MYSQL_BIND array
  1566. MYSQL_BIND where;
  1567. memset(&where, 0, sizeof(where));
  1568. uint32_t addr4 = static_cast<uint32_t>(lease->addr_);
  1569. where.buffer_type = MYSQL_TYPE_LONG;
  1570. where.buffer = reinterpret_cast<char*>(&addr4);
  1571. where.is_unsigned = MLM_TRUE;
  1572. bind.push_back(where);
  1573. // Drop to common update code
  1574. updateLeaseCommon(stindex, &bind[0], lease);
  1575. }
  1576. void
  1577. MySqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  1578. const StatementIndex stindex = UPDATE_LEASE6;
  1579. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1580. DHCPSRV_MYSQL_UPDATE_ADDR6).arg(lease->addr_.toText())
  1581. .arg(lease->type_);
  1582. // Create the MYSQL_BIND array for the data being updated
  1583. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1584. // Set up the WHERE clause value
  1585. MYSQL_BIND where;
  1586. memset(&where, 0, sizeof(where));
  1587. std::string addr6 = lease->addr_.toText();
  1588. unsigned long addr6_length = addr6.size();
  1589. // See the earlier description of the use of "const_cast" when accessing
  1590. // the address for an explanation of the reason.
  1591. where.buffer_type = MYSQL_TYPE_STRING;
  1592. where.buffer = const_cast<char*>(addr6.c_str());
  1593. where.buffer_length = addr6_length;
  1594. where.length = &addr6_length;
  1595. bind.push_back(where);
  1596. // Drop to common update code
  1597. updateLeaseCommon(stindex, &bind[0], lease);
  1598. }
  1599. // Delete lease methods. Similar to other groups of methods, these comprise
  1600. // a per-type method that sets up the relevant MYSQL_BIND array (in this
  1601. // case, a single method for both V4 and V6 addresses) and a common method that
  1602. // handles the common processing.
  1603. bool
  1604. MySqlLeaseMgr::deleteLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind) {
  1605. // Bind the input parameters to the statement
  1606. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1607. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1608. // Execute
  1609. status = mysql_stmt_execute(statements_[stindex]);
  1610. checkError(status, stindex, "unable to execute");
  1611. // See how many rows were affected. Note that the statement may delete
  1612. // multiple rows.
  1613. return (mysql_stmt_affected_rows(statements_[stindex]) > 0);
  1614. }
  1615. bool
  1616. MySqlLeaseMgr::deleteLease(const isc::asiolink::IOAddress& addr) {
  1617. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1618. DHCPSRV_MYSQL_DELETE_ADDR).arg(addr.toText());
  1619. // Set up the WHERE clause value
  1620. MYSQL_BIND inbind[1];
  1621. memset(inbind, 0, sizeof(inbind));
  1622. if (addr.isV4()) {
  1623. uint32_t addr4 = static_cast<uint32_t>(addr);
  1624. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1625. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1626. inbind[0].is_unsigned = MLM_TRUE;
  1627. return (deleteLeaseCommon(DELETE_LEASE4, inbind));
  1628. } else {
  1629. std::string addr6 = addr.toText();
  1630. unsigned long addr6_length = addr6.size();
  1631. // See the earlier description of the use of "const_cast" when accessing
  1632. // the address for an explanation of the reason.
  1633. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1634. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1635. inbind[0].buffer_length = addr6_length;
  1636. inbind[0].length = &addr6_length;
  1637. return (deleteLeaseCommon(DELETE_LEASE6, inbind));
  1638. }
  1639. }
  1640. // Miscellaneous database methods.
  1641. std::string
  1642. MySqlLeaseMgr::getName() const {
  1643. std::string name = "";
  1644. try {
  1645. name = getParameter("name");
  1646. } catch (...) {
  1647. // Return an empty name
  1648. }
  1649. return (name);
  1650. }
  1651. std::string
  1652. MySqlLeaseMgr::getDescription() const {
  1653. return (std::string("MySQL Database"));
  1654. }
  1655. std::pair<uint32_t, uint32_t>
  1656. MySqlLeaseMgr::getVersion() const {
  1657. const StatementIndex stindex = GET_VERSION;
  1658. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1659. DHCPSRV_MYSQL_GET_VERSION);
  1660. uint32_t major; // Major version number
  1661. uint32_t minor; // Minor version number
  1662. // Execute the prepared statement
  1663. int status = mysql_stmt_execute(statements_[stindex]);
  1664. if (status != 0) {
  1665. isc_throw(DbOperationError, "unable to execute <"
  1666. << text_statements_[stindex] << "> - reason: " <<
  1667. mysql_error(mysql_));
  1668. }
  1669. // Bind the output of the statement to the appropriate variables.
  1670. MYSQL_BIND bind[2];
  1671. memset(bind, 0, sizeof(bind));
  1672. bind[0].buffer_type = MYSQL_TYPE_LONG;
  1673. bind[0].is_unsigned = 1;
  1674. bind[0].buffer = &major;
  1675. bind[0].buffer_length = sizeof(major);
  1676. bind[1].buffer_type = MYSQL_TYPE_LONG;
  1677. bind[1].is_unsigned = 1;
  1678. bind[1].buffer = &minor;
  1679. bind[1].buffer_length = sizeof(minor);
  1680. status = mysql_stmt_bind_result(statements_[stindex], bind);
  1681. if (status != 0) {
  1682. isc_throw(DbOperationError, "unable to bind result set: " <<
  1683. mysql_error(mysql_));
  1684. }
  1685. // Fetch the data and set up the "release" object to release associated
  1686. // resources when this method exits then retrieve the data.
  1687. MySqlFreeResult fetch_release(statements_[stindex]);
  1688. status = mysql_stmt_fetch(statements_[stindex]);
  1689. if (status != 0) {
  1690. isc_throw(DbOperationError, "unable to obtain result set: " <<
  1691. mysql_error(mysql_));
  1692. }
  1693. return (std::make_pair(major, minor));
  1694. }
  1695. void
  1696. MySqlLeaseMgr::commit() {
  1697. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_COMMIT);
  1698. if (mysql_commit(mysql_) != 0) {
  1699. isc_throw(DbOperationError, "commit failed: " << mysql_error(mysql_));
  1700. }
  1701. }
  1702. void
  1703. MySqlLeaseMgr::rollback() {
  1704. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_ROLLBACK);
  1705. if (mysql_rollback(mysql_) != 0) {
  1706. isc_throw(DbOperationError, "rollback failed: " << mysql_error(mysql_));
  1707. }
  1708. }
  1709. }; // end of isc::dhcp namespace
  1710. }; // end of isc namespace