mysql_lease_mgr.cc 92 KB

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