ECAttachmentStorage.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. /*
  2. * Copyright 2005 - 2016 Zarafa and its licensors
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU Affero General Public License, version 3,
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Affero General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Affero General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. #include <kopano/platform.h>
  18. #include <stdexcept>
  19. #include <climits>
  20. #include <mapidefs.h>
  21. #include <cerrno>
  22. #include <algorithm>
  23. #include <kopano/lockhelper.hpp>
  24. #include <fcntl.h>
  25. #include <zlib.h>
  26. #include <ECSerializer.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <unistd.h>
  30. #include "ECAttachmentStorage.h"
  31. #include "SOAPUtils.h"
  32. #include <kopano/ECLogger.h>
  33. #include <kopano/MAPIErrors.h>
  34. #include <mapitags.h>
  35. #include <kopano/stringutil.h>
  36. #include "StreamUtil.h"
  37. #include "ECS3Attachment.h"
  38. namespace KC {
  39. // chunk size for attachment blobs, must be equal or larger than MAX, MAX may never shrink below 384*1024.
  40. #define CHUNK_SIZE (384 * 1024)
  41. // as adviced by http://www.zlib.net/manual.html we use a 128KB buffer; default is only 8KB
  42. #define ZLIB_BUFFER_SIZE std::max(CHUNK_SIZE, 128 * 1024)
  43. /*
  44. * Locking requirements of ECAttachmentStorage:
  45. * In the case of ECAttachmentStorage locking to protect against concurrent access is futile.
  46. * The theory is as follows:
  47. * If 2 users have a reference to the same attachment, neither can delete the mail causing
  48. * the other person to lose the attachment. This means that concurrent copy and delete actions
  49. * are possible on the same attachment. The only case where this does not hold is the case
  50. * when a user deletes the mail he is copying at the same time and that this is the last mail
  51. * which references that specific attachment.
  52. * The only race condition which might occur is that the dagent delivers a mail with attachment,
  53. * the server returns the attachment id back to the dagent, but the user for whom the message
  54. * was intended deletes the mail & attachment. In this case the dagent will no longer send the
  55. * attachment but only the attachment id. When that happens the server can return an error
  56. * and simply request the dagent to resend the attachment and to obtain a new attachment id.
  57. */
  58. // Generic Attachment storage
  59. ECAttachmentStorage::ECAttachmentStorage(ECDatabase *lpDatabase, unsigned int ulCompressionLevel)
  60. : m_lpDatabase(lpDatabase)
  61. {
  62. m_ulRef = 0;
  63. m_bFileCompression = ulCompressionLevel != 0;
  64. if (ulCompressionLevel > Z_BEST_COMPRESSION)
  65. ulCompressionLevel = Z_BEST_COMPRESSION;
  66. m_CompressionLevel = stringify(ulCompressionLevel);
  67. }
  68. ULONG ECAttachmentStorage::AddRef() {
  69. scoped_lock lk(m_refcnt_lock);
  70. return ++m_ulRef;
  71. }
  72. ULONG ECAttachmentStorage::Release() {
  73. ulock_normal l_ref(m_refcnt_lock);
  74. ULONG ulRef = --m_ulRef;
  75. l_ref.unlock();
  76. if (m_ulRef == 0)
  77. delete this;
  78. return ulRef;
  79. }
  80. /**
  81. * Create an attachment storage object which either uses the
  82. * ECDatabase or a filesystem as storage.
  83. *
  84. * @param[in] lpDatabase Database class that stays valid during the lifetime of the returned ECAttachmentStorage
  85. * @param[in] lpConfig The server configuration object
  86. * @param[out] lppAttachmentStorage The attachment storage object
  87. *
  88. * @return Kopano error code
  89. * @retval KCERR_DATABASE_ERROR given database pointer wasn't valid
  90. */
  91. ECRESULT ECAttachmentStorage::CreateAttachmentStorage(ECDatabase *lpDatabase,
  92. ECConfig *lpConfig, ECAttachmentStorage **lppAttachmentStorage)
  93. {
  94. ECAttachmentStorage *lpAttachmentStorage = NULL;
  95. if (lpDatabase == NULL) {
  96. ec_log_err("ECAttachmentStorage::CreateAttachmentStorage(): DB not available yet");
  97. return KCERR_DATABASE_ERROR; // somebody called this function too soon.
  98. }
  99. const char *ans = lpConfig->GetSetting("attachment_storage");
  100. const char *dir = lpConfig->GetSetting("attachment_path");
  101. if (dir == NULL) {
  102. ec_log_err("No attachment_path set despite attachment_storage=files. Falling back to database attachments.");
  103. ans = NULL;
  104. }
  105. if (ans != NULL && strcmp(ans, "files") == 0) {
  106. const char *const sync_files_par = lpConfig->GetSetting("attachment_files_fsync");
  107. bool sync_files = sync_files_par == NULL || strcasecmp(sync_files_par, "yes") == 0;
  108. const char *comp = lpConfig->GetSetting("attachment_compression");
  109. unsigned int complvl = (comp == NULL) ? 0 : strtoul(comp, NULL, 0);
  110. lpAttachmentStorage = new ECFileAttachment(lpDatabase, dir, complvl, sync_files);
  111. #ifdef HAVE_LIBS3_H
  112. } else if (ans != NULL && strcmp(ans, "s3") == 0) {
  113. try {
  114. lpAttachmentStorage = new ECS3Attachment(lpDatabase,
  115. lpConfig->GetSetting("attachment_s3_protocol"),
  116. lpConfig->GetSetting("attachment_s3_uristyle"),
  117. lpConfig->GetSetting("attachment_s3_accesskeyid"),
  118. lpConfig->GetSetting("attachment_s3_secretaccesskey"),
  119. lpConfig->GetSetting("attachment_s3_bucketname"),
  120. lpConfig->GetSetting("attachment_s3_region"),
  121. lpConfig->GetSetting("attachment_path"),
  122. strtol(lpConfig->GetSetting("attachment_compression"), NULL, 0));
  123. } catch (std::runtime_error &e) {
  124. ec_log_warn("Cannot instantiate ECS3Attachment: %s", e.what());
  125. return KCERR_DATABASE_ERROR;
  126. }
  127. #endif
  128. } else {
  129. lpAttachmentStorage = new ECDatabaseAttachment(lpDatabase);
  130. }
  131. lpAttachmentStorage->AddRef();
  132. *lppAttachmentStorage = lpAttachmentStorage;
  133. return erSuccess;
  134. }
  135. /**
  136. * Gets the instance id for a given hierarchy id and prop tag.
  137. *
  138. * @param[in] ulObjId Id from the hierarchy table
  139. * @param[in] ulTag Proptag of the instance data
  140. * @param[out] lpulInstanceId Id to use as instanceid
  141. *
  142. * @return Kopano error code
  143. */
  144. ECRESULT ECAttachmentStorage::GetSingleInstanceId(ULONG ulObjId, ULONG ulTag, ULONG *lpulInstanceId)
  145. {
  146. ECRESULT er = erSuccess;
  147. std::string strQuery;
  148. DB_RESULT lpDBResult;
  149. DB_ROW lpDBRow = NULL;
  150. strQuery =
  151. "SELECT `instanceid` "
  152. "FROM `singleinstances` "
  153. "WHERE `hierarchyid` = " + stringify(ulObjId) + " AND `tag` = " + stringify(ulTag) + " LIMIT 1";
  154. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  155. if (er != erSuccess) {
  156. ec_log_err("ECAttachmentStorage::GetSingleInstanceId(): DoSelect() failed %x", er);
  157. return er;
  158. }
  159. lpDBRow = m_lpDatabase->FetchRow(lpDBResult);
  160. if (lpDBRow == nullptr || lpDBRow[0] == nullptr)
  161. // ec_log_err("ECAttachmentStorage::GetSingleInstanceId(): FetchRow() failed %x", er);
  162. return KCERR_NOT_FOUND;
  163. if (lpulInstanceId)
  164. *lpulInstanceId = atoi(lpDBRow[0]);
  165. return erSuccess;
  166. }
  167. /**
  168. * Get all instance ids from a list of hierarchy ids, independant of
  169. * the proptag.
  170. * @todo this should be for a given tag, or we should return the tags too (map<InstanceID, ulPropId>)
  171. *
  172. * @param[in] lstObjIds list of hierarchy ids
  173. * @param[out] lstAttachIds list of unique corresponding instance ids
  174. *
  175. * @return Kopano error code
  176. */
  177. ECRESULT ECAttachmentStorage::GetSingleInstanceIds(const std::list<ULONG> &lstObjIds, std::list<ULONG> *lstAttachIds)
  178. {
  179. ECRESULT er = erSuccess;
  180. std::string strQuery;
  181. DB_RESULT lpDBResult;
  182. DB_ROW lpDBRow = NULL;
  183. std::list<ULONG> lstInstanceIds;
  184. /* No single instances were requested... */
  185. if (lstObjIds.empty())
  186. return erSuccess;
  187. strQuery =
  188. "SELECT DISTINCT `instanceid` "
  189. "FROM `singleinstances` "
  190. "WHERE `hierarchyid` IN (";
  191. for (auto i = lstObjIds.cbegin(); i != lstObjIds.cend(); ++i) {
  192. if (i != lstObjIds.cbegin())
  193. strQuery += ",";
  194. strQuery += stringify(*i);
  195. }
  196. strQuery += ")";
  197. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  198. if (er != erSuccess)
  199. return er;
  200. while ((lpDBRow = m_lpDatabase->FetchRow(lpDBResult)) != NULL) {
  201. if (lpDBRow[0] == NULL) {
  202. ec_log_err("ECAttachmentStorage::GetSingleInstanceIds(): column contains NULL");
  203. return KCERR_DATABASE_ERROR;
  204. }
  205. lstInstanceIds.push_back(atoi(lpDBRow[0]));
  206. }
  207. lstAttachIds->swap(lstInstanceIds);
  208. return erSuccess;
  209. }
  210. /**
  211. * Sets or replaces a row in the singleinstances table for a given
  212. * hierarchyid, tag and instanceid.
  213. *
  214. * @param[in] ulObjId HierarchyID to set/add instance id for
  215. * @param[in] ulInstanceId InstanceID to set for HierarchyID + Tag
  216. * @param[in] ulTag PropID to set/add instance id for
  217. *
  218. * @return Kopano error code
  219. */
  220. ECRESULT ECAttachmentStorage::SetSingleInstanceId(ULONG ulObjId, ULONG ulInstanceId, ULONG ulTag)
  221. {
  222. std::string strQuery;
  223. /*
  224. * Check if attachment reference exists, if not return error
  225. */
  226. if (!ExistAttachmentInstance(ulInstanceId))
  227. return KCERR_UNABLE_TO_COMPLETE;
  228. /*
  229. * Create Attachment reference, use provided attachment id
  230. */
  231. strQuery =
  232. "REPLACE INTO `singleinstances` (`instanceid`, `hierarchyid`, `tag`) VALUES"
  233. "(" + stringify(ulInstanceId) + ", " + stringify(ulObjId) + ", " + stringify(ulTag) + ")";
  234. return m_lpDatabase->DoInsert(strQuery, reinterpret_cast<unsigned int *>(&ulInstanceId));
  235. }
  236. /**
  237. * Get all HierarchyIDs for a given InstanceID.
  238. *
  239. * @param[in] ulInstanceId InstanceID to get HierarchyIDs for
  240. * @param[out] lplstObjIds List of all HierarchyIDs which link to the single instance
  241. *
  242. * @return Kopano error code
  243. */
  244. ECRESULT ECAttachmentStorage::GetSingleInstanceParents(ULONG ulInstanceId, std::list<ULONG> *lplstObjIds)
  245. {
  246. ECRESULT er = erSuccess;
  247. std::string strQuery;
  248. DB_RESULT lpDBResult;
  249. DB_ROW lpDBRow = NULL;
  250. std::list<ULONG> lstObjIds;
  251. strQuery =
  252. "SELECT DISTINCT `hierarchyid` "
  253. "FROM `singleinstances` "
  254. "WHERE `instanceid` = " + stringify(ulInstanceId);
  255. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  256. if (er != erSuccess)
  257. return er;
  258. while ((lpDBRow = m_lpDatabase->FetchRow(lpDBResult)) != NULL) {
  259. if (lpDBRow[0] == NULL) {
  260. ec_log_err("ECAttachmentStorage::GetSingleInstanceParents(): column contains NULL");
  261. return KCERR_DATABASE_ERROR;
  262. }
  263. lstObjIds.push_back(atoi(lpDBRow[0]));
  264. }
  265. lplstObjIds->swap(lstObjIds);
  266. return erSuccess;
  267. }
  268. /**
  269. * Checks if there are no references to a given InstanceID anymore.
  270. *
  271. * @param ulInstanceId InstanceID to check
  272. * @param bOrphan true if instance isn't referenced anymore
  273. *
  274. * @return Kopano error code
  275. */
  276. ECRESULT ECAttachmentStorage::IsOrphanedSingleInstance(ULONG ulInstanceId, bool *bOrphan)
  277. {
  278. ECRESULT er = erSuccess;
  279. std::string strQuery;
  280. DB_RESULT lpDBResult;
  281. DB_ROW lpDBRow = NULL;
  282. strQuery =
  283. "SELECT `instanceid` "
  284. "FROM `singleinstances` "
  285. "WHERE `instanceid` = " + stringify(ulInstanceId) + " "
  286. "LIMIT 1";
  287. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  288. if (er != erSuccess)
  289. return er;
  290. lpDBRow = m_lpDatabase->FetchRow(lpDBResult);
  291. /*
  292. * No results: Single Instance ID has been cleared (refcount = 0)
  293. */
  294. *bOrphan = (!lpDBRow || !lpDBRow[0]);
  295. return erSuccess;
  296. }
  297. /**
  298. * Make a list of all orphaned instances for a list of given InstanceIDs.
  299. *
  300. * @param[in] lstAttachments List of instance ids to check
  301. * @param[out] lplstOrphanedAttachments List of orphaned instance ids
  302. *
  303. * @return
  304. */
  305. ECRESULT ECAttachmentStorage::GetOrphanedSingleInstances(const std::list<ULONG> &lstInstanceIds, std::list<ULONG> *lplstOrphanedInstanceIds)
  306. {
  307. ECRESULT er = erSuccess;
  308. std::string strQuery;
  309. DB_RESULT lpDBResult;
  310. DB_ROW lpDBRow = NULL;
  311. strQuery =
  312. "SELECT DISTINCT `instanceid` "
  313. "FROM `singleinstances` "
  314. "WHERE `instanceid` IN ( ";
  315. for (auto i = lstInstanceIds.cbegin(); i != lstInstanceIds.cend(); ++i) {
  316. if (i != lstInstanceIds.cbegin())
  317. strQuery += ",";
  318. strQuery += stringify(*i);
  319. }
  320. strQuery += ")";
  321. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  322. if (er != erSuccess) {
  323. ec_log_err("ECAttachmentStorage::GetOrphanedSingleInstances(): DoSelect failed %x", er);
  324. return er;
  325. }
  326. /* First make a full copy of the list of Single Instance IDs */
  327. lplstOrphanedInstanceIds->assign(lstInstanceIds.begin(), lstInstanceIds.end());
  328. /*
  329. * Now filter out any Single Instance IDs which were returned in the query,
  330. * any results not returned by the query imply that the refcount is 0
  331. */
  332. while ((lpDBRow = m_lpDatabase->FetchRow(lpDBResult)) != NULL) {
  333. if (lpDBRow[0] == NULL) {
  334. ec_log_err("ECAttachmentStorage::GetOrphanedSingleInstances(): column contains NULL");
  335. return KCERR_DATABASE_ERROR;
  336. }
  337. lplstOrphanedInstanceIds->remove(atoi(lpDBRow[0]));
  338. }
  339. return erSuccess;
  340. }
  341. /**
  342. * For a given hierarchy id, check if this has a valid instance id
  343. *
  344. * @param[in] ulObjId hierarchy id to check instance for
  345. * @param[in] ulPropId property id to check instance for
  346. *
  347. * @return instance present
  348. */
  349. bool ECAttachmentStorage::ExistAttachment(ULONG ulObjId, ULONG ulPropId)
  350. {
  351. ECRESULT er = erSuccess;
  352. ULONG ulInstanceId = 0;
  353. /*
  354. * Convert object id into attachment id
  355. */
  356. er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
  357. if (er != erSuccess)
  358. return false;
  359. return ExistAttachmentInstance(ulInstanceId);
  360. }
  361. /**
  362. * Retrieve a large property from the storage, return data as blob.
  363. *
  364. * @param[in] soap Use soap for allocations. Returned data can directly be used to return to the client.
  365. * @param[in] ulObjId HierarchyID to load property for
  366. * @param[in] ulPropId property id to load
  367. * @param[out] lpiSize size of the property
  368. * @param[out] lppData data of the property
  369. *
  370. * @return Kopano error code
  371. */
  372. ECRESULT ECAttachmentStorage::LoadAttachment(struct soap *soap, ULONG ulObjId, ULONG ulPropId, size_t *lpiSize, unsigned char **lppData)
  373. {
  374. ECRESULT er;
  375. ULONG ulInstanceId = 0;
  376. /*
  377. * Convert object id into attachment id
  378. */
  379. er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
  380. if (er != erSuccess)
  381. return er;
  382. er = LoadAttachmentInstance(soap, ulInstanceId, lpiSize, lppData);
  383. if (er != erSuccess)
  384. return er;
  385. return erSuccess;
  386. }
  387. /**
  388. * Retrieve a large property from the storage, return data in a serializer.
  389. *
  390. * @param[in] ulObjId HierarchyID to load property for
  391. * @param[in] ulPropId property id to load
  392. * @param[out] lpiSize size of the property
  393. * @param[out] lpSink Write in this serializer
  394. *
  395. * @return Kopano error code
  396. */
  397. ECRESULT ECAttachmentStorage::LoadAttachment(ULONG ulObjId, ULONG ulPropId, size_t *lpiSize, ECSerializer *lpSink)
  398. {
  399. ECRESULT er;
  400. ULONG ulInstanceId = 0;
  401. /*
  402. * Convert object id into attachment id
  403. */
  404. er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
  405. if (er != erSuccess)
  406. return er;
  407. er = LoadAttachmentInstance(ulInstanceId, lpiSize, lpSink);
  408. if (er != erSuccess)
  409. return er;
  410. return erSuccess;
  411. }
  412. /**
  413. * Save a property of a specific object from a given blob, optionally remove previous data.
  414. *
  415. * @param[in] ulObjId HierarchyID of object
  416. * @param[in] ulPropId PropertyID to save
  417. * @param[in] bDeleteOld Remove old data before saving the new
  418. * @param[in] iSize size of lpData
  419. * @param[in] lpData data of the property
  420. * @param[out] lpulInstanceId InstanceID for the data (optional)
  421. *
  422. * @return Kopano error code
  423. */
  424. ECRESULT ECAttachmentStorage::SaveAttachment(ULONG ulObjId, ULONG ulPropId, bool bDeleteOld, size_t iSize, unsigned char *lpData, ULONG *lpulInstanceId)
  425. {
  426. ECRESULT er;
  427. ULONG ulInstanceId = 0;
  428. std::string strQuery;
  429. if (lpData == NULL)
  430. return KCERR_INVALID_PARAMETER;
  431. if (bDeleteOld) {
  432. /*
  433. * Call DeleteAttachment to decrease the refcount
  434. * and optionally delete the original attachment.
  435. */
  436. er = DeleteAttachment(ulObjId, ulPropId, true);
  437. if (er != erSuccess)
  438. return er;
  439. }
  440. /*
  441. * Create Attachment reference, detect new attachment id.
  442. */
  443. strQuery =
  444. "INSERT INTO `singleinstances` (`hierarchyid`, `tag`) VALUES"
  445. "(" + stringify(ulObjId) + ", " + stringify(ulPropId) + ")";
  446. er = m_lpDatabase->DoInsert(strQuery, (unsigned int*)&ulInstanceId);
  447. if (er != erSuccess) {
  448. ec_log_err("ECAttachmentStorage::SaveAttachment(): DoInsert failed %x", er);
  449. return er;
  450. }
  451. er = SaveAttachmentInstance(ulInstanceId, ulPropId, iSize, lpData);
  452. if (er != erSuccess)
  453. return er;
  454. if (lpulInstanceId)
  455. *lpulInstanceId = ulInstanceId;
  456. return erSuccess;
  457. }
  458. /**
  459. * Save a property of a specific object from a serializer, optionally remove previous data.
  460. *
  461. * @param[in] ulObjId HierarchyID of object
  462. * @param[in] ulPropId Property to save
  463. * @param[in] bDeleteOld Remove old data before saving the new
  464. * @param[in] iSize size in lpSource
  465. * @param[in] lpSource serializer to read data from
  466. * @param[out] lpulInstanceId InstanceID for the data (optional)
  467. *
  468. * @return Kopano error code
  469. */
  470. ECRESULT ECAttachmentStorage::SaveAttachment(ULONG ulObjId, ULONG ulPropId, bool bDeleteOld, size_t iSize, ECSerializer *lpSource, ULONG *lpulInstanceId)
  471. {
  472. ECRESULT er;
  473. ULONG ulInstanceId = 0;
  474. std::string strQuery;
  475. if (bDeleteOld) {
  476. /*
  477. * Call DeleteAttachment to decrease the refcount
  478. * and optionally delete the original attachment.
  479. */
  480. er = DeleteAttachment(ulObjId, ulPropId, true);
  481. if (er != erSuccess)
  482. return er;
  483. }
  484. /*
  485. * Create Attachment reference, detect new attachment id.
  486. */
  487. strQuery =
  488. "INSERT INTO `singleinstances` (`hierarchyid`, `tag`) VALUES"
  489. "(" + stringify(ulObjId) + ", " + stringify(ulPropId) + ")";
  490. er = m_lpDatabase->DoInsert(strQuery, (unsigned int*)&ulInstanceId);
  491. if (er != erSuccess) {
  492. ec_log_err("ECAttachmentStorage::SaveAttachment(): DoInsert failed %x", er);
  493. return er;
  494. }
  495. er = SaveAttachmentInstance(ulInstanceId, ulPropId, iSize, lpSource);
  496. if (er != erSuccess)
  497. return er;
  498. if (lpulInstanceId)
  499. *lpulInstanceId = ulInstanceId;
  500. return erSuccess;
  501. }
  502. /**
  503. * Save a property of an object with a given instance id, optionally remove previous data.
  504. *
  505. * @param[in] ulObjId HierarchyID of object
  506. * @param[in] ulPropId Property of object
  507. * @param[in] bDeleteOld Remove old data before saving the new
  508. * @param[in] ulInstanceId Instance id to link
  509. * @param[out] lpulInstanceId Same number as in ulInstanceId
  510. *
  511. * @return
  512. */
  513. ECRESULT ECAttachmentStorage::SaveAttachment(ULONG ulObjId, ULONG ulPropId, bool bDeleteOld, ULONG ulInstanceId, ULONG *lpulInstanceId)
  514. {
  515. ECRESULT er;
  516. ULONG ulOldAttachId = 0;
  517. if (bDeleteOld) {
  518. /*
  519. * Call DeleteAttachment to decrease the refcount
  520. * and optionally delete the original attachment.
  521. */
  522. if (GetSingleInstanceId(ulObjId, ulPropId, &ulOldAttachId) == erSuccess &&
  523. ulOldAttachId == ulInstanceId)
  524. // Nothing to do, we already have that instance ID
  525. return erSuccess;
  526. er = DeleteAttachment(ulObjId, ulPropId, true);
  527. if (er != erSuccess)
  528. return er;
  529. }
  530. er = SetSingleInstanceId(ulObjId, ulInstanceId, ulPropId);
  531. if (er != erSuccess)
  532. return er;
  533. /* InstanceId is equal to provided AttachId */
  534. *lpulInstanceId = ulInstanceId;
  535. return erSuccess;
  536. }
  537. /**
  538. * Make a copy of attachment data for a given object.
  539. *
  540. * In reality, the data is not copied, but an extra singleinstance
  541. * entry is added for the new hierarchyid.
  542. *
  543. * @param[in] ulObjId Source hierarchy id to instance data from
  544. * @param[in] ulNewObjId Additional hierarchy id which has the same data
  545. *
  546. * @return Kopano error code
  547. */
  548. ECRESULT ECAttachmentStorage::CopyAttachment(ULONG ulObjId, ULONG ulNewObjId)
  549. {
  550. ECRESULT er;
  551. std::string strQuery;
  552. /*
  553. * Only update the reference count in the `singleinstances` table,
  554. * no need to really physically store the attachment twice.
  555. */
  556. strQuery =
  557. "INSERT INTO `singleinstances` (`hierarchyid`, `instanceid`, `tag`) "
  558. "SELECT " + stringify(ulNewObjId) + ", `instanceid`, `tag` "
  559. "FROM `singleinstances` "
  560. "WHERE `hierarchyid` = " + stringify(ulObjId);
  561. er = m_lpDatabase->DoInsert(strQuery);
  562. if (er != erSuccess)
  563. ec_log_err("ECAttachmentStorage::CopyAttachment(): DoInsert failed %x", er);
  564. return er;
  565. }
  566. /**
  567. * Delete all properties of given list of hierarchy ids.
  568. *
  569. * @param[in] lstDeleteObjects list of hierarchy ids to delete singleinstance data for
  570. *
  571. * @return Kopano error code
  572. */
  573. ECRESULT ECAttachmentStorage::DeleteAttachments(const std::list<ULONG> &lstDeleteObjects)
  574. {
  575. ECRESULT er = erSuccess;
  576. std::list<ULONG> lstAttachments;
  577. std::list<ULONG> lstDeleteAttach;
  578. std::string strQuery;
  579. /*
  580. * Convert object ids into attachment ids
  581. * NOTE: lstDeleteObjects.size() >= lstAttachments.size()
  582. * because the list does not 100% consists of attachments id and the
  583. * duplicate attachment ids will be filtered out.
  584. */
  585. er = GetSingleInstanceIds(lstDeleteObjects, &lstAttachments);
  586. if (er != erSuccess)
  587. return er;
  588. /* No attachments present, we're done */
  589. if (lstAttachments.empty())
  590. return er;
  591. /*
  592. * Remove all objects from `singleinstances` table this will decrease the
  593. * reference count for each attachment.
  594. */
  595. strQuery =
  596. "DELETE FROM `singleinstances` "
  597. "WHERE `hierarchyid` IN (";
  598. for (auto i = lstDeleteObjects.cbegin(); i != lstDeleteObjects.cend(); ++i) {
  599. if (i != lstDeleteObjects.cbegin())
  600. strQuery += ",";
  601. strQuery += stringify(*i);
  602. }
  603. strQuery += ")";
  604. er = m_lpDatabase->DoDelete(strQuery);
  605. if (er != erSuccess) {
  606. ec_log_err("ECAttachmentStorage::DeleteAttachments(): DoDelete failed %x", er);
  607. return er;
  608. }
  609. /*
  610. * Get the list of orphaned Single Instance IDs which we can delete.
  611. */
  612. er = GetOrphanedSingleInstances(lstAttachments, &lstDeleteAttach);
  613. if (er != erSuccess)
  614. return er;
  615. if (!lstDeleteAttach.empty()) {
  616. er = DeleteAttachmentInstances(lstDeleteAttach, false);
  617. if (er != erSuccess)
  618. return er;
  619. }
  620. return erSuccess;
  621. }
  622. /**
  623. * Delete one single instance property of an object.
  624. * public interface version
  625. *
  626. * @param[in] ulObjId HierarchyID of object to delete single instance property from
  627. * @param[in] ulPropId Property of object to remove
  628. *
  629. * @return
  630. */
  631. ECRESULT ECAttachmentStorage::DeleteAttachment(ULONG ulObjId, ULONG ulPropId) {
  632. return DeleteAttachment(ulObjId, ulPropId, false);
  633. }
  634. /**
  635. * Delete one single instance property of an object.
  636. *
  637. * @param[in] ulObjId HierarchyID of object to delete single instance property from
  638. * @param[in] ulPropId Property of object to remove
  639. * @param[in] bReplace Flag used for transations in ECFileStorage
  640. *
  641. * @return Kopano error code
  642. */
  643. ECRESULT ECAttachmentStorage::DeleteAttachment(ULONG ulObjId, ULONG ulPropId, bool bReplace)
  644. {
  645. ECRESULT er;
  646. ULONG ulInstanceId = 0;
  647. bool bOrphan = false;
  648. std::string strQuery;
  649. /*
  650. * Convert object id into attachment id
  651. */
  652. er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
  653. if (er != erSuccess) {
  654. if (er == KCERR_NOT_FOUND)
  655. er = erSuccess; // Nothing to delete
  656. return er;
  657. }
  658. /*
  659. * Remove object from `singleinstances` table, this will decrease the
  660. * reference count for the attachment.
  661. */
  662. strQuery =
  663. "DELETE FROM `singleinstances` "
  664. "WHERE `hierarchyid` = " + stringify(ulObjId) + " "
  665. "AND `tag` = " + stringify(ulPropId);
  666. er = m_lpDatabase->DoDelete(strQuery);
  667. if (er != erSuccess) {
  668. ec_log_err("ECAttachmentStorage::DeleteAttachment(): DoDelete failed %x", er);
  669. return er;
  670. }
  671. /*
  672. * Check if the attachment can be permanently deleted.
  673. */
  674. if (IsOrphanedSingleInstance(ulInstanceId, &bOrphan) == erSuccess && bOrphan) {
  675. er = DeleteAttachmentInstance(ulInstanceId, bReplace);
  676. if (er != erSuccess)
  677. return er;
  678. }
  679. return erSuccess;
  680. }
  681. /**
  682. * Get the size of a large property of a specific object
  683. *
  684. * @param[in] ulObjId HierarchyID of object
  685. * @param[in] ulPropId PropertyID of object
  686. * @param[out] lpulSize size of property
  687. *
  688. * @return Kopano error code
  689. */
  690. ECRESULT ECAttachmentStorage::GetSize(ULONG ulObjId, ULONG ulPropId, size_t *lpulSize)
  691. {
  692. ECRESULT er;
  693. ULONG ulInstanceId = 0;
  694. /*
  695. * Convert object id into attachment id
  696. */
  697. er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
  698. if (er == KCERR_NOT_FOUND) {
  699. *lpulSize = 0;
  700. return erSuccess;
  701. } else if (er != erSuccess) {
  702. return er;
  703. }
  704. return GetSizeInstance(ulInstanceId, lpulSize);
  705. }
  706. // Attachment storage is in database
  707. ECDatabaseAttachment::ECDatabaseAttachment(ECDatabase *lpDatabase) :
  708. ECAttachmentStorage(lpDatabase, 0)
  709. {
  710. }
  711. /**
  712. * For a given instance id, check if this has a valid attachment data present
  713. *
  714. * @param[in] ulInstanceId instance id to check validity
  715. *
  716. * @return instance present
  717. */
  718. bool ECDatabaseAttachment::ExistAttachmentInstance(ULONG ulInstanceId)
  719. {
  720. ECRESULT er = erSuccess;
  721. std::string strQuery;
  722. DB_RESULT lpDBResult;
  723. DB_ROW lpDBRow = NULL;
  724. strQuery = "SELECT instanceid FROM lob WHERE instanceid = " + stringify(ulInstanceId) + " LIMIT 1";
  725. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  726. if (er != erSuccess) {
  727. ec_log_err("ECAttachmentStorage::ExistAttachmentInstance(): DoSelect failed %x", er);
  728. return false;
  729. }
  730. lpDBRow = m_lpDatabase->FetchRow(lpDBResult);
  731. if (!lpDBRow || !lpDBRow[0])
  732. return false; /* KCERR_NOT_FOUND */
  733. return true;
  734. }
  735. /**
  736. * Load instance data using soap and return as blob.
  737. *
  738. * @param[in] soap soap to use memory allocations for
  739. * @param[in] ulInstanceId InstanceID to load
  740. * @param[out] lpiSize size in lppData
  741. * @param[out] lppData data of instance
  742. *
  743. * @return Kopano error code
  744. */
  745. ECRESULT ECDatabaseAttachment::LoadAttachmentInstance(struct soap *soap, ULONG ulInstanceId, size_t *lpiSize, unsigned char **lppData)
  746. {
  747. ECRESULT er = erSuccess;
  748. size_t iSize = 0;
  749. size_t iReadSize = 0;
  750. unsigned char *lpData = NULL;
  751. std::string strQuery;
  752. DB_RESULT lpDBResult;
  753. DB_ROW lpDBRow = NULL;
  754. DB_LENGTHS lpDBLen = NULL;
  755. // we first need to know the complete size of the attachment (some old databases don't have the correct chunk size)
  756. strQuery = "SELECT SUM(LENGTH(val_binary)) FROM lob WHERE instanceid = " + stringify(ulInstanceId);
  757. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  758. if (er != erSuccess) {
  759. ec_log_err("ECAttachmentStorage::LoadAttachmentInstance(): DoSelect failed %x", er);
  760. goto exit;
  761. }
  762. lpDBRow = m_lpDatabase->FetchRow(lpDBResult);
  763. if (lpDBRow == NULL || lpDBRow[0] == NULL) {
  764. er = KCERR_DATABASE_ERROR;
  765. ec_log_err("ECDatabaseAttachment::LoadAttachmentInstance(): no row returned");
  766. goto exit;
  767. }
  768. iSize = strtoul(lpDBRow[0], NULL, 0);
  769. // get all chunks
  770. strQuery = "SELECT val_binary FROM lob WHERE instanceid = " + stringify(ulInstanceId) + " ORDER BY chunkid";
  771. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  772. if (er != erSuccess) {
  773. ec_log_err("ECAttachmentStorage::LoadAttachmentInstance(): DoSelect(2) failed %x", er);
  774. goto exit;
  775. }
  776. lpData = s_alloc<unsigned char>(soap, iSize);
  777. while ((lpDBRow = m_lpDatabase->FetchRow(lpDBResult))) {
  778. if (lpDBRow[0] == NULL) {
  779. // broken attachment!
  780. er = KCERR_DATABASE_ERROR;
  781. ec_log_err("ECDatabaseAttachment::LoadAttachmentInstance(): column contained NULL");
  782. goto exit;
  783. }
  784. lpDBLen = m_lpDatabase->FetchRowLengths(lpDBResult);
  785. memcpy(lpData + iReadSize, lpDBRow[0], lpDBLen[0]);
  786. iReadSize += lpDBLen[0];
  787. }
  788. *lpiSize = iReadSize;
  789. *lppData = lpData;
  790. exit:
  791. if (er != erSuccess && !soap)
  792. delete [] lpData;
  793. return er;
  794. }
  795. /**
  796. * Load instance data using a serializer.
  797. *
  798. * @param[in] ulInstanceId InstanceID to load
  799. * @param[out] lpiSize size written in in lpSink
  800. * @param[in] lpSink serializer to write in
  801. *
  802. * @return
  803. */
  804. ECRESULT ECDatabaseAttachment::LoadAttachmentInstance(ULONG ulInstanceId, size_t *lpiSize, ECSerializer *lpSink)
  805. {
  806. ECRESULT er = erSuccess;
  807. size_t iReadSize = 0;
  808. std::string strQuery;
  809. DB_RESULT lpDBResult;
  810. DB_ROW lpDBRow = NULL;
  811. DB_LENGTHS lpDBLen = NULL;
  812. // get all chunks
  813. strQuery = "SELECT val_binary FROM lob WHERE instanceid = " + stringify(ulInstanceId) + " ORDER BY chunkid";
  814. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  815. if (er != erSuccess) {
  816. ec_log_err("ECAttachmentStorage::LoadAttachmentInstance(): DoSelect failed %x", er);
  817. return er;
  818. }
  819. while ((lpDBRow = m_lpDatabase->FetchRow(lpDBResult))) {
  820. if (lpDBRow[0] == NULL) {
  821. // broken attachment !
  822. ec_log_err("ECDatabaseAttachment::LoadAttachmentInstance(): column contained NULL");
  823. return KCERR_DATABASE_ERROR;
  824. }
  825. lpDBLen = m_lpDatabase->FetchRowLengths(lpDBResult);
  826. er = lpSink->Write(lpDBRow[0], 1, lpDBLen[0]);
  827. if (er != erSuccess) {
  828. ec_log_err("ECAttachmentStorage::LoadAttachmentInstance(): Write failed %x", er);
  829. return er;
  830. }
  831. iReadSize += lpDBLen[0];
  832. }
  833. *lpiSize = iReadSize;
  834. return erSuccess;
  835. }
  836. /**
  837. * Save a property in a new instance from a blob
  838. *
  839. * @note Property id here is actually useless, but legacy requires
  840. * this. Removing the `tag` column from the database would require a
  841. * database update on the lob table, which would make database
  842. * attachment users very unhappy.
  843. *
  844. * @param[in] ulInstanceId InstanceID to save data under
  845. * @param[in] ulPropId PropertyID to save
  846. * @param[in] iSize size of lpData
  847. * @param[in] lpData Data of property
  848. *
  849. * @return Kopano error code
  850. */
  851. ECRESULT ECDatabaseAttachment::SaveAttachmentInstance(ULONG ulInstanceId, ULONG ulPropId, size_t iSize, unsigned char *lpData)
  852. {
  853. ECRESULT er;
  854. std::string strQuery;
  855. // make chunks of 393216 bytes (384*1024)
  856. size_t iSizeLeft = iSize;
  857. size_t iPtr = 0;
  858. size_t ulChunk = 0;
  859. do {
  860. size_t iChunkSize = iSizeLeft < CHUNK_SIZE ? iSizeLeft : CHUNK_SIZE;
  861. strQuery = (std::string)"INSERT INTO lob (instanceid, chunkid, tag, val_binary) VALUES (" +
  862. stringify(ulInstanceId) + ", " + stringify(ulChunk) + ", " + stringify(ulPropId) +
  863. ", " + m_lpDatabase->EscapeBinary(lpData + iPtr, iChunkSize) + ")";
  864. er = m_lpDatabase->DoInsert(strQuery);
  865. if (er != erSuccess) {
  866. ec_log_err("ECAttachmentStorage::SaveAttachmentInstance(): DoInsert failed %x", er);
  867. return er;
  868. }
  869. ++ulChunk;
  870. iSizeLeft -= iChunkSize;
  871. iPtr += iChunkSize;
  872. } while (iSizeLeft > 0);
  873. return erSuccess;
  874. }
  875. /**
  876. * Save a property in a new instance from a serializer
  877. *
  878. * @note Property id here is actually useless, but legacy requires
  879. * this. Removing the `tag` column from the database would require a
  880. * database update on the lob table, which would make database
  881. * attachment users very unhappy.
  882. *
  883. * @param[in] ulInstanceId InstanceID to save data under
  884. * @param[in] ulPropId PropertyID to save
  885. * @param[in] iSize size in lpSource
  886. * @param[in] lpSource serializer to read data from
  887. *
  888. * @return Kopano error code
  889. */
  890. ECRESULT ECDatabaseAttachment::SaveAttachmentInstance(ULONG ulInstanceId, ULONG ulPropId, size_t iSize, ECSerializer *lpSource)
  891. {
  892. ECRESULT er;
  893. std::string strQuery;
  894. unsigned char szBuffer[CHUNK_SIZE] = {0};
  895. // make chunks of 393216 bytes (384*1024)
  896. size_t iSizeLeft = iSize;
  897. size_t ulChunk = 0;
  898. while (iSizeLeft > 0) {
  899. size_t iChunkSize = iSizeLeft < CHUNK_SIZE ? iSizeLeft : CHUNK_SIZE;
  900. er = lpSource->Read(szBuffer, 1, iChunkSize);
  901. if (er != erSuccess)
  902. return er;
  903. strQuery = (std::string)"INSERT INTO lob (instanceid, chunkid, tag, val_binary) VALUES (" +
  904. stringify(ulInstanceId) + ", " + stringify(ulChunk) + ", " + stringify(ulPropId) +
  905. ", " + m_lpDatabase->EscapeBinary(szBuffer, iChunkSize) + ")";
  906. er = m_lpDatabase->DoInsert(strQuery);
  907. if (er != erSuccess) {
  908. ec_log_err("ECAttachmentStorage::SaveAttachmentInstance(): DoInsert failed %x", er);
  909. return er;
  910. }
  911. ++ulChunk;
  912. iSizeLeft -= iChunkSize;
  913. }
  914. return erSuccess;
  915. }
  916. /**
  917. * Delete given instances from the database
  918. *
  919. * @param[in] lstDeleteInstances List of instance ids to remove from the database
  920. * @param[in] bReplace unused, see ECFileAttachment
  921. *
  922. * @return Kopano error code
  923. */
  924. ECRESULT ECDatabaseAttachment::DeleteAttachmentInstances(const std::list<ULONG> &lstDeleteInstances, bool bReplace)
  925. {
  926. ECRESULT er = erSuccess;
  927. std::string strQuery;
  928. strQuery = (std::string)"DELETE FROM lob WHERE instanceid IN (";
  929. for (auto iterDel = lstDeleteInstances.cbegin();
  930. iterDel != lstDeleteInstances.cend(); ++iterDel) {
  931. if (iterDel != lstDeleteInstances.cbegin())
  932. strQuery += ",";
  933. strQuery += stringify(*iterDel);
  934. }
  935. strQuery += ")";
  936. er = m_lpDatabase->DoDelete(strQuery);
  937. return er;
  938. }
  939. /**
  940. * Delete a single instanceid from the database
  941. *
  942. * @param[in] ulInstanceId instance id to remove
  943. * @param[in] bReplace unused, see ECFileAttachment
  944. *
  945. * @return
  946. */
  947. ECRESULT ECDatabaseAttachment::DeleteAttachmentInstance(ULONG ulInstanceId, bool bReplace)
  948. {
  949. ECRESULT er = erSuccess;
  950. std::string strQuery;
  951. strQuery = (std::string)"DELETE FROM lob WHERE instanceid=" + stringify(ulInstanceId);
  952. er = m_lpDatabase->DoDelete(strQuery);
  953. return er;
  954. }
  955. /**
  956. * Return the size of an instance
  957. *
  958. * @param[in] ulInstanceId InstanceID to check the size for
  959. * @param[out] lpulSize Size of the instance
  960. * @param[out] lpbCompressed unused, see ECFileAttachment
  961. *
  962. * @return Kopano error code
  963. */
  964. ECRESULT ECDatabaseAttachment::GetSizeInstance(ULONG ulInstanceId, size_t *lpulSize, bool *lpbCompressed)
  965. {
  966. ECRESULT er = erSuccess;
  967. std::string strQuery;
  968. DB_RESULT lpDBResult;
  969. DB_ROW lpDBRow = NULL;
  970. strQuery = "SELECT SUM(LENGTH(val_binary)) FROM lob WHERE instanceid = " + stringify(ulInstanceId);
  971. er = m_lpDatabase->DoSelect(strQuery, &lpDBResult);
  972. if (er != erSuccess) {
  973. ec_log_err("ECAttachmentStorage::GetSizeInstance(): DoSelect failed %x", er);
  974. return er;
  975. }
  976. lpDBRow = m_lpDatabase->FetchRow(lpDBResult);
  977. if (lpDBRow == NULL || lpDBRow[0] == NULL) {
  978. ec_log_err("ECDatabaseAttachment::GetSizeInstance(): now row or column contained NULL");
  979. return KCERR_DATABASE_ERROR;
  980. }
  981. *lpulSize = strtoul(lpDBRow[0], NULL, 0);
  982. if (lpbCompressed)
  983. *lpbCompressed = false;
  984. return erSuccess;
  985. }
  986. ECRESULT ECDatabaseAttachment::Begin()
  987. {
  988. return erSuccess;
  989. }
  990. ECRESULT ECDatabaseAttachment::Commit()
  991. {
  992. return erSuccess;
  993. }
  994. ECRESULT ECDatabaseAttachment::Rollback()
  995. {
  996. return erSuccess;
  997. }
  998. // Attachment storage is in separate files
  999. ECFileAttachment::ECFileAttachment(ECDatabase *lpDatabase,
  1000. const std::string &basepath, unsigned int ulCompressionLevel,
  1001. const bool force_changes_to_disk) :
  1002. ECAttachmentStorage(lpDatabase, ulCompressionLevel),
  1003. m_basepath(basepath)
  1004. {
  1005. if (m_basepath.empty())
  1006. m_basepath = "/var/lib/kopano";
  1007. this -> force_changes_to_disk = force_changes_to_disk;
  1008. if (force_changes_to_disk) {
  1009. m_dirp = opendir(m_basepath.c_str());
  1010. if (m_dirp)
  1011. m_dirFd = dirfd(m_dirp);
  1012. if (m_dirFd == -1)
  1013. ec_log_warn("Problem opening directory file \"%s\": %s - attachment storage atomicity not guaranteed", m_basepath.c_str(), strerror(errno));
  1014. }
  1015. attachment_size_safety_limit = 512 * 1024 * 1024; // FIXME make configurable
  1016. }
  1017. ECFileAttachment::~ECFileAttachment()
  1018. {
  1019. if (m_dirp != NULL)
  1020. closedir(m_dirp);
  1021. if (m_bTransaction)
  1022. assert(false);
  1023. }
  1024. /**
  1025. * For a given instance id, check if this has a valid attachment data present
  1026. *
  1027. * @param[in] ulInstanceId instance id to check validity
  1028. *
  1029. * @return instance present
  1030. */
  1031. bool ECFileAttachment::ExistAttachmentInstance(ULONG ulInstanceId)
  1032. {
  1033. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1034. struct stat st;
  1035. if (stat(filename.c_str(), &st) == -1) {
  1036. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression);
  1037. if (stat(filename.c_str(), &st) == -1)
  1038. return false;
  1039. }
  1040. return true;
  1041. }
  1042. /**
  1043. * @uclen: number of uncompressed bytes that is requested
  1044. */
  1045. static ssize_t gzread_retry(gzFile fp, void *data, size_t uclen)
  1046. {
  1047. ssize_t read_total = 0;
  1048. auto buf = static_cast<char *>(data);
  1049. if (uclen == 0)
  1050. /* Avoid useless churn. */
  1051. return 0;
  1052. while (uclen > 0) {
  1053. int chunk_size = (uclen > INT_MAX) ? INT_MAX : uclen;
  1054. int ret = gzread(fp, buf, chunk_size);
  1055. /*
  1056. * Save @errno now, since gzerror() code looks prone to
  1057. * reset it.
  1058. */
  1059. int saved_errno = errno;
  1060. int zerror;
  1061. const char *zerrstr = gzerror(fp, &zerror);
  1062. if (ret < 0 && zerror == Z_ERRNO &&
  1063. (saved_errno == EINTR || saved_errno == EAGAIN))
  1064. /* Server delay (cf. gzread_write) */
  1065. continue;
  1066. if (ret < 0 && zerror == Z_ERRNO) {
  1067. ec_log_err("gzread: %s (%d): %s",
  1068. zerrstr, zerror, strerror(saved_errno));
  1069. return ret;
  1070. }
  1071. if (ret < 0) {
  1072. ec_log_err("gzread: %s (%d)", zerrstr, zerror);
  1073. return ret;
  1074. }
  1075. if (ret == 0)
  1076. /*
  1077. * EOF (since we already excluded chunk_size==0
  1078. * requests).
  1079. */
  1080. break;
  1081. buf += ret;
  1082. read_total += ret;
  1083. uclen -= ret;
  1084. }
  1085. return read_total;
  1086. }
  1087. static ssize_t gzwrite_retry(gzFile fp, const void *data, size_t uclen)
  1088. {
  1089. size_t wrote_total = 0;
  1090. auto buf = static_cast<const char *>(data);
  1091. if (uclen == 0)
  1092. /* Avoid useless churn. */
  1093. return 0;
  1094. while (uclen > 0) {
  1095. int chunk_size = (uclen > INT_MAX) ? INT_MAX : uclen;
  1096. int ret = gzwrite(fp, buf, chunk_size);
  1097. int saved_errno = errno;
  1098. int zerror;
  1099. const char *zerrstr = gzerror(fp, &zerror);
  1100. if (ret < 0 && zerror == Z_ERRNO &&
  1101. (saved_errno == EINTR || saved_errno == EAGAIN))
  1102. /*
  1103. * Choosing to continue reading can delay server
  1104. * shutdown... but we are in a soap handler, so
  1105. * whatelse could we do.
  1106. */
  1107. continue;
  1108. if (ret < 0 && zerror == Z_ERRNO) {
  1109. ec_log_err("gzwrite: %s (%d): %s",
  1110. zerrstr, zerror, strerror(saved_errno));
  1111. return ret;
  1112. }
  1113. if (ret < 0) {
  1114. ec_log_err("gzwrite: %s (%d)", zerrstr, zerror);
  1115. return ret;
  1116. }
  1117. if (ret == 0)
  1118. /* ??? - could happen if the file is not open for write */
  1119. break;
  1120. buf += ret;
  1121. wrote_total += ret;
  1122. uclen -= ret;
  1123. }
  1124. return wrote_total;
  1125. }
  1126. bool ECFileAttachment::VerifyInstanceSize(const ULONG instanceId, const size_t expectedSize, const std::string & filename) {
  1127. bool bCompressed = false;
  1128. size_t ulSize = 0;
  1129. if (GetSizeInstance(instanceId, &ulSize, &bCompressed) != erSuccess) {
  1130. ec_log_debug("ECFileAttachment::VerifyInstanceSize(): Failed verifying size of \"%s\"", filename.c_str());
  1131. return false;
  1132. }
  1133. if (ulSize != expectedSize) {
  1134. ec_log_debug("ECFileAttachment::VerifyInstanceSize(): Uncompressed size unexpected for \"%s\": expected %lu, got %lu.", filename.c_str(), static_cast<unsigned long>(expectedSize), static_cast<unsigned long>(ulSize));
  1135. return false;
  1136. }
  1137. if (ulSize > attachment_size_safety_limit)
  1138. ec_log_debug("ECFileAttachment::VerifyInstanceSize(): Overly large file (%lu/%lu): \"%s\"", static_cast<unsigned long>(expectedSize), static_cast<unsigned long>(ulSize), filename.c_str());
  1139. return true;
  1140. }
  1141. /**
  1142. * Load instance data using soap and return as blob.
  1143. *
  1144. * @param[in] soap soap to use memory allocations for
  1145. * @param[in] ulInstanceId InstanceID to load
  1146. * @param[out] lpiSize size in lppData
  1147. * @param[out] lppData data of instance
  1148. *
  1149. * @return Kopano error code
  1150. */
  1151. ECRESULT ECFileAttachment::LoadAttachmentInstance(struct soap *soap, ULONG ulInstanceId, size_t *lpiSize, unsigned char **lppData) {
  1152. ECRESULT er = erSuccess;
  1153. string filename;
  1154. unsigned char *lpData = NULL;
  1155. bool bCompressed = false;
  1156. int fd = -1;
  1157. gzFile gzfp = NULL;
  1158. *lpiSize = 0;
  1159. filename = CreateAttachmentFilename(ulInstanceId, bCompressed);
  1160. fd = open(filename.c_str(), O_RDONLY);
  1161. if (fd < 0 && errno != ENOENT) {
  1162. /* Access problems */
  1163. ec_log_err("K-1561: cannot open attachment \"%s\": %s", filename.c_str(), strerror(errno));
  1164. return KCERR_NO_ACCESS;
  1165. } else if (fd < 0) {
  1166. /* Not found, try gzip */
  1167. bCompressed = true;
  1168. filename = CreateAttachmentFilename(ulInstanceId, bCompressed);
  1169. fd = open(filename.c_str(), O_RDONLY);
  1170. if (fd < 0) {
  1171. ec_log_err("K-1562: cannot open attachment \"%s\": %s", filename.c_str(), strerror(errno));
  1172. return KCERR_NOT_FOUND;
  1173. }
  1174. }
  1175. my_readahead(fd);
  1176. /*
  1177. * CreateAttachmentFilename Already checked if we are working with a compressed or uncompressed file,
  1178. * no need to perform retries when our first guess (which is based on CreateAttachmentFilename) fails.
  1179. */
  1180. if (bCompressed) {
  1181. unsigned char *temp = NULL;
  1182. /* Compressed attachment */
  1183. gzfp = gzdopen(fd, "rb");
  1184. if (!gzfp) {
  1185. // do not use KCERR_NOT_FOUND: the file is already open so it exists
  1186. // so something else is going wrong here
  1187. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): cannot gzopen attachment \"%s\": %s", filename.c_str(), strerror(errno));
  1188. er = KCERR_UNKNOWN;
  1189. goto exit;
  1190. }
  1191. #if ZLIB_VERNUM >= 0x1240
  1192. if (gzbuffer(gzfp, ZLIB_BUFFER_SIZE) == -1)
  1193. ec_log_warn("gzbuffer failed");
  1194. #endif
  1195. size_t memory_block_size = 0;
  1196. for(;;)
  1197. {
  1198. int ret = -1;
  1199. if (memory_block_size == *lpiSize) {
  1200. if (memory_block_size)
  1201. memory_block_size *= 2;
  1202. else
  1203. memory_block_size = CHUNK_SIZE;
  1204. auto new_temp = static_cast<unsigned char *>(realloc(temp, memory_block_size));
  1205. if (!new_temp) {
  1206. // first free memory or the logging may fail too
  1207. free(temp);
  1208. temp = NULL;
  1209. *lpiSize = 0;
  1210. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Out of memory while reading \"%s\"", filename.c_str());
  1211. er = KCERR_UNABLE_TO_COMPLETE;
  1212. goto exit;
  1213. }
  1214. temp = new_temp;
  1215. }
  1216. ret = gzread_retry(gzfp, &temp[*lpiSize], memory_block_size - *lpiSize);
  1217. if (ret < 0) {
  1218. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Error while gzreading attachment data from \"%s\"", filename.c_str());
  1219. // er = KCERR_DATABASE_ERROR;
  1220. //break;
  1221. *lpiSize = 0;
  1222. break;
  1223. }
  1224. if (ret == 0)
  1225. break;
  1226. *lpiSize += ret;
  1227. if (*lpiSize >= attachment_size_safety_limit) {
  1228. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Size safety limit (%lu) reached for \"%s\" (compressed)", static_cast<unsigned long>(attachment_size_safety_limit), filename.c_str());
  1229. // er = KCERR_DATABASE_ERROR;
  1230. //break;
  1231. *lpiSize = 0;
  1232. break;
  1233. }
  1234. }
  1235. if (er == erSuccess)
  1236. (void)VerifyInstanceSize(ulInstanceId, *lpiSize, filename);
  1237. if (er == erSuccess) {
  1238. lpData = s_alloc<unsigned char>(soap, *lpiSize);
  1239. memcpy(lpData, temp, *lpiSize);
  1240. }
  1241. free(temp);
  1242. }
  1243. else {
  1244. ssize_t lReadSize = 0;
  1245. struct stat st;
  1246. if (fstat(fd, &st) == -1)
  1247. {
  1248. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Error while doing fstat on \"%s\": %s", filename.c_str(), strerror(errno));
  1249. // FIXME er = KCERR_DATABASE_ERROR;
  1250. *lpiSize = 0;
  1251. lpData = s_alloc<unsigned char>(soap, *lpiSize);
  1252. *lppData = lpData;
  1253. goto exit;
  1254. }
  1255. *lpiSize = st.st_size;
  1256. if (*lpiSize >= attachment_size_safety_limit) {
  1257. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Size safety limit (%lu) reached for \"%s\" (uncompressed)", static_cast<unsigned long>(attachment_size_safety_limit), filename.c_str());
  1258. // FIXME er = KCERR_DATABASE_ERROR;
  1259. *lpiSize = 0;
  1260. lpData = s_alloc<unsigned char>(soap, *lpiSize);
  1261. *lppData = lpData;
  1262. goto exit;
  1263. }
  1264. lpData = s_alloc<unsigned char>(soap, *lpiSize);
  1265. /* Uncompressed attachment */
  1266. lReadSize = read_retry(fd, lpData, *lpiSize);
  1267. if (lReadSize < 0) {
  1268. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Error while reading attachment data from \"%s\": %s", filename.c_str(), strerror(errno));
  1269. // FIXME er = KCERR_DATABASE_ERROR;
  1270. *lpiSize = 0;
  1271. *lppData = lpData;
  1272. goto exit;
  1273. }
  1274. if (lReadSize != static_cast<ssize_t>(*lpiSize)) {
  1275. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Short read while reading attachment data from \"%s\": expected %lu, got %lu.", filename.c_str(), static_cast<unsigned long>(*lpiSize), static_cast<unsigned long>(lReadSize));
  1276. // FIXME er = KCERR_DATABASE_ERROR;
  1277. *lpiSize = 0;
  1278. *lppData = lpData;
  1279. goto exit;
  1280. }
  1281. }
  1282. *lppData = lpData;
  1283. exit:
  1284. if (er != erSuccess)
  1285. delete [] lpData;
  1286. if (gzfp)
  1287. {
  1288. gzclose(gzfp);
  1289. fd = -1;
  1290. }
  1291. if (fd != -1)
  1292. close(fd);
  1293. return er;
  1294. }
  1295. /**
  1296. * Load instance data using a serializer.
  1297. *
  1298. * @param[in] ulInstanceId InstanceID to load
  1299. * @param[out] lpiSize size written in in lpSink
  1300. * @param[in] lpSink serializer to write in
  1301. *
  1302. * @return
  1303. */
  1304. ECRESULT ECFileAttachment::LoadAttachmentInstance(ULONG ulInstanceId, size_t *lpiSize, ECSerializer *lpSink) {
  1305. ECRESULT er = erSuccess;
  1306. string filename;
  1307. bool bCompressed = false;
  1308. char buffer[CHUNK_SIZE];
  1309. int fd = -1;
  1310. gzFile gzfp = NULL;
  1311. *lpiSize = 0;
  1312. filename = CreateAttachmentFilename(ulInstanceId, bCompressed);
  1313. fd = open(filename.c_str(), O_RDONLY);
  1314. if (fd < 0 && errno != ENOENT) {
  1315. /* Access problems */
  1316. ec_log_err("K-1563: cannot open attachment \"%s\": %s", filename.c_str(), strerror(errno));
  1317. return KCERR_NO_ACCESS;
  1318. } else if (fd < 0) {
  1319. /* Not found, try gzip */
  1320. bCompressed = true;
  1321. filename = CreateAttachmentFilename(ulInstanceId, bCompressed);
  1322. fd = open(filename.c_str(), O_RDONLY);
  1323. if (fd < 0) {
  1324. ec_log_err("K-1564: cannot open attachment \"%s\": %s", filename.c_str(), strerror(errno));
  1325. return KCERR_NOT_FOUND;
  1326. }
  1327. }
  1328. my_readahead(fd);
  1329. if (bCompressed) {
  1330. /* Compressed attachment */
  1331. gzfp = gzdopen(fd, "rb");
  1332. if (!gzfp) {
  1333. er = KCERR_UNKNOWN;
  1334. goto exit;
  1335. }
  1336. #if ZLIB_VERNUM >= 0x1240
  1337. if (gzbuffer(gzfp, ZLIB_BUFFER_SIZE) == -1)
  1338. ec_log_warn("gzbuffer failed");
  1339. #endif
  1340. for(;;) {
  1341. ssize_t lReadNow = gzread_retry(gzfp, buffer, sizeof(buffer));
  1342. if (lReadNow < 0) {
  1343. ec_log_err("ECFileAttachment::LoadAttachmentInstance(): Error while gzreading attachment data from \"%s\".", filename.c_str());
  1344. er = KCERR_DATABASE_ERROR;
  1345. goto exit;
  1346. }
  1347. if (lReadNow == 0)
  1348. break;
  1349. lpSink->Write(buffer, 1, lReadNow);
  1350. *lpiSize += lReadNow;
  1351. }
  1352. if (er == erSuccess)
  1353. (void)VerifyInstanceSize(ulInstanceId, *lpiSize, filename);
  1354. }
  1355. else {
  1356. for(;;) {
  1357. ssize_t lReadNow = read_retry(fd, buffer, sizeof(buffer));
  1358. if (lReadNow < 0) {
  1359. ec_log_err("ECFileAttachment::LoadAttachmentInstance(SOAP): Error while reading attachment data from \"%s\": %s", filename.c_str(), strerror(errno));
  1360. er = KCERR_DATABASE_ERROR;
  1361. goto exit;
  1362. }
  1363. if (lReadNow == 0)
  1364. break;
  1365. lpSink->Write(buffer, 1, lReadNow);
  1366. *lpiSize += lReadNow;
  1367. }
  1368. }
  1369. exit:
  1370. if (gzfp) {
  1371. gzclose(gzfp);
  1372. fd = -1;
  1373. }
  1374. if (fd != -1)
  1375. close(fd);
  1376. return er;
  1377. }
  1378. static bool EvaluateCompressibleness(const uint8_t *const lpData, const size_t iSize) {
  1379. // If a file is smallar than the (usual) blocksize of the filesystem
  1380. // then don't bother compressing it; it will give no gain as the
  1381. // whole block will be read anyway when it is retrieved from disk.
  1382. // In theory we could still try to compress it to see if the result
  1383. // is smaller than 60: if a file is 60 bytes or less in size, then
  1384. // it can be stored into the inode itself (at least for the ext4
  1385. // filesystem). But note: gzip has a metadata overhead of 18 bytes
  1386. // (see http://en.wikipedia.org/wiki/Gzip#File_format ) so a file
  1387. // should be compressible to at most 42 bytes.
  1388. if (iSize <= 4096)
  1389. return false;
  1390. // ZIP (also most OpenOffice documents; those are multiple files in a ZIP-file)
  1391. if (lpData[0] == 'P' && lpData[1] == 'K' && lpData[2] == 0x03 && lpData[3] == 0x04)
  1392. return false;
  1393. // JPEG
  1394. if (lpData[0] == 0xff && lpData[1] == 0xd8)
  1395. return false;
  1396. // GIF
  1397. if (lpData[0] == 'G' && lpData[1] == 'I' && lpData[2] == 'F' && lpData[3] == '8')
  1398. return false;
  1399. // PNG
  1400. if (lpData[0] == 0x89 && lpData[1] == 0x50 && lpData[2] == 0x4e && lpData[3] == 0x47 && lpData[4] == 0x0d && lpData[5] == 0x0a && lpData[6] == 0x1a && lpData[7] == 0x0a)
  1401. return false;
  1402. // RAR
  1403. if (lpData[0] == 0x52 && lpData[1] == 0x61 && lpData[2] == 0x72 && lpData[3] == 0x21 && lpData[4] == 0x1A && lpData[5] == 0x07)
  1404. return false;
  1405. // GZIP
  1406. if (lpData[0] == 0x1f && lpData[1] == 0x8b)
  1407. return false;
  1408. // XZ
  1409. if (lpData[0] == 0xfd && lpData[1] == '7' && lpData[2] == 'z' && lpData[3] == 'X' && lpData[4] == 'Z' && lpData[5] == 0x00)
  1410. return false;
  1411. // BZ (.bz2 et al)
  1412. if (lpData[0] == 0x42 && lpData[1] == 0x5A && lpData[2] == 0x68)
  1413. return false;
  1414. // MP3
  1415. if ((lpData[0] == 0x49 && lpData[1] == 0x44 && lpData[2] == 0x33) || (lpData[0] == 0xff && lpData[1] == 0xfb))
  1416. return false;
  1417. // FIXME what to do with PDF? ('%PDF')
  1418. return true;
  1419. }
  1420. /**
  1421. * Save a property in a new instance from a blob
  1422. *
  1423. * @param[in] ulInstanceId InstanceID to save data under
  1424. * @param[in] ulPropId unused, required by interface, see ECDatabaseAttachment
  1425. * @param[in] iSize size of lpData
  1426. * @param[in] lpData Data of property
  1427. *
  1428. * @return Kopano error code
  1429. */
  1430. ECRESULT ECFileAttachment::SaveAttachmentInstance(ULONG ulInstanceId,
  1431. ULONG ulPropId, size_t iSize, unsigned char *lpData)
  1432. {
  1433. bool compressible = EvaluateCompressibleness(lpData, iSize);
  1434. bool compressAttachment = compressible ? m_bFileCompression && iSize : false;
  1435. ECRESULT er = erSuccess;
  1436. string filename = CreateAttachmentFilename(ulInstanceId, compressAttachment);
  1437. gzFile gzfp = NULL;
  1438. int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IRGRP);
  1439. if (fd < 0) {
  1440. ec_log_err("Unable to open attachment \"%s\" for writing: %s", filename.c_str(), strerror(errno));
  1441. er = KCERR_DATABASE_ERROR;
  1442. goto exit;
  1443. }
  1444. // no need to remove the file, just overwrite it
  1445. if (compressAttachment) {
  1446. gzfp = gzdopen(fd, std::string("wb" + m_CompressionLevel).c_str());
  1447. if (!gzfp) {
  1448. ec_log_err("Unable to gzopen attachment \"%s\" for writing: %s", filename.c_str(), strerror(errno));
  1449. er = KCERR_DATABASE_ERROR;
  1450. goto exit;
  1451. }
  1452. ssize_t iWritten = gzwrite_retry(gzfp, lpData, iSize);
  1453. if (iWritten != static_cast<ssize_t>(iSize)) {
  1454. ec_log_err("Unable to gzwrite %lu bytes to attachment \"%s\", returned %lu.",
  1455. static_cast<unsigned long>(iSize), filename.c_str(), static_cast<unsigned long>(iWritten));
  1456. er = KCERR_DATABASE_ERROR;
  1457. goto exit;
  1458. }
  1459. }
  1460. else {
  1461. give_filesize_hint(fd, iSize);
  1462. ssize_t iWritten = write_retry(fd, lpData, iSize);
  1463. if (iWritten != static_cast<ssize_t>(iSize)) {
  1464. ec_log_err("Unable to write %lu bytes to attachment \"%s\": %s. Returned %lu.",
  1465. static_cast<unsigned long>(iSize), filename.c_str(), strerror(errno), static_cast<unsigned long>(iWritten));
  1466. er = KCERR_DATABASE_ERROR;
  1467. goto exit;
  1468. }
  1469. }
  1470. // set in transaction before disk full check to remove empty file
  1471. if(m_bTransaction)
  1472. m_setNewAttachment.insert(ulInstanceId);
  1473. exit:
  1474. if (gzfp != NULL) {
  1475. int ret = gzclose(gzfp);
  1476. if (ret != Z_OK) {
  1477. ec_log_err("gzclose on attachment \"%s\" failed: %s",
  1478. filename.c_str(), (ret == Z_ERRNO) ? strerror(errno) : gzerror(gzfp, NULL));
  1479. er = KCERR_DATABASE_ERROR;
  1480. }
  1481. fd = -1;
  1482. }
  1483. if (fd != -1)
  1484. close(fd);
  1485. return er;
  1486. }
  1487. /**
  1488. * Save a property in a new instance from a serializer
  1489. *
  1490. * @param[in] ulInstanceId InstanceID to save data under
  1491. * @param[in] ulPropId unused, required by interface, see ECDatabaseAttachment
  1492. * @param[in] iSize size in lpSource
  1493. * @param[in] lpSource serializer to read data from
  1494. *
  1495. * @return Kopano error code
  1496. */
  1497. ECRESULT ECFileAttachment::SaveAttachmentInstance(ULONG ulInstanceId,
  1498. ULONG ulPropId, size_t iSize, ECSerializer *lpSource)
  1499. {
  1500. ECRESULT er = erSuccess;
  1501. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1502. unsigned char szBuffer[CHUNK_SIZE];
  1503. size_t iSizeLeft = iSize;
  1504. int fd = open(filename.c_str(), O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
  1505. if (fd == -1) {
  1506. ec_log_err("Unable to open attachment \"%s\" for writing: %s.",
  1507. filename.c_str(), strerror(errno));
  1508. er = KCERR_DATABASE_ERROR;
  1509. goto exit;
  1510. }
  1511. //no need to remove the file, just overwrite it
  1512. if (m_bFileCompression) {
  1513. gzFile gzfp = gzdopen(fd, std::string("wb" + m_CompressionLevel).c_str());
  1514. if (!gzfp) {
  1515. ec_log_err("Unable to gzdopen attachment \"%s\" for writing: %s",
  1516. filename.c_str(), strerror(errno));
  1517. er = KCERR_DATABASE_ERROR;
  1518. goto exit;
  1519. }
  1520. // file created on disk, now in transaction
  1521. if (m_bTransaction)
  1522. m_setNewAttachment.insert(ulInstanceId);
  1523. while (iSizeLeft > 0) {
  1524. size_t iChunkSize = iSizeLeft < CHUNK_SIZE ? iSizeLeft : CHUNK_SIZE;
  1525. er = lpSource->Read(szBuffer, 1, iChunkSize);
  1526. if (er != erSuccess) {
  1527. ec_log_err("Problem retrieving attachment from ECSource: %s (0x%x)", GetMAPIErrorMessage(kcerr_to_mapierr(er, ~0U /* anything yielding UNKNOWN */)), er);
  1528. er = KCERR_DATABASE_ERROR;
  1529. break;
  1530. }
  1531. ssize_t iWritten = gzwrite_retry(gzfp, szBuffer, iChunkSize);
  1532. if (iWritten != static_cast<ssize_t>(iChunkSize)) {
  1533. ec_log_err("Unable to gzwrite %lu bytes to attachment \"%s\", returned %lu",
  1534. static_cast<unsigned long>(iChunkSize), filename.c_str(), static_cast<unsigned long>(iWritten));
  1535. er = KCERR_DATABASE_ERROR;
  1536. break;
  1537. }
  1538. iSizeLeft -= iChunkSize;
  1539. }
  1540. if (er == erSuccess) {
  1541. if (gzflush(gzfp, Z_FINISH)) {
  1542. int saved_errno = errno;
  1543. int zerror;
  1544. const char *zstrerr = gzerror(gzfp, &zerror);
  1545. ec_log_err("gzflush failed: %s (%d)", zstrerr, zerror);
  1546. if (zerror == Z_ERRNO)
  1547. ec_log_err("gzflush failed: stdio says: %s", strerror(saved_errno));
  1548. er = KCERR_DATABASE_ERROR;
  1549. }
  1550. if (force_changes_to_disk && !force_buffers_to_disk(fd)) {
  1551. ec_log_warn("Problem syncing file \"%s\": %s", filename.c_str(), strerror(errno));
  1552. er = KCERR_DATABASE_ERROR;
  1553. }
  1554. }
  1555. int ret = gzclose(gzfp);
  1556. if (ret != Z_OK) {
  1557. ec_log_err("Problem closing file \"%s\": %s",
  1558. filename.c_str(), (ret == Z_ERRNO) ? strerror(errno) : gzerror(gzfp, NULL));
  1559. er = KCERR_DATABASE_ERROR;
  1560. }
  1561. // if gzclose fails, we can't know if the fd is still valid or not
  1562. fd = -1;
  1563. }
  1564. else {
  1565. give_filesize_hint(fd, iSize);
  1566. // file created on disk, now in transaction
  1567. if (m_bTransaction)
  1568. m_setNewAttachment.insert(ulInstanceId);
  1569. while (iSizeLeft > 0) {
  1570. size_t iChunkSize = iSizeLeft < CHUNK_SIZE ? iSizeLeft : CHUNK_SIZE;
  1571. er = lpSource->Read(szBuffer, 1, iChunkSize);
  1572. if (er != erSuccess) {
  1573. ec_log_err("Problem retrieving attachment from ECSource: %s (0x%x)", GetMAPIErrorMessage(kcerr_to_mapierr(er, ~0U)), er);
  1574. er = KCERR_DATABASE_ERROR;
  1575. break;
  1576. }
  1577. ssize_t iWritten = write_retry(fd, szBuffer, iChunkSize);
  1578. if (iWritten != static_cast<ssize_t>(iChunkSize)) {
  1579. ec_log_err("Unable to write %lu bytes to streaming attachment: %s", static_cast<unsigned long>(iChunkSize), strerror(errno));
  1580. er = KCERR_DATABASE_ERROR;
  1581. break;
  1582. }
  1583. iSizeLeft -= iChunkSize;
  1584. }
  1585. if (er == erSuccess) {
  1586. if (force_changes_to_disk && !force_buffers_to_disk(fd)) {
  1587. ec_log_warn("Problem syncing file \"%s\": %s", filename.c_str(), strerror(errno));
  1588. er = KCERR_DATABASE_ERROR;
  1589. }
  1590. }
  1591. close(fd);
  1592. fd = -1;
  1593. }
  1594. exit:
  1595. if (er == erSuccess && m_dirFd != -1 && fsync(m_dirFd) == -1)
  1596. ec_log_warn("Problem syncing parent directory of \"%s\": %s", filename.c_str(), strerror(errno));
  1597. if (fd != -1)
  1598. close(fd);
  1599. return er;
  1600. }
  1601. /**
  1602. * Delete given instances from the filesystem
  1603. *
  1604. * @param[in] lstDeleteInstances List of instance ids to remove from the filesystem
  1605. * @param[in] bReplace Transaction marker
  1606. *
  1607. * @return Kopano error code
  1608. */
  1609. ECRESULT ECFileAttachment::DeleteAttachmentInstances(const std::list<ULONG> &lstDeleteInstances, bool bReplace)
  1610. {
  1611. ECRESULT er = erSuccess;
  1612. int errors = 0;
  1613. for (auto del_id : lstDeleteInstances) {
  1614. er = this->DeleteAttachmentInstance(del_id, bReplace);
  1615. if (er != erSuccess)
  1616. ++errors;
  1617. }
  1618. if (errors)
  1619. ec_log_err("ECFileAttachment::DeleteAttachmentInstances(): %x delete fails", errors);
  1620. return errors == 0 ? erSuccess : KCERR_DATABASE_ERROR;
  1621. }
  1622. /**
  1623. * Mark a file deleted by renaming it
  1624. *
  1625. * @param[in] ulInstanceId instance id to mark
  1626. *
  1627. * @return Kopano error code
  1628. */
  1629. ECRESULT ECFileAttachment::MarkAttachmentForDeletion(ULONG ulInstanceId)
  1630. {
  1631. ECRESULT er;
  1632. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1633. if(rename(filename.c_str(), string(filename+".deleted").c_str()) == 0)
  1634. return erSuccess;
  1635. if (errno == ENOENT) {
  1636. // retry with another filename
  1637. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression);
  1638. if(rename(filename.c_str(), string(filename+".deleted").c_str()) == 0)
  1639. return erSuccess;
  1640. }
  1641. // FIXME log in all errno cases
  1642. if (errno == EACCES || errno == EPERM)
  1643. er = KCERR_NO_ACCESS;
  1644. else if (errno == ENOENT)
  1645. er = KCERR_NOT_FOUND;
  1646. else {
  1647. er = KCERR_DATABASE_ERROR;
  1648. ec_log_err("ECFileAttachment::MarkAttachmentForDeletion(): cannot mark %u", ulInstanceId);
  1649. }
  1650. return er;
  1651. }
  1652. /**
  1653. * Revert a delete marked instance
  1654. *
  1655. * @param[in] ulInstanceId instance id to restore
  1656. *
  1657. * @return Kopano error code
  1658. */
  1659. ECRESULT ECFileAttachment::RestoreMarkedAttachment(ULONG ulInstanceId)
  1660. {
  1661. ECRESULT er;
  1662. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1663. if(rename(string(filename+".deleted").c_str(), filename.c_str()) == 0)
  1664. return erSuccess;
  1665. if (errno == ENOENT) {
  1666. // retry with another filename
  1667. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression);
  1668. if(rename(string(filename+".deleted").c_str(), filename.c_str()) == 0)
  1669. return erSuccess;
  1670. }
  1671. if (errno == EACCES || errno == EPERM)
  1672. er = KCERR_NO_ACCESS;
  1673. else if (errno == ENOENT)
  1674. er = KCERR_NOT_FOUND;
  1675. else {
  1676. er = KCERR_DATABASE_ERROR;
  1677. ec_log_err("ECFileAttachment::RestoreMarkedAttachment(): cannot mark %u", ulInstanceId);
  1678. }
  1679. return er;
  1680. }
  1681. /**
  1682. * Delete a marked instance from the filesystem
  1683. *
  1684. * @param[in] ulInstanceId instance id to remove
  1685. *
  1686. * @return Kopano error code
  1687. */
  1688. ECRESULT ECFileAttachment::DeleteMarkedAttachment(ULONG ulInstanceId)
  1689. {
  1690. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression) + ".deleted";
  1691. if (unlink(filename.c_str()) == 0)
  1692. return erSuccess;
  1693. if (errno == ENOENT) {
  1694. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression) + ".deleted";
  1695. if (unlink(filename.c_str()) == 0)
  1696. return erSuccess;
  1697. }
  1698. ECRESULT er = erSuccess;
  1699. ec_log_err("%s unlink %s failed: %s\n", __PRETTY_FUNCTION__, filename.c_str(), strerror(errno));
  1700. if (errno == EACCES || errno == EPERM)
  1701. er = KCERR_NO_ACCESS;
  1702. else if (errno != ENOENT) { // ignore "file not found" error
  1703. er = KCERR_DATABASE_ERROR;
  1704. ec_log_err("ECFileAttachment::DeleteMarkedAttachment() cannot delete instance %u", ulInstanceId);
  1705. }
  1706. return er;
  1707. }
  1708. /**
  1709. * Delete a single instanceid from the filesystem
  1710. *
  1711. * @param[in] ulInstanceId instance id to remove
  1712. * @param[in] bReplace Transaction marker
  1713. *
  1714. * @return
  1715. */
  1716. ECRESULT ECFileAttachment::DeleteAttachmentInstance(ULONG ulInstanceId, bool bReplace)
  1717. {
  1718. ECRESULT er = erSuccess;
  1719. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1720. if(m_bTransaction) {
  1721. if (bReplace) {
  1722. er = MarkAttachmentForDeletion(ulInstanceId);
  1723. if (er != erSuccess && er != KCERR_NOT_FOUND) {
  1724. assert(false);
  1725. return er;
  1726. } else if(er != KCERR_NOT_FOUND) {
  1727. m_setMarkedAttachment.insert(ulInstanceId);
  1728. }
  1729. er = erSuccess;
  1730. } else {
  1731. m_setDeletedAttachment.insert(ulInstanceId);
  1732. }
  1733. return er;
  1734. }
  1735. if (unlink(filename.c_str()) != 0) {
  1736. if (errno == ENOENT){
  1737. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression);
  1738. if (unlink(filename.c_str()) == 0)
  1739. return erSuccess;
  1740. }
  1741. if (errno == EACCES || errno == EPERM)
  1742. er = KCERR_NO_ACCESS;
  1743. else if (errno != ENOENT) { // ignore "file not found" error
  1744. er = KCERR_DATABASE_ERROR;
  1745. ec_log_err("ECFileAttachment::DeleteAttachmentInstance() id %u fail", ulInstanceId);
  1746. }
  1747. }
  1748. return er;
  1749. }
  1750. /**
  1751. * Return a filename for an instance id
  1752. *
  1753. * @param[in] ulInstanceId instance id to convert to a filename
  1754. * @param[in] bCompressed add compression marker to filename
  1755. *
  1756. * @return Kopano error code
  1757. */
  1758. std::string ECFileAttachment::CreateAttachmentFilename(ULONG ulInstanceId, bool bCompressed)
  1759. {
  1760. string filename;
  1761. unsigned int l1, l2;
  1762. l1 = ulInstanceId % ATTACH_PATHDEPTH_LEVEL1;
  1763. l2 = (ulInstanceId / ATTACH_PATHDEPTH_LEVEL1) % ATTACH_PATHDEPTH_LEVEL2;
  1764. filename = m_basepath + PATH_SEPARATOR + stringify(l1) + PATH_SEPARATOR + stringify(l2) + PATH_SEPARATOR + stringify(ulInstanceId);
  1765. if (bCompressed)
  1766. filename += ".gz";
  1767. return filename;
  1768. }
  1769. /**
  1770. * Return the size of an instance
  1771. *
  1772. * @param[in] ulInstanceId InstanceID to check the size for
  1773. * @param[out] lpulSize Size of the instance
  1774. * @param[out] lpbCompressed the instance was compressed
  1775. *
  1776. * @return Kopano error code
  1777. */
  1778. ECRESULT ECFileAttachment::GetSizeInstance(ULONG ulInstanceId, size_t *lpulSize, bool *lpbCompressed)
  1779. {
  1780. ECRESULT er = erSuccess;
  1781. string filename = CreateAttachmentFilename(ulInstanceId, m_bFileCompression);
  1782. bool bCompressed = m_bFileCompression;
  1783. struct stat st;
  1784. /*
  1785. * We are always going to use the normal FILE handler for determining the file size,
  1786. * the gzFile handler is broken since it doesn't support SEEK_END and gzseek itself
  1787. * is very slow. When the attachment has been zipped, we are going to read the
  1788. * last 4 bytes of the file, which contain the uncompressed filesize
  1789. * (provided that there is a single gzip stream).
  1790. *
  1791. * For uncompressed files we use fstat() which is the fastest as the inode is already
  1792. * in memory due to the earlier open().
  1793. */
  1794. int fd = open(filename.c_str(), O_RDONLY);
  1795. if (fd == -1) {
  1796. filename = CreateAttachmentFilename(ulInstanceId, !m_bFileCompression);
  1797. bCompressed = !m_bFileCompression;
  1798. fd = open(filename.c_str(), O_RDONLY);
  1799. }
  1800. if (fd == -1) {
  1801. ec_log_err("ECFileAttachment::GetSizeInstance(): file \"%s\" cannot be accessed: %s", filename.c_str(), strerror(errno));
  1802. er = KCERR_NOT_FOUND;
  1803. goto exit;
  1804. }
  1805. /* Uncompressed attachment */
  1806. if (fstat(fd, &st) == -1) {
  1807. ec_log_err("ECFileAttachment::GetSizeInstance(): file \"%s\" fstat failed: %s", filename.c_str(), strerror(errno));
  1808. // FIXME er = KCERR_DATABASE_ERROR;
  1809. goto exit;
  1810. }
  1811. if (!bCompressed) {
  1812. *lpulSize = st.st_size;
  1813. } else if (st.st_size >= 4) {
  1814. /* Compressed attachment */
  1815. // a compressed file of only 4 bytes does not exist so we could
  1816. // make this minimum size bigger
  1817. if (lseek(fd, -4, SEEK_END) == -1) {
  1818. ec_log_err("ECFileAttachment::GetSizeInstance(): file \"%s\" fseek (compressed file) failed: %s", filename.c_str(), strerror(errno));
  1819. // FIXME er = KCERR_DATABASE_ERROR;
  1820. goto exit;
  1821. }
  1822. // FIXME endianness
  1823. uint32_t atsize;
  1824. if (read_retry(fd, &atsize, 4) != 4) {
  1825. ec_log_err("ECFileAttachment::GetSizeInstance(): file \"%s\" fread failed: %s", filename.c_str(), strerror(errno));
  1826. // FIXME er = KCERR_DATABASE_ERROR;
  1827. goto exit;
  1828. }
  1829. if (st.st_size >= 40 && atsize == 0) {
  1830. ec_log_warn("ECFileAttachment: %s seems to be an unsupported multi-stream gzip file (KC-104).", filename.c_str());
  1831. //er = KCERR_DATABASE_ERROR;
  1832. goto exit;
  1833. }
  1834. *lpulSize = atsize;
  1835. } else {
  1836. *lpulSize = 0;
  1837. ec_log_debug("ECFileAttachment::GetSizeInstance(): file \"%s\" is truncated!", filename.c_str());
  1838. // FIXME return some error
  1839. }
  1840. if (lpbCompressed)
  1841. *lpbCompressed = bCompressed;
  1842. exit:
  1843. if (fd != -1)
  1844. close(fd);
  1845. return er;
  1846. }
  1847. ECRESULT ECFileAttachment::Begin()
  1848. {
  1849. if(m_bTransaction) {
  1850. // Possible a duplicate begin call, don't destroy the data in production
  1851. assert(false);
  1852. return erSuccess;
  1853. }
  1854. // Set begin values
  1855. m_setNewAttachment.clear();
  1856. m_setDeletedAttachment.clear();
  1857. m_setMarkedAttachment.clear();
  1858. m_bTransaction = true;
  1859. return erSuccess;
  1860. }
  1861. ECRESULT ECFileAttachment::Commit()
  1862. {
  1863. ECRESULT er = erSuccess;
  1864. bool bError = false;
  1865. if(!m_bTransaction) {
  1866. assert(false);
  1867. return erSuccess;
  1868. }
  1869. // Disable the transaction
  1870. m_bTransaction = false;
  1871. // Delete the attachments
  1872. for (auto att_id : m_setDeletedAttachment)
  1873. if (DeleteAttachmentInstance(att_id, false) != erSuccess)
  1874. bError = true;
  1875. // Delete marked attachments
  1876. for (auto att_id : m_setMarkedAttachment)
  1877. if (DeleteMarkedAttachment(att_id) != erSuccess)
  1878. bError = true;
  1879. if (bError) {
  1880. assert(false);
  1881. er = KCERR_DATABASE_ERROR;
  1882. ec_log_err("ECFileAttachment::Commit() error during commit");
  1883. }
  1884. m_setNewAttachment.clear();
  1885. m_setDeletedAttachment.clear();
  1886. m_setMarkedAttachment.clear();
  1887. return er;
  1888. }
  1889. ECRESULT ECFileAttachment::Rollback()
  1890. {
  1891. ECRESULT er = erSuccess;
  1892. bool bError = false;
  1893. if(!m_bTransaction) {
  1894. assert(false);
  1895. return erSuccess;
  1896. }
  1897. // Disable the transaction
  1898. m_bTransaction = false;
  1899. // Don't delete the attachments
  1900. m_setDeletedAttachment.clear();
  1901. // Remove the created attachments
  1902. for (auto att_id : m_setNewAttachment)
  1903. if (DeleteAttachmentInstance(att_id, false) != erSuccess)
  1904. bError = true;
  1905. // Restore marked attachment
  1906. for (auto att_id : m_setMarkedAttachment)
  1907. if (RestoreMarkedAttachment(att_id) != erSuccess)
  1908. bError = true;
  1909. m_setNewAttachment.clear();
  1910. m_setMarkedAttachment.clear();
  1911. if (bError) {
  1912. assert(false);
  1913. er = KCERR_DATABASE_ERROR;
  1914. ec_log_err("ECFileAttachment::Rollback() error");
  1915. }
  1916. return er;
  1917. }
  1918. } /* namespace */