mysql_lease_mgr.cc 90 KB

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