mysql_lease_mgr.cc 67 KB

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