mysql_lease_mgr.cc 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027
  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_->hwaddr_.size();
  325. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  326. bind_[1].buffer = reinterpret_cast<char*>(&(lease_->hwaddr_->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. // Recreate the hardware address.
  511. HWAddrPtr hwaddr(new HWAddr(hwaddr_buffer_, hwaddr_length_, HTYPE_ETHER));
  512. // note that T1 and T2 are not stored
  513. return (Lease4Ptr(new Lease4(addr4_, hwaddr,
  514. client_id_buffer_, client_id_length_,
  515. valid_lifetime_, 0, 0, cltt, subnet_id_,
  516. fqdn_fwd_, fqdn_rev_, hostname)));
  517. }
  518. /// @brief Return columns in error
  519. ///
  520. /// If an error is returned from a fetch (in particular, a truncated
  521. /// status), this method can be called to get the names of the fields in
  522. /// error. It returns a string comprising the names of the fields
  523. /// separated by commas. In the case of there being no error indicators
  524. /// set, it returns the string "(None)".
  525. ///
  526. /// @return Comma-separated list of columns in error, or the string
  527. /// "(None)".
  528. std::string getErrorColumns() {
  529. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  530. }
  531. private:
  532. // Note: All array lengths are equal to the corresponding variable in the
  533. // schema.
  534. // Note: Arrays are declared fixed length for speed of creation
  535. uint32_t addr4_; ///< IPv4 address
  536. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  537. std::string columns_[LEASE_COLUMNS];///< Column names
  538. my_bool error_[LEASE_COLUMNS]; ///< Error array
  539. std::vector<uint8_t> hwaddr_; ///< Hardware address
  540. uint8_t hwaddr_buffer_[HWAddr::MAX_HWADDR_LEN];
  541. ///< Hardware address buffer
  542. unsigned long hwaddr_length_; ///< Hardware address length
  543. std::vector<uint8_t> client_id_; ///< Client identification
  544. uint8_t client_id_buffer_[ClientId::MAX_CLIENT_ID_LEN];
  545. ///< Client ID buffer
  546. unsigned long client_id_length_; ///< Client ID address length
  547. my_bool client_id_null_; ///< Is Client ID null?
  548. MYSQL_TIME expire_; ///< Lease expiry time
  549. Lease4Ptr lease_; ///< Pointer to lease object
  550. uint32_t subnet_id_; ///< Subnet identification
  551. uint32_t valid_lifetime_; ///< Lease time
  552. my_bool fqdn_fwd_; ///< Has forward DNS update been
  553. ///< performed
  554. my_bool fqdn_rev_; ///< Has reverse DNS update been
  555. ///< performed
  556. char hostname_buffer_[HOSTNAME_MAX_LEN];
  557. ///< Client hostname
  558. unsigned long hostname_length_; ///< Client hostname length
  559. };
  560. /// @brief Exchange MySQL and Lease6 Data
  561. ///
  562. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  563. /// describe the parameters in the prepared statements. Where information is
  564. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  565. /// structure is identical. This class handles the creation of that array.
  566. ///
  567. /// Owing to the MySQL API, the process requires some intermediate variables
  568. /// to hold things like data length etc. This object holds those variables.
  569. ///
  570. /// @note There are no unit tests for this class. It is tested indirectly
  571. /// in all MySqlLeaseMgr::xxx6() calls where it is used.
  572. class MySqlLease6Exchange : public MySqlLeaseExchange {
  573. /// @brief Set number of database columns for this lease structure
  574. static const size_t LEASE_COLUMNS = 12;
  575. public:
  576. /// @brief Constructor
  577. ///
  578. /// The initialization of the variables here is nonly to satisfy cppcheck -
  579. /// all variables are initialized/set in the methods before they are used.
  580. MySqlLease6Exchange() : addr6_length_(0), duid_length_(0),
  581. fqdn_fwd_(false), fqdn_rev_(false),
  582. hostname_length_(0) {
  583. memset(addr6_buffer_, 0, sizeof(addr6_buffer_));
  584. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  585. memset(hostname_buffer_, 0, sizeof(hostname_buffer_));
  586. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  587. // Set the column names (for error messages)
  588. columns_[0] = "address";
  589. columns_[1] = "duid";
  590. columns_[2] = "valid_lifetime";
  591. columns_[3] = "expire";
  592. columns_[4] = "subnet_id";
  593. columns_[5] = "pref_lifetime";
  594. columns_[6] = "lease_type";
  595. columns_[7] = "iaid";
  596. columns_[8] = "prefix_len";
  597. columns_[9] = "fqdn_fwd";
  598. columns_[10] = "fqdn_rev";
  599. columns_[11] = "hostname";
  600. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  601. }
  602. /// @brief Create MYSQL_BIND objects for Lease6 Pointer
  603. ///
  604. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  605. /// the database.
  606. ///
  607. /// @param lease Lease object to be added to the database.
  608. ///
  609. /// @return Vector of MySQL BIND objects representing the data to be added.
  610. std::vector<MYSQL_BIND> createBindForSend(const Lease6Ptr& lease) {
  611. // Store lease object to ensure it remains valid.
  612. lease_ = lease;
  613. // Ensure bind_ array clear for constructing the MYSQL_BIND structures
  614. // for this lease.
  615. // It sets all fields, including is_null, to zero, so we need to set
  616. // is_null only if it should be true. This gives up minor performance
  617. // benefit while being safe approach. For improved readability, the
  618. // code that explicitly sets is_null is there, but is commented out.
  619. memset(bind_, 0, sizeof(bind_));
  620. // address: varchar(39)
  621. addr6_ = lease_->addr_.toText();
  622. addr6_length_ = addr6_.size();
  623. // In the following statement, the string is being read. However, the
  624. // MySQL C interface does not use "const", so the "buffer" element
  625. // is declared as "char*" instead of "const char*". To resolve this,
  626. // the "const" is discarded. (Note that the address of addr6_.c_str()
  627. // is guaranteed to be valid until the next non-const operation on
  628. // addr6_.)
  629. //
  630. // The const_cast could be avoided by copying the string to a writeable
  631. // buffer and storing the address of that in the "buffer" element.
  632. // However, this introduces a copy operation (with additional overhead)
  633. // purely to get round the structures introduced by design of the
  634. // MySQL interface (which uses the area pointed to by "buffer" as input
  635. // when specifying query parameters and as output when retrieving data).
  636. // For that reason, "const_cast" has been used.
  637. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  638. bind_[0].buffer = const_cast<char*>(addr6_.c_str());
  639. bind_[0].buffer_length = addr6_length_;
  640. bind_[0].length = &addr6_length_;
  641. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  642. // reasons, see memset() above
  643. // duid: varchar(128)
  644. duid_ = lease_->duid_->getDuid();
  645. duid_length_ = duid_.size();
  646. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  647. bind_[1].buffer = reinterpret_cast<char*>(&(duid_[0]));
  648. bind_[1].buffer_length = duid_length_;
  649. bind_[1].length = &duid_length_;
  650. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  651. // reasons, see memset() above
  652. // valid lifetime: unsigned int
  653. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  654. bind_[2].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  655. bind_[2].is_unsigned = MLM_TRUE;
  656. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  657. // reasons, see memset() above
  658. // expire: timestamp
  659. // The lease structure holds the client last transmission time (cltt_)
  660. // For convenience for external tools, this is converted to lease
  661. /// expiry time (expire). The relationship is given by:
  662. //
  663. // expire = cltt_ + valid_lft_
  664. //
  665. // @todo Handle overflows
  666. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  667. expire_);
  668. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  669. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  670. bind_[3].buffer_length = sizeof(expire_);
  671. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  672. // reasons, see memset() above
  673. // subnet_id: unsigned int
  674. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  675. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  676. bind_[4].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  677. bind_[4].is_unsigned = MLM_TRUE;
  678. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  679. // reasons, see memset() above
  680. // pref_lifetime: unsigned int
  681. // Can use lease_->preferred_lft_ directly as it is of type uint32_t.
  682. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  683. bind_[5].buffer = reinterpret_cast<char*>(&lease_->preferred_lft_);
  684. bind_[5].is_unsigned = MLM_TRUE;
  685. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  686. // reasons, see memset() above
  687. // lease_type: tinyint
  688. // Must convert to uint8_t as lease_->type_ is a LeaseType variable.
  689. lease_type_ = lease_->type_;
  690. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  691. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  692. bind_[6].is_unsigned = MLM_TRUE;
  693. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  694. // reasons, see memset() above
  695. // iaid: unsigned int
  696. // Can use lease_->iaid_ directly as it is of type uint32_t.
  697. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  698. bind_[7].buffer = reinterpret_cast<char*>(&lease_->iaid_);
  699. bind_[7].is_unsigned = MLM_TRUE;
  700. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  701. // reasons, see memset() above
  702. // prefix_len: unsigned tinyint
  703. // Can use lease_->prefixlen_ directly as it is uint32_t.
  704. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  705. bind_[8].buffer = reinterpret_cast<char*>(&lease_->prefixlen_);
  706. bind_[8].is_unsigned = MLM_TRUE;
  707. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  708. // reasons, see memset() above
  709. // fqdn_fwd: boolean
  710. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  711. bind_[9].buffer = reinterpret_cast<char*>(&lease_->fqdn_fwd_);
  712. bind_[9].is_unsigned = MLM_TRUE;
  713. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  714. // reasons, see memset() above
  715. // fqdn_rev: boolean
  716. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  717. bind_[10].buffer = reinterpret_cast<char*>(&lease_->fqdn_rev_);
  718. bind_[10].is_unsigned = MLM_TRUE;
  719. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  720. // reasons, see memset() above
  721. // hostname: varchar(255)
  722. bind_[11].buffer_type = MYSQL_TYPE_VARCHAR;
  723. bind_[11].buffer = const_cast<char*>(lease_->hostname_.c_str());
  724. bind_[11].buffer_length = lease_->hostname_.length();
  725. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  726. // reasons, see memset() above
  727. // Add the error flags
  728. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  729. // .. and check that we have the numbers correct at compile time.
  730. BOOST_STATIC_ASSERT(11 < LEASE_COLUMNS);
  731. // Add the data to the vector. Note the end element is one after the
  732. // end of the array.
  733. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  734. }
  735. /// @brief Create BIND array to receive data
  736. ///
  737. /// Creates a MYSQL_BIND array to receive Lease6 data from the database.
  738. /// After data is successfully received, getLeaseData() is used to copy
  739. /// it to a Lease6 object.
  740. ///
  741. /// @return Vector of MySQL BIND objects passed to the MySQL data retrieval
  742. /// functions.
  743. std::vector<MYSQL_BIND> createBindForReceive() {
  744. // Initialize MYSQL_BIND array.
  745. // It sets all fields, including is_null, to zero, so we need to set
  746. // is_null only if it should be true. This gives up minor performance
  747. // benefit while being safe approach. For improved readability, the
  748. // code that explicitly sets is_null is there, but is commented out.
  749. memset(bind_, 0, sizeof(bind_));
  750. // address: varchar(39)
  751. // A Lease6_ address has a maximum of 39 characters. The array is
  752. // one byte longer than this to guarantee that we can always null
  753. // terminate it whatever is returned.
  754. addr6_length_ = sizeof(addr6_buffer_) - 1;
  755. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  756. bind_[0].buffer = addr6_buffer_;
  757. bind_[0].buffer_length = addr6_length_;
  758. bind_[0].length = &addr6_length_;
  759. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  760. // reasons, see memset() above
  761. // client_id: varbinary(128)
  762. duid_length_ = sizeof(duid_buffer_);
  763. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  764. bind_[1].buffer = reinterpret_cast<char*>(duid_buffer_);
  765. bind_[1].buffer_length = duid_length_;
  766. bind_[1].length = &duid_length_;
  767. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  768. // reasons, see memset() above
  769. // lease_time: unsigned int
  770. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  771. bind_[2].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  772. bind_[2].is_unsigned = MLM_TRUE;
  773. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  774. // reasons, see memset() above
  775. // expire: timestamp
  776. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  777. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  778. bind_[3].buffer_length = sizeof(expire_);
  779. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  780. // reasons, see memset() above
  781. // subnet_id: unsigned int
  782. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  783. bind_[4].buffer = reinterpret_cast<char*>(&subnet_id_);
  784. bind_[4].is_unsigned = MLM_TRUE;
  785. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  786. // reasons, see memset() above
  787. // pref_lifetime: unsigned int
  788. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  789. bind_[5].buffer = reinterpret_cast<char*>(&pref_lifetime_);
  790. bind_[5].is_unsigned = MLM_TRUE;
  791. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  792. // reasons, see memset() above
  793. // lease_type: tinyint
  794. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  795. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  796. bind_[6].is_unsigned = MLM_TRUE;
  797. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  798. // reasons, see memset() above
  799. // iaid: unsigned int
  800. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  801. bind_[7].buffer = reinterpret_cast<char*>(&iaid_);
  802. bind_[7].is_unsigned = MLM_TRUE;
  803. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  804. // reasons, see memset() above
  805. // prefix_len: unsigned tinyint
  806. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  807. bind_[8].buffer = reinterpret_cast<char*>(&prefixlen_);
  808. bind_[8].is_unsigned = MLM_TRUE;
  809. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  810. // reasons, see memset() above
  811. // fqdn_fwd: boolean
  812. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  813. bind_[9].buffer = reinterpret_cast<char*>(&fqdn_fwd_);
  814. bind_[9].is_unsigned = MLM_TRUE;
  815. // bind_[9].is_null = &MLM_FALSE; // commented out for performance
  816. // reasons, see memset() above
  817. // fqdn_rev: boolean
  818. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  819. bind_[10].buffer = reinterpret_cast<char*>(&fqdn_rev_);
  820. bind_[10].is_unsigned = MLM_TRUE;
  821. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  822. // reasons, see memset() above
  823. // hostname: varchar(255)
  824. hostname_length_ = sizeof(hostname_buffer_);
  825. bind_[11].buffer_type = MYSQL_TYPE_STRING;
  826. bind_[11].buffer = reinterpret_cast<char*>(hostname_buffer_);
  827. bind_[11].buffer_length = hostname_length_;
  828. bind_[11].length = &hostname_length_;
  829. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  830. // reasons, see memset() above
  831. // Add the error flags
  832. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  833. // .. and check that we have the numbers correct at compile time.
  834. BOOST_STATIC_ASSERT(11 < LEASE_COLUMNS);
  835. // Add the data to the vector. Note the end element is one after the
  836. // end of the array.
  837. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  838. }
  839. /// @brief Copy Received Data into Lease6 Object
  840. ///
  841. /// Called after the MYSQL_BIND array created by createBindForReceive()
  842. /// has been used, this copies data from the internal member variables
  843. /// into a Lease6 object.
  844. ///
  845. /// @return Lease6Ptr Pointer to a Lease6 object holding the relevant
  846. /// data.
  847. ///
  848. /// @throw isc::BadValue Unable to convert Lease Type value in database
  849. Lease6Ptr getLeaseData() {
  850. // The address buffer is declared larger than the buffer size passed
  851. // to the access function so that we can always append a null byte.
  852. // Create the IOAddress object corresponding to the received data.
  853. addr6_buffer_[addr6_length_] = '\0';
  854. std::string address = addr6_buffer_;
  855. isc::asiolink::IOAddress addr(address);
  856. // Set the lease type in a variable of the appropriate data type, which
  857. // has been initialized with an arbitrary (but valid) value.
  858. Lease::Type type = Lease::TYPE_NA;
  859. switch (lease_type_) {
  860. case Lease::TYPE_NA:
  861. type = Lease::TYPE_NA;
  862. break;
  863. case Lease::TYPE_TA:
  864. type = Lease::TYPE_TA;
  865. break;
  866. case Lease::TYPE_PD:
  867. type = Lease::TYPE_PD;
  868. break;
  869. default:
  870. isc_throw(BadValue, "invalid lease type returned (" <<
  871. static_cast<int>(lease_type_) << ") for lease with "
  872. << "address " << address << ". Only 0, 1, or 2 are "
  873. << "allowed.");
  874. }
  875. // Set up DUID,
  876. DuidPtr duid_ptr(new DUID(duid_buffer_, duid_length_));
  877. // Hostname is passed to Lease6 as a string object, so we have to
  878. // create it from the hostname buffer and length.
  879. std::string hostname(hostname_buffer_,
  880. hostname_buffer_ + hostname_length_);
  881. /// @todo: HWAddr is not yet stored, see ticket #3556.
  882. HWAddrPtr hwaddr;
  883. // Create the lease and set the cltt (after converting from the
  884. // expire time retrieved from the database).
  885. Lease6Ptr result(new Lease6(type, addr, duid_ptr, iaid_,
  886. pref_lifetime_, valid_lifetime_, 0, 0,
  887. subnet_id_, fqdn_fwd_, fqdn_rev_,
  888. hostname, hwaddr, prefixlen_));
  889. time_t cltt = 0;
  890. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  891. result->cltt_ = cltt;
  892. return (result);
  893. }
  894. /// @brief Return columns in error
  895. ///
  896. /// If an error is returned from a fetch (in particular, a truncated
  897. /// status), this method can be called to get the names of the fields in
  898. /// error. It returns a string comprising the names of the fields
  899. /// separated by commas. In the case of there being no error indicators
  900. /// set, it returns the string "(None)".
  901. ///
  902. /// @return Comma-separated list of columns in error, or the string
  903. /// "(None)".
  904. std::string getErrorColumns() {
  905. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  906. }
  907. private:
  908. // Note: All array lengths are equal to the corresponding variable in the
  909. // schema.
  910. // Note: arrays are declared fixed length for speed of creation
  911. std::string addr6_; ///< String form of address
  912. char addr6_buffer_[ADDRESS6_TEXT_MAX_LEN + 1]; ///< Character
  913. ///< array form of V6 address
  914. unsigned long addr6_length_; ///< Length of the address
  915. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  916. std::string columns_[LEASE_COLUMNS];///< Column names
  917. std::vector<uint8_t> duid_; ///< Client identification
  918. uint8_t duid_buffer_[DUID::MAX_DUID_LEN]; ///< Buffer form of DUID
  919. unsigned long duid_length_; ///< Length of the DUID
  920. my_bool error_[LEASE_COLUMNS]; ///< Error indicators
  921. MYSQL_TIME expire_; ///< Lease expiry time
  922. uint32_t iaid_; ///< Identity association ID
  923. Lease6Ptr lease_; ///< Pointer to lease object
  924. uint8_t lease_type_; ///< Lease type
  925. uint8_t prefixlen_; ///< Prefix length
  926. uint32_t pref_lifetime_; ///< Preferred lifetime
  927. uint32_t subnet_id_; ///< Subnet identification
  928. uint32_t valid_lifetime_; ///< Lease time
  929. my_bool fqdn_fwd_; ///< Has forward DNS update been
  930. ///< performed
  931. my_bool fqdn_rev_; ///< Has reverse DNS update been
  932. ///< performed
  933. char hostname_buffer_[HOSTNAME_MAX_LEN];
  934. ///< Client hostname
  935. unsigned long hostname_length_; ///< Client hostname length
  936. };
  937. /// @brief Fetch and Release MySQL Results
  938. ///
  939. /// When a MySQL statement is expected, to fetch the results the function
  940. /// mysql_stmt_fetch() must be called. As well as getting data, this
  941. /// allocates internal state. Subsequent calls to mysql_stmt_fetch can be
  942. /// made, but when all the data is retrieved, mysql_stmt_free_result must be
  943. /// called to free up the resources allocated.
  944. ///
  945. /// Created prior to the first fetch, this class's destructor calls
  946. /// mysql_stmt_free_result, so eliminating the need for an explicit release
  947. /// in the method calling mysql_stmt_free_result. In this way, it guarantees
  948. /// that the resources are released even if the MySqlLeaseMgr method concerned
  949. /// exits via an exception.
  950. class MySqlFreeResult {
  951. public:
  952. /// @brief Constructor
  953. ///
  954. /// Store the pointer to the statement for which data is being fetched.
  955. ///
  956. /// Note that according to the MySQL documentation, mysql_stmt_free_result
  957. /// only releases resources if a cursor has been allocated for the
  958. /// statement. This implies that it is a no-op if none have been. Either
  959. /// way, any error from mysql_stmt_free_result is ignored. (Generating
  960. /// an exception is not much help, as it will only confuse things if the
  961. /// method calling mysql_stmt_fetch is exiting via an exception.)
  962. MySqlFreeResult(MYSQL_STMT* statement) : statement_(statement)
  963. {}
  964. /// @brief Destructor
  965. ///
  966. /// Frees up fetch context if a fetch has been successfully executed.
  967. ~MySqlFreeResult() {
  968. (void) mysql_stmt_free_result(statement_);
  969. }
  970. private:
  971. MYSQL_STMT* statement_; ///< Statement for which results are freed
  972. };
  973. // MySqlLeaseMgr Constructor and Destructor
  974. MySqlLeaseMgr::MySqlLeaseMgr(const LeaseMgr::ParameterMap& parameters)
  975. : LeaseMgr(parameters) {
  976. // Open the database.
  977. openDatabase();
  978. // Enable autocommit. To avoid a flush to disk on every commit, the global
  979. // parameter innodb_flush_log_at_trx_commit should be set to 2. This will
  980. // cause the changes to be written to the log, but flushed to disk in the
  981. // background every second. Setting the parameter to that value will speed
  982. // up the system, but at the risk of losing data if the system crashes.
  983. my_bool result = mysql_autocommit(mysql_, 1);
  984. if (result != 0) {
  985. isc_throw(DbOperationError, mysql_error(mysql_));
  986. }
  987. // Prepare all statements likely to be used.
  988. prepareStatements();
  989. // Create the exchange objects for use in exchanging data between the
  990. // program and the database.
  991. exchange4_.reset(new MySqlLease4Exchange());
  992. exchange6_.reset(new MySqlLease6Exchange());
  993. }
  994. MySqlLeaseMgr::~MySqlLeaseMgr() {
  995. // Free up the prepared statements, ignoring errors. (What would we do
  996. // about them? We're destroying this object and are not really concerned
  997. // with errors on a database connection that is about to go away.)
  998. for (int i = 0; i < statements_.size(); ++i) {
  999. if (statements_[i] != NULL) {
  1000. (void) mysql_stmt_close(statements_[i]);
  1001. statements_[i] = NULL;
  1002. }
  1003. }
  1004. // There is no need to close the database in this destructor: it is
  1005. // closed in the destructor of the mysql_ member variable.
  1006. }
  1007. // Time conversion methods.
  1008. //
  1009. // Note that the MySQL TIMESTAMP data type (used for "expire") converts data
  1010. // from the current timezone to UTC for storage, and from UTC to the current
  1011. // timezone for retrieval.
  1012. //
  1013. // This causes no problems providing that:
  1014. // a) cltt is given in local time
  1015. // b) We let the system take care of timezone conversion when converting
  1016. // from a time read from the database into a local time.
  1017. void
  1018. MySqlLeaseMgr::convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  1019. MYSQL_TIME& expire) {
  1020. // Calculate expiry time.
  1021. // @TODO: handle overflows
  1022. time_t expire_time = cltt + valid_lifetime;
  1023. // Convert to broken-out time
  1024. struct tm expire_tm;
  1025. (void) localtime_r(&expire_time, &expire_tm);
  1026. // Place in output expire structure.
  1027. expire.year = expire_tm.tm_year + 1900;
  1028. expire.month = expire_tm.tm_mon + 1; // Note different base
  1029. expire.day = expire_tm.tm_mday;
  1030. expire.hour = expire_tm.tm_hour;
  1031. expire.minute = expire_tm.tm_min;
  1032. expire.second = expire_tm.tm_sec;
  1033. expire.second_part = 0; // No fractional seconds
  1034. expire.neg = my_bool(0); // Not negative
  1035. }
  1036. void
  1037. MySqlLeaseMgr::convertFromDatabaseTime(const MYSQL_TIME& expire,
  1038. uint32_t valid_lifetime, time_t& cltt) {
  1039. // Copy across fields from MYSQL_TIME structure.
  1040. struct tm expire_tm;
  1041. memset(&expire_tm, 0, sizeof(expire_tm));
  1042. expire_tm.tm_year = expire.year - 1900;
  1043. expire_tm.tm_mon = expire.month - 1;
  1044. expire_tm.tm_mday = expire.day;
  1045. expire_tm.tm_hour = expire.hour;
  1046. expire_tm.tm_min = expire.minute;
  1047. expire_tm.tm_sec = expire.second;
  1048. expire_tm.tm_isdst = -1; // Let the system work out about DST
  1049. // Convert to local time
  1050. cltt = mktime(&expire_tm) - valid_lifetime;
  1051. }
  1052. // Open the database using the parameters passed to the constructor.
  1053. void
  1054. MySqlLeaseMgr::openDatabase() {
  1055. // Set up the values of the parameters
  1056. const char* host = "localhost";
  1057. string shost;
  1058. try {
  1059. shost = getParameter("host");
  1060. host = shost.c_str();
  1061. } catch (...) {
  1062. // No host. Fine, we'll use "localhost"
  1063. }
  1064. const char* user = NULL;
  1065. string suser;
  1066. try {
  1067. suser = getParameter("user");
  1068. user = suser.c_str();
  1069. } catch (...) {
  1070. // No user. Fine, we'll use NULL
  1071. }
  1072. const char* password = NULL;
  1073. string spassword;
  1074. try {
  1075. spassword = getParameter("password");
  1076. password = spassword.c_str();
  1077. } catch (...) {
  1078. // No password. Fine, we'll use NULL
  1079. }
  1080. const char* name = NULL;
  1081. string sname;
  1082. try {
  1083. sname = getParameter("name");
  1084. name = sname.c_str();
  1085. } catch (...) {
  1086. // No database name. Throw a "NoName" exception
  1087. isc_throw(NoDatabaseName, "must specified a name for the database");
  1088. }
  1089. // Set options for the connection:
  1090. //
  1091. // Automatic reconnection: after a period of inactivity, the client will
  1092. // disconnect from the database. This option causes it to automatically
  1093. // reconnect when another operation is about to be done.
  1094. my_bool auto_reconnect = MLM_TRUE;
  1095. int result = mysql_options(mysql_, MYSQL_OPT_RECONNECT, &auto_reconnect);
  1096. if (result != 0) {
  1097. isc_throw(DbOpenError, "unable to set auto-reconnect option: " <<
  1098. mysql_error(mysql_));
  1099. }
  1100. // Set SQL mode options for the connection: SQL mode governs how what
  1101. // constitutes insertable data for a given column, and how to handle
  1102. // invalid data. We want to ensure we get the strictest behavior and
  1103. // to reject invalid data with an error.
  1104. const char *sql_mode = "SET SESSION sql_mode ='STRICT_ALL_TABLES'";
  1105. result = mysql_options(mysql_, MYSQL_INIT_COMMAND, sql_mode);
  1106. if (result != 0) {
  1107. isc_throw(DbOpenError, "unable to set SQL mode options: " <<
  1108. mysql_error(mysql_));
  1109. }
  1110. // Open the database.
  1111. //
  1112. // The option CLIENT_FOUND_ROWS is specified so that in an UPDATE,
  1113. // the affected rows are the number of rows found that match the
  1114. // WHERE clause of the SQL statement, not the rows changed. The reason
  1115. // here is that MySQL apparently does not update a row if data has not
  1116. // changed and so the "affected rows" (retrievable from MySQL) is zero.
  1117. // This makes it hard to distinguish whether the UPDATE changed no rows
  1118. // because no row matching the WHERE clause was found, or because a
  1119. // row was found but no data was altered.
  1120. MYSQL* status = mysql_real_connect(mysql_, host, user, password, name,
  1121. 0, NULL, CLIENT_FOUND_ROWS);
  1122. if (status != mysql_) {
  1123. isc_throw(DbOpenError, mysql_error(mysql_));
  1124. }
  1125. }
  1126. // Prepared statement setup. The textual form of an SQL statement is stored
  1127. // in a vector of strings (text_statements_) and is used in the output of
  1128. // error messages. The SQL statement is also compiled into a "prepared
  1129. // statement" (stored in statements_), which avoids the overhead of compilation
  1130. // during use. As prepared statements have resources allocated to them, the
  1131. // class destructor explicitly destroys them.
  1132. void
  1133. MySqlLeaseMgr::prepareStatement(StatementIndex index, const char* text) {
  1134. // Validate that there is space for the statement in the statements array
  1135. // and that nothing has been placed there before.
  1136. if ((index >= statements_.size()) || (statements_[index] != NULL)) {
  1137. isc_throw(InvalidParameter, "invalid prepared statement index (" <<
  1138. static_cast<int>(index) << ") or indexed prepared " <<
  1139. "statement is not null");
  1140. }
  1141. // All OK, so prepare the statement
  1142. text_statements_[index] = std::string(text);
  1143. statements_[index] = mysql_stmt_init(mysql_);
  1144. if (statements_[index] == NULL) {
  1145. isc_throw(DbOperationError, "unable to allocate MySQL prepared "
  1146. "statement structure, reason: " << mysql_error(mysql_));
  1147. }
  1148. int status = mysql_stmt_prepare(statements_[index], text, strlen(text));
  1149. if (status != 0) {
  1150. isc_throw(DbOperationError, "unable to prepare MySQL statement <" <<
  1151. text << ">, reason: " << mysql_error(mysql_));
  1152. }
  1153. }
  1154. void
  1155. MySqlLeaseMgr::prepareStatements() {
  1156. // Allocate space for all statements
  1157. statements_.clear();
  1158. statements_.resize(NUM_STATEMENTS, NULL);
  1159. text_statements_.clear();
  1160. text_statements_.resize(NUM_STATEMENTS, std::string(""));
  1161. // Created the MySQL prepared statements for each DML statement.
  1162. for (int i = 0; tagged_statements[i].text != NULL; ++i) {
  1163. prepareStatement(tagged_statements[i].index,
  1164. tagged_statements[i].text);
  1165. }
  1166. }
  1167. // Add leases to the database. The two public methods accept a lease object
  1168. // (either V4 of V6), bind the contents to the appropriate prepared
  1169. // statement, then call common code to execute the statement.
  1170. bool
  1171. MySqlLeaseMgr::addLeaseCommon(StatementIndex stindex,
  1172. std::vector<MYSQL_BIND>& bind) {
  1173. // Bind the parameters to the statement
  1174. int status = mysql_stmt_bind_param(statements_[stindex], &bind[0]);
  1175. checkError(status, stindex, "unable to bind parameters");
  1176. // Execute the statement
  1177. status = mysql_stmt_execute(statements_[stindex]);
  1178. if (status != 0) {
  1179. // Failure: check for the special case of duplicate entry. If this is
  1180. // the case, we return false to indicate that the row was not added.
  1181. // Otherwise we throw an exception.
  1182. if (mysql_errno(mysql_) == ER_DUP_ENTRY) {
  1183. return (false);
  1184. }
  1185. checkError(status, stindex, "unable to execute");
  1186. }
  1187. // Insert succeeded
  1188. return (true);
  1189. }
  1190. bool
  1191. MySqlLeaseMgr::addLease(const Lease4Ptr& lease) {
  1192. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1193. DHCPSRV_MYSQL_ADD_ADDR4).arg(lease->addr_.toText());
  1194. // Create the MYSQL_BIND array for the lease
  1195. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1196. // ... and drop to common code.
  1197. return (addLeaseCommon(INSERT_LEASE4, bind));
  1198. }
  1199. bool
  1200. MySqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  1201. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1202. DHCPSRV_MYSQL_ADD_ADDR6).arg(lease->addr_.toText())
  1203. .arg(lease->type_);
  1204. // Create the MYSQL_BIND array for the lease
  1205. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1206. // ... and drop to common code.
  1207. return (addLeaseCommon(INSERT_LEASE6, bind));
  1208. }
  1209. // Extraction of leases from the database.
  1210. //
  1211. // All getLease() methods ultimately call getLeaseCollection(). This
  1212. // binds the input parameters passed to it with the appropriate prepared
  1213. // statement and executes the statement. It then gets the results from the
  1214. // database. getlease() methods that expect a single result back call it
  1215. // with the "single" parameter set true: this causes an exception to be
  1216. // generated if multiple records can be retrieved from the result set. (Such
  1217. // an occurrence either indicates corruption in the database, or that an
  1218. // assumption that a query can only return a single record is incorrect.)
  1219. // Methods that require a collection of records have "single" set to the
  1220. // default value of false. The logic is the same for both Lease4 and Lease6
  1221. // objects, so the code is templated.
  1222. //
  1223. // Methods that require a collection of objects access this method through
  1224. // two interface methods (also called getLeaseCollection()). These are
  1225. // short enough as to be defined in the header file: all they do is to supply
  1226. // the appropriate MySqlLeaseXExchange object depending on the type of the
  1227. // LeaseCollection objects passed to them.
  1228. //
  1229. // Methods that require a single object to be returned access the method
  1230. // through two interface methods (called getLease()). As well as supplying
  1231. // the appropriate exchange object, they convert between lease collection
  1232. // holding zero or one leases into an appropriate Lease object.
  1233. template <typename Exchange, typename LeaseCollection>
  1234. void MySqlLeaseMgr::getLeaseCollection(StatementIndex stindex,
  1235. MYSQL_BIND* bind,
  1236. Exchange& exchange,
  1237. LeaseCollection& result,
  1238. bool single) const {
  1239. // Bind the selection parameters to the statement
  1240. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1241. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1242. // Set up the MYSQL_BIND array for the data being returned and bind it to
  1243. // the statement.
  1244. std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
  1245. status = mysql_stmt_bind_result(statements_[stindex], &outbind[0]);
  1246. checkError(status, stindex, "unable to bind SELECT clause parameters");
  1247. // Execute the statement
  1248. status = mysql_stmt_execute(statements_[stindex]);
  1249. checkError(status, stindex, "unable to execute");
  1250. // Ensure that all the lease information is retrieved in one go to avoid
  1251. // overhead of going back and forth between client and server.
  1252. status = mysql_stmt_store_result(statements_[stindex]);
  1253. checkError(status, stindex, "unable to set up for storing all results");
  1254. // Set up the fetch "release" object to release resources associated
  1255. // with the call to mysql_stmt_fetch when this method exits, then
  1256. // retrieve the data.
  1257. MySqlFreeResult fetch_release(statements_[stindex]);
  1258. int count = 0;
  1259. while ((status = mysql_stmt_fetch(statements_[stindex])) == 0) {
  1260. try {
  1261. result.push_back(exchange->getLeaseData());
  1262. } catch (const isc::BadValue& ex) {
  1263. // Rethrow the exception with a bit more data.
  1264. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  1265. text_statements_[stindex] << ">");
  1266. }
  1267. if (single && (++count > 1)) {
  1268. isc_throw(MultipleRecords, "multiple records were found in the "
  1269. "database where only one was expected for query "
  1270. << text_statements_[stindex]);
  1271. }
  1272. }
  1273. // How did the fetch end?
  1274. if (status == 1) {
  1275. // Error - unable to fetch results
  1276. checkError(status, stindex, "unable to fetch results");
  1277. } else if (status == MYSQL_DATA_TRUNCATED) {
  1278. // Data truncated - throw an exception indicating what was at fault
  1279. isc_throw(DataTruncated, text_statements_[stindex]
  1280. << " returned truncated data: columns affected are "
  1281. << exchange->getErrorColumns());
  1282. }
  1283. }
  1284. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1285. Lease4Ptr& result) const {
  1286. // Create appropriate collection object and get all leases matching
  1287. // the selection criteria. The "single" paraeter is true to indicate
  1288. // that the called method should throw an exception if multiple
  1289. // matching records are found: this particular method is called when only
  1290. // one or zero matches is expected.
  1291. Lease4Collection collection;
  1292. getLeaseCollection(stindex, bind, exchange4_, collection, true);
  1293. // Return single record if present, else clear the lease.
  1294. if (collection.empty()) {
  1295. result.reset();
  1296. } else {
  1297. result = *collection.begin();
  1298. }
  1299. }
  1300. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1301. Lease6Ptr& result) const {
  1302. // Create appropriate collection object and get all leases matching
  1303. // the selection criteria. The "single" paraeter is true to indicate
  1304. // that the called method should throw an exception if multiple
  1305. // matching records are found: this particular method is called when only
  1306. // one or zero matches is expected.
  1307. Lease6Collection collection;
  1308. getLeaseCollection(stindex, bind, exchange6_, collection, true);
  1309. // Return single record if present, else clear the lease.
  1310. if (collection.empty()) {
  1311. result.reset();
  1312. } else {
  1313. result = *collection.begin();
  1314. }
  1315. }
  1316. // Basic lease access methods. Obtain leases from the database using various
  1317. // criteria.
  1318. Lease4Ptr
  1319. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
  1320. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1321. DHCPSRV_MYSQL_GET_ADDR4).arg(addr.toText());
  1322. // Set up the WHERE clause value
  1323. MYSQL_BIND inbind[1];
  1324. memset(inbind, 0, sizeof(inbind));
  1325. uint32_t addr4 = static_cast<uint32_t>(addr);
  1326. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1327. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1328. inbind[0].is_unsigned = MLM_TRUE;
  1329. // Get the data
  1330. Lease4Ptr result;
  1331. getLease(GET_LEASE4_ADDR, inbind, result);
  1332. return (result);
  1333. }
  1334. Lease4Collection
  1335. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr) const {
  1336. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1337. DHCPSRV_MYSQL_GET_HWADDR).arg(hwaddr.toText());
  1338. // Set up the WHERE clause value
  1339. MYSQL_BIND inbind[1];
  1340. memset(inbind, 0, sizeof(inbind));
  1341. // As "buffer" is "char*" - even though the data is being read - we need
  1342. // to cast away the "const"ness as well as reinterpreting the data as
  1343. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1344. // local variable, but as the data is only being read, this introduces
  1345. // an unnecessary copy).
  1346. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1347. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1348. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1349. inbind[0].buffer = reinterpret_cast<char*>(data);
  1350. inbind[0].buffer_length = hwaddr_length;
  1351. inbind[0].length = &hwaddr_length;
  1352. // Get the data
  1353. Lease4Collection result;
  1354. getLeaseCollection(GET_LEASE4_HWADDR, inbind, result);
  1355. return (result);
  1356. }
  1357. Lease4Ptr
  1358. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr, SubnetID subnet_id) const {
  1359. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1360. DHCPSRV_MYSQL_GET_SUBID_HWADDR)
  1361. .arg(subnet_id).arg(hwaddr.toText());
  1362. // Set up the WHERE clause value
  1363. MYSQL_BIND inbind[2];
  1364. memset(inbind, 0, sizeof(inbind));
  1365. // As "buffer" is "char*" - even though the data is being read - we need
  1366. // to cast away the "const"ness as well as reinterpreting the data as
  1367. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1368. // local variable, but as the data is only being read, this introduces
  1369. // an unnecessary copy).
  1370. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1371. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1372. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1373. inbind[0].buffer = reinterpret_cast<char*>(data);
  1374. inbind[0].buffer_length = hwaddr_length;
  1375. inbind[0].length = &hwaddr_length;
  1376. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1377. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1378. inbind[1].is_unsigned = MLM_TRUE;
  1379. // Get the data
  1380. Lease4Ptr result;
  1381. getLease(GET_LEASE4_HWADDR_SUBID, inbind, result);
  1382. return (result);
  1383. }
  1384. Lease4Collection
  1385. MySqlLeaseMgr::getLease4(const ClientId& clientid) const {
  1386. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1387. DHCPSRV_MYSQL_GET_CLIENTID).arg(clientid.toText());
  1388. // Set up the WHERE clause value
  1389. MYSQL_BIND inbind[1];
  1390. memset(inbind, 0, sizeof(inbind));
  1391. std::vector<uint8_t> client_data = clientid.getClientId();
  1392. unsigned long client_data_length = client_data.size();
  1393. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1394. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1395. inbind[0].buffer_length = client_data_length;
  1396. inbind[0].length = &client_data_length;
  1397. // Get the data
  1398. Lease4Collection result;
  1399. getLeaseCollection(GET_LEASE4_CLIENTID, inbind, result);
  1400. return (result);
  1401. }
  1402. Lease4Ptr
  1403. MySqlLeaseMgr::getLease4(const ClientId&, const HWAddr&, SubnetID) const {
  1404. /// This function is currently not implemented because allocation engine
  1405. /// searches for the lease using HW address or client identifier.
  1406. /// It never uses both parameters in the same time. We need to
  1407. /// consider if this function is needed at all.
  1408. isc_throw(NotImplemented, "The MySqlLeaseMgr::getLease4 function was"
  1409. " called, but it is not implemented");
  1410. }
  1411. Lease4Ptr
  1412. MySqlLeaseMgr::getLease4(const ClientId& clientid, SubnetID subnet_id) const {
  1413. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1414. DHCPSRV_MYSQL_GET_SUBID_CLIENTID)
  1415. .arg(subnet_id).arg(clientid.toText());
  1416. // Set up the WHERE clause value
  1417. MYSQL_BIND inbind[2];
  1418. memset(inbind, 0, sizeof(inbind));
  1419. std::vector<uint8_t> client_data = clientid.getClientId();
  1420. unsigned long client_data_length = client_data.size();
  1421. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1422. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1423. inbind[0].buffer_length = client_data_length;
  1424. inbind[0].length = &client_data_length;
  1425. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1426. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1427. inbind[1].is_unsigned = MLM_TRUE;
  1428. // Get the data
  1429. Lease4Ptr result;
  1430. getLease(GET_LEASE4_CLIENTID_SUBID, inbind, result);
  1431. return (result);
  1432. }
  1433. Lease6Ptr
  1434. MySqlLeaseMgr::getLease6(Lease::Type lease_type,
  1435. const isc::asiolink::IOAddress& addr) const {
  1436. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1437. DHCPSRV_MYSQL_GET_ADDR6).arg(addr.toText())
  1438. .arg(lease_type);
  1439. // Set up the WHERE clause value
  1440. MYSQL_BIND inbind[2];
  1441. memset(inbind, 0, sizeof(inbind));
  1442. std::string addr6 = addr.toText();
  1443. unsigned long addr6_length = addr6.size();
  1444. // See the earlier description of the use of "const_cast" when accessing
  1445. // the address for an explanation of the reason.
  1446. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1447. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1448. inbind[0].buffer_length = addr6_length;
  1449. inbind[0].length = &addr6_length;
  1450. // LEASE_TYPE
  1451. inbind[1].buffer_type = MYSQL_TYPE_TINY;
  1452. inbind[1].buffer = reinterpret_cast<char*>(&lease_type);
  1453. inbind[1].is_unsigned = MLM_TRUE;
  1454. Lease6Ptr result;
  1455. getLease(GET_LEASE6_ADDR, inbind, result);
  1456. return (result);
  1457. }
  1458. Lease6Collection
  1459. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1460. const DUID& duid, uint32_t iaid) const {
  1461. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1462. DHCPSRV_MYSQL_GET_IAID_DUID).arg(iaid).arg(duid.toText())
  1463. .arg(lease_type);
  1464. // Set up the WHERE clause value
  1465. MYSQL_BIND inbind[3];
  1466. memset(inbind, 0, sizeof(inbind));
  1467. // In the following statement, the DUID is being read. However, the
  1468. // MySQL C interface does not use "const", so the "buffer" element
  1469. // is declared as "char*" instead of "const char*". To resolve this,
  1470. // the "const" is discarded before the uint8_t* is cast to char*.
  1471. //
  1472. // Note that the const_cast could be avoided by copying the DUID to
  1473. // a writeable buffer and storing the address of that in the "buffer"
  1474. // element. However, this introduces a copy operation (with additional
  1475. // overhead) purely to get round the structures introduced by design of
  1476. // the MySQL interface (which uses the area pointed to by "buffer" as
  1477. // input when specifying query parameters and as output when retrieving
  1478. // data). For that reason, "const_cast" has been used.
  1479. const vector<uint8_t>& duid_vector = duid.getDuid();
  1480. unsigned long duid_length = duid_vector.size();
  1481. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1482. inbind[0].buffer = reinterpret_cast<char*>(
  1483. const_cast<uint8_t*>(&duid_vector[0]));
  1484. inbind[0].buffer_length = duid_length;
  1485. inbind[0].length = &duid_length;
  1486. // IAID
  1487. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1488. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1489. inbind[1].is_unsigned = MLM_TRUE;
  1490. // LEASE_TYPE
  1491. inbind[2].buffer_type = MYSQL_TYPE_TINY;
  1492. inbind[2].buffer = reinterpret_cast<char*>(&lease_type);
  1493. inbind[2].is_unsigned = MLM_TRUE;
  1494. // ... and get the data
  1495. Lease6Collection result;
  1496. getLeaseCollection(GET_LEASE6_DUID_IAID, inbind, result);
  1497. return (result);
  1498. }
  1499. Lease6Collection
  1500. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1501. const DUID& duid, uint32_t iaid,
  1502. SubnetID subnet_id) const {
  1503. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1504. DHCPSRV_MYSQL_GET_IAID_SUBID_DUID)
  1505. .arg(iaid).arg(subnet_id).arg(duid.toText())
  1506. .arg(lease_type);
  1507. // Set up the WHERE clause value
  1508. MYSQL_BIND inbind[4];
  1509. memset(inbind, 0, sizeof(inbind));
  1510. // See the earlier description of the use of "const_cast" when accessing
  1511. // the DUID for an explanation of the reason.
  1512. const vector<uint8_t>& duid_vector = duid.getDuid();
  1513. unsigned long duid_length = duid_vector.size();
  1514. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1515. inbind[0].buffer = reinterpret_cast<char*>(
  1516. const_cast<uint8_t*>(&duid_vector[0]));
  1517. inbind[0].buffer_length = duid_length;
  1518. inbind[0].length = &duid_length;
  1519. // IAID
  1520. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1521. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1522. inbind[1].is_unsigned = MLM_TRUE;
  1523. // Subnet ID
  1524. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  1525. inbind[2].buffer = reinterpret_cast<char*>(&subnet_id);
  1526. inbind[2].is_unsigned = MLM_TRUE;
  1527. // LEASE_TYPE
  1528. inbind[3].buffer_type = MYSQL_TYPE_TINY;
  1529. inbind[3].buffer = reinterpret_cast<char*>(&lease_type);
  1530. inbind[3].is_unsigned = MLM_TRUE;
  1531. // ... and get the data
  1532. Lease6Collection result;
  1533. getLeaseCollection(GET_LEASE6_DUID_IAID_SUBID, inbind, result);
  1534. return (result);
  1535. }
  1536. // Update lease methods. These comprise common code that handles the actual
  1537. // update, and type-specific methods that set up the parameters for the prepared
  1538. // statement depending on the type of lease.
  1539. template <typename LeasePtr>
  1540. void
  1541. MySqlLeaseMgr::updateLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind,
  1542. const LeasePtr& lease) {
  1543. // Bind the parameters to the statement
  1544. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1545. checkError(status, stindex, "unable to bind parameters");
  1546. // Execute
  1547. status = mysql_stmt_execute(statements_[stindex]);
  1548. checkError(status, stindex, "unable to execute");
  1549. // See how many rows were affected. The statement should only update a
  1550. // single row.
  1551. int affected_rows = mysql_stmt_affected_rows(statements_[stindex]);
  1552. if (affected_rows == 0) {
  1553. isc_throw(NoSuchLease, "unable to update lease for address " <<
  1554. lease->addr_ << " as it does not exist");
  1555. } else if (affected_rows > 1) {
  1556. // Should not happen - primary key constraint should only have selected
  1557. // one row.
  1558. isc_throw(DbOperationError, "apparently updated more than one lease "
  1559. "that had the address " << lease->addr_);
  1560. }
  1561. }
  1562. void
  1563. MySqlLeaseMgr::updateLease4(const Lease4Ptr& lease) {
  1564. const StatementIndex stindex = UPDATE_LEASE4;
  1565. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1566. DHCPSRV_MYSQL_UPDATE_ADDR4).arg(lease->addr_.toText());
  1567. // Create the MYSQL_BIND array for the data being updated
  1568. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1569. // Set up the WHERE clause and append it to the MYSQL_BIND array
  1570. MYSQL_BIND where;
  1571. memset(&where, 0, sizeof(where));
  1572. uint32_t addr4 = static_cast<uint32_t>(lease->addr_);
  1573. where.buffer_type = MYSQL_TYPE_LONG;
  1574. where.buffer = reinterpret_cast<char*>(&addr4);
  1575. where.is_unsigned = MLM_TRUE;
  1576. bind.push_back(where);
  1577. // Drop to common update code
  1578. updateLeaseCommon(stindex, &bind[0], lease);
  1579. }
  1580. void
  1581. MySqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  1582. const StatementIndex stindex = UPDATE_LEASE6;
  1583. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1584. DHCPSRV_MYSQL_UPDATE_ADDR6).arg(lease->addr_.toText())
  1585. .arg(lease->type_);
  1586. // Create the MYSQL_BIND array for the data being updated
  1587. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1588. // Set up the WHERE clause value
  1589. MYSQL_BIND where;
  1590. memset(&where, 0, sizeof(where));
  1591. std::string addr6 = lease->addr_.toText();
  1592. unsigned long addr6_length = addr6.size();
  1593. // See the earlier description of the use of "const_cast" when accessing
  1594. // the address for an explanation of the reason.
  1595. where.buffer_type = MYSQL_TYPE_STRING;
  1596. where.buffer = const_cast<char*>(addr6.c_str());
  1597. where.buffer_length = addr6_length;
  1598. where.length = &addr6_length;
  1599. bind.push_back(where);
  1600. // Drop to common update code
  1601. updateLeaseCommon(stindex, &bind[0], lease);
  1602. }
  1603. // Delete lease methods. Similar to other groups of methods, these comprise
  1604. // a per-type method that sets up the relevant MYSQL_BIND array (in this
  1605. // case, a single method for both V4 and V6 addresses) and a common method that
  1606. // handles the common processing.
  1607. bool
  1608. MySqlLeaseMgr::deleteLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind) {
  1609. // Bind the input parameters to the statement
  1610. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1611. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1612. // Execute
  1613. status = mysql_stmt_execute(statements_[stindex]);
  1614. checkError(status, stindex, "unable to execute");
  1615. // See how many rows were affected. Note that the statement may delete
  1616. // multiple rows.
  1617. return (mysql_stmt_affected_rows(statements_[stindex]) > 0);
  1618. }
  1619. bool
  1620. MySqlLeaseMgr::deleteLease(const isc::asiolink::IOAddress& addr) {
  1621. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1622. DHCPSRV_MYSQL_DELETE_ADDR).arg(addr.toText());
  1623. // Set up the WHERE clause value
  1624. MYSQL_BIND inbind[1];
  1625. memset(inbind, 0, sizeof(inbind));
  1626. if (addr.isV4()) {
  1627. uint32_t addr4 = static_cast<uint32_t>(addr);
  1628. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1629. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1630. inbind[0].is_unsigned = MLM_TRUE;
  1631. return (deleteLeaseCommon(DELETE_LEASE4, inbind));
  1632. } else {
  1633. std::string addr6 = addr.toText();
  1634. unsigned long addr6_length = addr6.size();
  1635. // See the earlier description of the use of "const_cast" when accessing
  1636. // the address for an explanation of the reason.
  1637. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1638. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1639. inbind[0].buffer_length = addr6_length;
  1640. inbind[0].length = &addr6_length;
  1641. return (deleteLeaseCommon(DELETE_LEASE6, inbind));
  1642. }
  1643. }
  1644. // Miscellaneous database methods.
  1645. std::string
  1646. MySqlLeaseMgr::getName() const {
  1647. std::string name = "";
  1648. try {
  1649. name = getParameter("name");
  1650. } catch (...) {
  1651. // Return an empty name
  1652. }
  1653. return (name);
  1654. }
  1655. std::string
  1656. MySqlLeaseMgr::getDescription() const {
  1657. return (std::string("MySQL Database"));
  1658. }
  1659. std::pair<uint32_t, uint32_t>
  1660. MySqlLeaseMgr::getVersion() const {
  1661. const StatementIndex stindex = GET_VERSION;
  1662. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1663. DHCPSRV_MYSQL_GET_VERSION);
  1664. uint32_t major; // Major version number
  1665. uint32_t minor; // Minor version number
  1666. // Execute the prepared statement
  1667. int status = mysql_stmt_execute(statements_[stindex]);
  1668. if (status != 0) {
  1669. isc_throw(DbOperationError, "unable to execute <"
  1670. << text_statements_[stindex] << "> - reason: " <<
  1671. mysql_error(mysql_));
  1672. }
  1673. // Bind the output of the statement to the appropriate variables.
  1674. MYSQL_BIND bind[2];
  1675. memset(bind, 0, sizeof(bind));
  1676. bind[0].buffer_type = MYSQL_TYPE_LONG;
  1677. bind[0].is_unsigned = 1;
  1678. bind[0].buffer = &major;
  1679. bind[0].buffer_length = sizeof(major);
  1680. bind[1].buffer_type = MYSQL_TYPE_LONG;
  1681. bind[1].is_unsigned = 1;
  1682. bind[1].buffer = &minor;
  1683. bind[1].buffer_length = sizeof(minor);
  1684. status = mysql_stmt_bind_result(statements_[stindex], bind);
  1685. if (status != 0) {
  1686. isc_throw(DbOperationError, "unable to bind result set: " <<
  1687. mysql_error(mysql_));
  1688. }
  1689. // Fetch the data and set up the "release" object to release associated
  1690. // resources when this method exits then retrieve the data.
  1691. MySqlFreeResult fetch_release(statements_[stindex]);
  1692. status = mysql_stmt_fetch(statements_[stindex]);
  1693. if (status != 0) {
  1694. isc_throw(DbOperationError, "unable to obtain result set: " <<
  1695. mysql_error(mysql_));
  1696. }
  1697. return (std::make_pair(major, minor));
  1698. }
  1699. void
  1700. MySqlLeaseMgr::commit() {
  1701. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_COMMIT);
  1702. if (mysql_commit(mysql_) != 0) {
  1703. isc_throw(DbOperationError, "commit failed: " << mysql_error(mysql_));
  1704. }
  1705. }
  1706. void
  1707. MySqlLeaseMgr::rollback() {
  1708. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_ROLLBACK);
  1709. if (mysql_rollback(mysql_) != 0) {
  1710. isc_throw(DbOperationError, "rollback failed: " << mysql_error(mysql_));
  1711. }
  1712. }
  1713. }; // end of isc::dhcp namespace
  1714. }; // end of isc namespace