FileManager.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security.Policy;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Microsoft.InformationProtection;
  10. using Microsoft.InformationProtection.File;
  11. using Microsoft.InformationProtection.Protection;
  12. namespace AipGateway.AIP
  13. {
  14. // public struct ProtectionDetails
  15. // {
  16. // public List<UserRoles> UserRoles;
  17. // public List<UserRights> UserRights;
  18. // public string TemplateId;
  19. // public bool IsProtected;
  20. // }
  21. public class FileManager : AbstractManager
  22. {
  23. private IFileProfile _profile = null;
  24. private IFileEngine _engine = null;
  25. public FileManager()
  26. {
  27. }
  28. ~FileManager() => this.Dispose(false);
  29. public override void Dispose()
  30. {
  31. this.Dispose(true);
  32. GC.SuppressFinalize((object)this);
  33. }
  34. protected virtual void Dispose(bool disposing)
  35. {
  36. lock (this)
  37. {
  38. if (_profile != null & _engine != null)
  39. {
  40. //_profile.UnloadEngineAsync(_engine.Settings.EngineId).Wait();
  41. }
  42. _engine = null;
  43. _profile = null;
  44. }
  45. }
  46. public override bool CreateProfile(ref MipContext mipContext)
  47. {
  48. try
  49. {
  50. var profileSettings = new FileProfileSettings(mipContext,
  51. CacheStorageType.OnDiskEncrypted,
  52. // CacheStorageType.InMemory,
  53. new ConsentDelegateImplementation());
  54. // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
  55. _profile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
  56. }
  57. catch (Exception e)
  58. {
  59. SetError(1, "FileManager::CreateProfile Failed.", e.Message);
  60. return false;
  61. }
  62. return _profile != null;
  63. }
  64. public override bool CreateEngine(ref Identity identity, ref AuthDelegateImplementation authDelegate)
  65. {
  66. try
  67. {
  68. authDelegate.ResetError();
  69. //CultureInfo.CurrentCulture.Name;
  70. // 보호 엔진 설정 개체를 만듭니다. 첫 번째 매개변수인 엔진 ID에 빈 문자열을 전달하면 SDK가 GUID를 생성합니다.
  71. // 이메일 주소나 기타 고유한 값을 전달하면 동일한 사용자에 대해 캐시된 엔진이 매번 로드되도록 하는 데 도움이 됩니다.
  72. // 로캘 설정은 지원되며 특히 클라이언트 응용 프로그램의 경우 컴퓨터 로캘을 기반으로 제공되어야 합니다.
  73. var engineSettings = new FileEngineSettings(identity.Email, authDelegate, string.Empty, "en-US")
  74. {
  75. // Provide the identity for service discovery.
  76. Identity = identity,
  77. // Set ProtectionOnlyEngine to true for AD RMS as labeling isn't supported
  78. //ProtectionOnlyEngine = true
  79. };
  80. // Enable DKE
  81. // var functionsDict = engineSettings.ConfiguredFunctionality ?? new Dictionary<FunctionalityFilterType, bool>();
  82. // functionsDict[FunctionalityFilterType.DoubleKeyProtection] = true;
  83. // functionsDict[FunctionalityFilterType.DoubleKeyUserDefinedProtection] = true;
  84. // engineSettings.ConfiguredFunctionality = functionsDict;
  85. _engine = Task.Run(async () => await _profile.AddEngineAsync(engineSettings)).Result;
  86. //Console.WriteLine("File Engine Sensitivity Labels ======================================================");
  87. //var labels = _engine.SensitivityLabels;
  88. //for (int ii = 0; ii < labels.Count; ii++)
  89. //{
  90. //Console.WriteLine("{0}: {1}, {2}", ii.ToString(), labels[ii].Id + " : " + labels[ii].Name, labels[ii].IsActive);
  91. // Label label = _engine.GetLabelById(labels[ii].Id);
  92. // if (label.Children.Count > 0)
  93. // {
  94. // for (int jj = 0; jj < label.Children.Count; jj++)
  95. // {
  96. // Console.WriteLine("\t{0}: {1}, {2}", jj.ToString(), label.Children[jj].Id + " : " + label.Children[jj].Name, label.Children[jj].IsActive);
  97. // }
  98. // }
  99. // Console.WriteLine("{0}: {1}, {2}, {3}, {4}, {5}", ii.ToString(), label.Id + " : " + label.Name, label.IsActive,
  100. // label.Sensitivity, label.ActionSource, label.Description);
  101. //}
  102. //Console.WriteLine("=======================================================================");
  103. }
  104. catch (Exception e)
  105. {
  106. if (authDelegate.LastErrNo != 0)
  107. {
  108. SetError(authDelegate.LastErrNo, "FileManager::CreateEngine Failed.", authDelegate.LastErrMsg);
  109. }
  110. else
  111. {
  112. SetError(2, "FileManager::CreateEngine Failed.", e.Message);
  113. }
  114. return false;
  115. }
  116. return _engine != null;
  117. }
  118. public IEnumerable<Label> SensitivityLabels()
  119. {
  120. return _engine.SensitivityLabels;
  121. }
  122. private IFileHandler CreateFileHandler(Stream inputStream, string outputFile)
  123. {
  124. if (inputStream == null)
  125. {
  126. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 스트림의 정보가 없습니다.");
  127. return null;
  128. }
  129. if (outputFile == null || outputFile.Length == 0)
  130. {
  131. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 출력 파일 이릅이 존재하지 않습니다.");
  132. return null;
  133. }
  134. try
  135. {
  136. var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputStream, outputFile, true))
  137. .Result;
  138. return handler;
  139. }
  140. catch (Exception ex)
  141. {
  142. SetError(91, "FileManager::CreateFileHandler Failed.", ex.Message);
  143. }
  144. return null;
  145. }
  146. private Int64 GetFileSize(string fileName)
  147. {
  148. try
  149. {
  150. return new FileInfo(fileName).Length;
  151. }
  152. catch { return 0; }
  153. }
  154. private IFileHandler CreateFileHandler(string inputFile, string outputFile)
  155. {
  156. if (!File.Exists(inputFile))
  157. {
  158. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 파일이 존재하지 않습니다. " + inputFile);
  159. return null;
  160. }
  161. try
  162. {
  163. var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputFile, outputFile, true))
  164. .Result;
  165. return handler;
  166. }
  167. catch (Exception ex)
  168. {
  169. SetError(91, "FileManager::CreateFileHandler Failed.", ex.Message);
  170. }
  171. return null;
  172. }
  173. public AipFileInfo GetFileInfo(Stream fileStream, string outputFileName)
  174. {
  175. //string outputFile = "c:\\data\\samplexxxxxx.pptx";// System.IO.Path.GetTempFileName();
  176. Console.WriteLine("FileManager::GetFileInfo: Create Template File, {0}", outputFileName);
  177. var handler = CreateFileHandler(fileStream, outputFileName);
  178. if (handler == null)
  179. {
  180. File.Delete(outputFileName);
  181. return null;
  182. }
  183. var result = GetFileInfo(handler);
  184. try
  185. {
  186. result.FileSize = fileStream.Length;
  187. File.Delete(outputFileName);
  188. }
  189. catch (Exception ex)
  190. {
  191. result.FileSize = 0;
  192. LastErrMsg = ex.Message;
  193. }
  194. return result;
  195. }
  196. public AipFileInfo GetFileInfo(string fileName)
  197. {
  198. var handler = CreateFileHandler(fileName, fileName);
  199. if (handler == null)
  200. {
  201. return null;
  202. }
  203. var result = GetFileInfo(handler);
  204. try
  205. {
  206. result.FileSize = GetFileSize(fileName);
  207. }
  208. catch(Exception ex)
  209. {
  210. result.FileSize = 0;
  211. LastErrMsg = ex.Message;
  212. }
  213. return result;
  214. }
  215. private AipFileInfo GetFileInfo(IFileHandler handler)
  216. {
  217. if (handler == null)
  218. {
  219. return null;
  220. }
  221. AipFileInfo fileInfo = new AipFileInfo
  222. {
  223. Content = null,
  224. Label = null,
  225. Protection = null,
  226. OutputFileName = null,
  227. FileSize = 0,
  228. };
  229. fileInfo.OutputFileName = handler.OutputFileName;
  230. if (handler.Label != null)
  231. {
  232. fileInfo.Content = new AipContentLabel()
  233. {
  234. //Label = Utilities.LabelToAip(handler.Label.Label),
  235. CreationTime = handler.Label.CreationTime,
  236. AssignmentMethod = (AipAssignmentMethod)handler.Label.AssignmentMethod,
  237. IsProtectionAppliedFromLabel = handler.Label.IsProtectionAppliedFromLabel,
  238. };
  239. fileInfo.Label = Utilities.LabelToAip(handler.Label.Label);
  240. }
  241. if (handler.Protection != null)
  242. {
  243. fileInfo.Protection = new AipProtection()
  244. {
  245. Owner = handler.Protection.Owner,
  246. IssuedTo = handler.Protection.IssuedTo,
  247. IsIssuedToOwner = handler.Protection.IsIssuedToOwner,
  248. ContentId = handler.Protection.ContentId,
  249. AuditedExtractAllowed = handler.Protection.AuditedExtractAllowed,
  250. BlockSize = handler.Protection.BlockSize,
  251. ProtectionDescriptor = null,
  252. };
  253. if (handler.Protection.ProtectionDescriptor != null)
  254. {
  255. fileInfo.Protection.ProtectionDescriptor = new AipProtectionDescriptor()
  256. {
  257. ProtectionType = (AipProtectionType)handler.Protection.ProtectionDescriptor.ProtectionType,
  258. TemplateId = handler.Protection.ProtectionDescriptor.TemplateId,
  259. LabelInformation = new AipLabelInfo(),
  260. LabelId = handler.Protection.ProtectionDescriptor.LabelId,
  261. Owner = handler.Protection.ProtectionDescriptor.Owner,
  262. ContentId = handler.Protection.ProtectionDescriptor.ContentId,
  263. Name = handler.Protection.ProtectionDescriptor.Name,
  264. Description = handler.Protection.ProtectionDescriptor.Description,
  265. AllowOfflineAccess = handler.Protection.ProtectionDescriptor.AllowOfflineAccess,
  266. Referrer = handler.Protection.ProtectionDescriptor.Referrer,
  267. ContentValidUntil = handler.Protection.ProtectionDescriptor.ContentValidUntil,
  268. DoubleKeyUrl = handler.Protection.ProtectionDescriptor.DoubleKeyUrl,
  269. };
  270. if (handler.Protection.ProtectionDescriptor.LabelInformation != null)
  271. {
  272. fileInfo.Protection.ProtectionDescriptor.LabelInformation.LabelId =
  273. handler.Protection.ProtectionDescriptor.LabelInformation.LabelId;
  274. fileInfo.Protection.ProtectionDescriptor.LabelInformation.TenantId =
  275. handler.Protection.ProtectionDescriptor.LabelInformation.TenantId;
  276. }
  277. }
  278. }
  279. return fileInfo;
  280. }
  281. public Label GetLabelById(string labelId)
  282. {
  283. Label label;
  284. try
  285. {
  286. label = _engine.GetLabelById(labelId);
  287. }
  288. catch (Exception ex)
  289. {
  290. SetError(99, "FileManager::GetLabel Failed. Request Label Id: " + labelId, ex.Message);
  291. return null;
  292. }
  293. return label;
  294. }
  295. /// <summary>
  296. /// ///////////////////////////////////////////////////////////////
  297. /// </summary>
  298. /// <param name="fileName"></param>
  299. /// <param name="actualFileName"></param>
  300. /// <param name="email"></param>
  301. /// <param name="labelId"></param>
  302. /// <param name="templateId"></param>
  303. /// <param name="comments"></param>
  304. /// <returns></returns>
  305. public SetFileInfo SetLabel(string fileName, string actualFileName, string email, string labelId, string templateId, string comments)
  306. {
  307. SetFileInfo result = new SetFileInfo()
  308. {
  309. errorNo = 0,
  310. errorMsg = "Success",
  311. };
  312. var handler = CreateFileHandler(fileName, actualFileName);
  313. if (handler == null)
  314. {
  315. result.errorNo = 201;
  316. result.errorMsg = LastErrMsg;
  317. return result;
  318. }
  319. result.fileSize = GetFileSize(fileName);
  320. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, result);
  321. }
  322. public SetFileInfo SetLabel(Stream fileStream, string actualFileName, string email, string labelId, string templateId, string comments)
  323. {
  324. SetFileInfo result = new SetFileInfo()
  325. {
  326. errorNo = 0,
  327. errorMsg = "Success",
  328. };
  329. var handler = CreateFileHandler(fileStream, actualFileName);
  330. if (handler == null)
  331. {
  332. result.errorNo = 201;
  333. result.errorMsg = LastErrMsg;
  334. return result;
  335. }
  336. result.fileSize = fileStream.Length;
  337. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, result);
  338. }
  339. public SetFileInfo SetLabel(IFileHandler handler, string actualFileName, string email, string labelId, string templateId, string comments, SetFileInfo result)
  340. {
  341. Label label = GetLabelById(labelId);
  342. if (label == null)
  343. {
  344. result.errorNo = 202;
  345. result.errorMsg = LastErrMsg;
  346. return result;
  347. }
  348. if (comments == "")
  349. {
  350. comments = "SetLabel";
  351. }
  352. LabelingOptions labelingOptions = new LabelingOptions()
  353. {
  354. AssignmentMethod = AssignmentMethod.Auto, //Standard,
  355. JustificationMessage = comments,
  356. IsDowngradeJustified = true
  357. };
  358. string ownerEmail = email;
  359. if (handler.Label != null && handler.Label.Label != null)
  360. {
  361. result.lableGuid = handler.Label.Label.Id;
  362. }
  363. if (handler.Protection != null)
  364. {
  365. ownerEmail = handler.Protection.Owner;
  366. result.fileOwner = handler.Protection.Owner;
  367. if (handler.Protection.ProtectionDescriptor != null)
  368. {
  369. result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
  370. }
  371. }
  372. var protectionSettings = new ProtectionSettings
  373. {
  374. PFileExtensionBehavior = PFileExtensionBehavior.Default,
  375. };
  376. if (ownerEmail != "")
  377. {
  378. protectionSettings.DelegatedUserEmail = ownerEmail;
  379. }
  380. try
  381. {
  382. handler.SetLabel(label, labelingOptions, protectionSettings);
  383. if (templateId != "")
  384. {
  385. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  386. handler.SetProtection(protectionDescriptor, protectionSettings);
  387. }
  388. }
  389. catch (Exception ex)
  390. {
  391. result.errorNo = 203;
  392. result.errorMsg = ex.Message;
  393. SetError(53, "FileManager::SetLabel Failed.", ex.Message);
  394. return result;
  395. }
  396. bool isCommited = false;
  397. if (handler.IsModified())
  398. {
  399. isCommited = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  400. }
  401. if (isCommited)
  402. {
  403. //handler.NotifyCommitSuccessful(fileName);
  404. result.newFileSize = GetFileSize(actualFileName);
  405. result.newFileLabelGuid = labelId;
  406. result.newFileName = actualFileName;
  407. result.newFileOwner = ownerEmail;
  408. result.newFileTemplateGuid = labelId;
  409. }
  410. else
  411. {
  412. result.errorNo = 204;
  413. result.errorMsg = "AIP File CommitAsync Failed.";
  414. SetError(53, "FileManager::SetLabel Failed.", "Label Id: " + labelId + ", SetLabel Failed.");
  415. }
  416. AipFileInfo info = GetFileInfo(actualFileName);
  417. if (info != null)
  418. {
  419. if (info.Label != null)
  420. {
  421. result.newFileLabelGuid = info.Label.Id;
  422. }
  423. if (info.Protection != null)
  424. {
  425. result.newFileOwner = info.Protection.Owner;
  426. if (info.Protection.ProtectionDescriptor != null)
  427. {
  428. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  429. }
  430. }
  431. }
  432. return result;
  433. }
  434. /// <summary>
  435. /// //////////////////////////////////////////////////////////////
  436. /// </summary>
  437. /// <param name="fileName"></param>
  438. /// <param name="actualFileName"></param>
  439. /// <param name="email"></param>
  440. /// <param name="comments"></param>
  441. /// <param name="isDelProtection"></param>
  442. /// <returns></returns>
  443. public SetFileInfo DeleteLabel(string fileName, string actualFileName, string email, string comments, bool isDelProtection)
  444. {
  445. SetFileInfo result = new SetFileInfo()
  446. {
  447. errorNo = 0,
  448. errorMsg = "Success",
  449. };
  450. var outFileName = actualFileName == string.Empty ? fileName : actualFileName;
  451. var handler = CreateFileHandler(fileName, outFileName);
  452. if (handler == null)
  453. {
  454. result.errorNo = 201;
  455. result.errorMsg = LastErrMsg;
  456. return result;
  457. }
  458. result.fileSize = GetFileSize(fileName);
  459. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, result);
  460. }
  461. public SetFileInfo DeleteLabel(Stream fileStream, string actualFileName, string email, string comments, bool isDelProtection)
  462. {
  463. SetFileInfo result = new SetFileInfo()
  464. {
  465. errorNo = 0,
  466. errorMsg = "Success",
  467. };
  468. var handler = CreateFileHandler(fileStream, actualFileName);
  469. if (handler == null)
  470. {
  471. result.errorNo = 201;
  472. result.errorMsg = LastErrMsg;
  473. return result;
  474. }
  475. result.fileSize = fileStream.Length;
  476. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, result);
  477. }
  478. public SetFileInfo DeleteLabel(IFileHandler handler, string actualFileName, string email, string comments, bool isDelProtection, SetFileInfo result)
  479. {
  480. if (comments == "")
  481. {
  482. comments = "Delete Label by " + email;
  483. }
  484. LabelingOptions invokeLabelingOptions = new LabelingOptions()
  485. {
  486. AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  487. JustificationMessage = comments,
  488. IsDowngradeJustified = true
  489. };
  490. string ownerEmail = email;
  491. if (handler.Label != null && handler.Label.Label != null)
  492. {
  493. result.lableGuid = handler.Label.Label.Id;
  494. }
  495. if (handler.Protection != null)
  496. {
  497. ownerEmail = handler.Protection.Owner;
  498. result.fileOwner = handler.Protection.Owner;
  499. if (handler.Protection.ProtectionDescriptor != null)
  500. {
  501. result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
  502. }
  503. }
  504. var protectionSettings = new ProtectionSettings
  505. {
  506. PFileExtensionBehavior = PFileExtensionBehavior.Default,
  507. };
  508. if (ownerEmail != "")
  509. {
  510. protectionSettings.DelegatedUserEmail = ownerEmail;
  511. }
  512. try
  513. {
  514. if (isDelProtection && handler.Protection != null)
  515. {
  516. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  517. {
  518. handler.RemoveProtection();
  519. }
  520. }
  521. handler.DeleteLabel(invokeLabelingOptions);
  522. }
  523. catch (Exception ex)
  524. {
  525. result.errorNo = 203;
  526. result.errorMsg = ex.Message;
  527. SetError(53, "FileManager::DeleteLabel Failed.", ex.Message);
  528. return result;
  529. }
  530. bool isCommited = false;
  531. if (handler.IsModified())
  532. {
  533. isCommited = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  534. }
  535. if (isCommited)
  536. {
  537. //handler.NotifyCommitSuccessful(fileName);
  538. result.newFileSize = GetFileSize(actualFileName);
  539. result.newFileLabelGuid = "";
  540. result.newFileName = actualFileName;
  541. result.newFileOwner = ownerEmail;
  542. result.newFileTemplateGuid = "";
  543. }
  544. else
  545. {
  546. result.errorNo = 204;
  547. result.errorMsg = "AIP File CommitAsync Failed.";
  548. SetError(54, "FileManager::DeleteLabel Failed.", "DeleteLabel Failed by " + ownerEmail);
  549. }
  550. AipFileInfo info = GetFileInfo(actualFileName);
  551. if (info != null)
  552. {
  553. if (info.Label != null)
  554. {
  555. result.newFileLabelGuid = info.Label.Id;
  556. }
  557. if (info.Protection != null)
  558. {
  559. result.newFileOwner = info.Protection.Owner;
  560. if (info.Protection.ProtectionDescriptor != null)
  561. {
  562. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  563. }
  564. }
  565. }
  566. return result;
  567. }
  568. /// <summary>
  569. /// /////////////////////////////////////////////////////////////////
  570. /// </summary>
  571. /// <param name="fileName"></param>
  572. /// <param name="actualFileName"></param>
  573. /// <param name="email"></param>
  574. /// <param name="templateId"></param>
  575. /// <param name="comments"></param>
  576. /// <returns></returns>
  577. public SetFileInfo SetProtection(string fileName, string actualFileName, string email, string templateId, string comments)
  578. {
  579. SetFileInfo result = new SetFileInfo()
  580. {
  581. errorNo = 0,
  582. errorMsg = "Success",
  583. };
  584. var handler = CreateFileHandler(fileName, actualFileName);
  585. if (handler == null)
  586. {
  587. result.errorNo = 201;
  588. result.errorMsg = LastErrMsg;
  589. return result;
  590. }
  591. result.fileSize = GetFileSize(fileName);
  592. return SetProtection(handler, actualFileName, email, templateId, comments, result);
  593. }
  594. public SetFileInfo SetProtection(Stream fileStream, string actualFileName, string email, string templateId, string comments)
  595. {
  596. SetFileInfo result = new SetFileInfo()
  597. {
  598. errorNo = 0,
  599. errorMsg = "Success",
  600. };
  601. var handler = CreateFileHandler(fileStream, actualFileName);
  602. if (handler == null)
  603. {
  604. result.errorNo = 201;
  605. result.errorMsg = LastErrMsg;
  606. return result;
  607. }
  608. result.fileSize = fileStream.Length;
  609. return SetProtection(handler, actualFileName, email, templateId, comments, result);
  610. }
  611. public SetFileInfo SetProtection(IFileHandler handler, string actualFileName, string email, string templateId, string comments, SetFileInfo result)
  612. {
  613. if (comments == "")
  614. {
  615. comments = "SetProtection";
  616. }
  617. string ownerEmail = email;
  618. if (handler.Label != null && handler.Label.Label != null)
  619. {
  620. result.lableGuid = handler.Label.Label.Id;
  621. }
  622. if (handler.Protection != null)
  623. {
  624. ownerEmail = handler.Protection.Owner;
  625. result.fileOwner = handler.Protection.Owner;
  626. if (handler.Protection.ProtectionDescriptor != null)
  627. {
  628. result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
  629. }
  630. }
  631. try
  632. {
  633. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  634. ProtectionSettings protectionSettings = new ProtectionSettings
  635. {
  636. PFileExtensionBehavior = PFileExtensionBehavior.Default,
  637. };
  638. if (ownerEmail != "")
  639. {
  640. protectionSettings.DelegatedUserEmail = ownerEmail;
  641. }
  642. handler.SetProtection(protectionDescriptor, protectionSettings);
  643. }
  644. catch (Exception ex)
  645. {
  646. result.errorNo = 204;
  647. result.errorMsg = ex.Message;
  648. SetError(54, "FileManager::SetProtect Failed.", ex.Message);
  649. return result;
  650. }
  651. bool isCommited = false;
  652. if (handler.IsModified())
  653. {
  654. try
  655. {
  656. isCommited = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  657. }
  658. catch (Exception ex)
  659. {
  660. // TODO: Exception catch 해야함.......... 여기서 캣치하면 정확한 오류 메시지를 확인 할 수 없음.
  661. result.errorNo = 205;
  662. result.errorMsg = "AIP File CommitAsync Failed." + ex.Message;
  663. SetError(55, "FileManager::SetProtection CommitAsync Failed.", ex.Message);
  664. }
  665. }
  666. if (isCommited)
  667. {
  668. //handler.NotifyCommitSuccessful(fileName);
  669. result.newFileSize = GetFileSize(actualFileName);
  670. //result.newFileLabelGuid = string.Empty;
  671. result.newFileName = actualFileName;
  672. result.newFileOwner = ownerEmail;
  673. result.newFileTemplateGuid = string.Empty;
  674. }
  675. else
  676. {
  677. result.errorNo = 206;
  678. result.errorMsg = "AIP File CommitAsync Failed.";
  679. SetError(56, "FileManager::SetProtect Failed.", "Template Id: " + templateId + ", SetProtect Failed.");
  680. }
  681. AipFileInfo info = GetFileInfo(actualFileName);
  682. if (info != null)
  683. {
  684. if (info.Label != null)
  685. {
  686. result.newFileLabelGuid = info.Label.Id;
  687. }
  688. if (info.Protection != null)
  689. {
  690. result.newFileOwner = info.Protection.Owner;
  691. if (info.Protection.ProtectionDescriptor != null)
  692. {
  693. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  694. }
  695. }
  696. }
  697. return result;
  698. }
  699. /// <summary>
  700. /// ///////////////////////////////////////////////////////////////////
  701. /// </summary>
  702. /// <param name="fileName"></param>
  703. /// <param name="actualFileName"></param>
  704. /// <param name="email"></param>
  705. /// <param name="comments"></param>
  706. /// <returns></returns>
  707. public SetFileInfo RemoveProtection(string fileName, string actualFileName, string email, string comments)
  708. {
  709. SetFileInfo result = new SetFileInfo()
  710. {
  711. errorNo = 0,
  712. errorMsg = "Success",
  713. };
  714. var handler = CreateFileHandler(fileName, actualFileName);
  715. if (handler == null)
  716. {
  717. result.errorNo = 201;
  718. result.errorMsg = LastErrMsg;
  719. return result;
  720. }
  721. result.fileSize = GetFileSize(fileName);
  722. return RemoveProtection(handler, actualFileName, email, comments, result);
  723. }
  724. public SetFileInfo RemoveProtection(Stream fileStream, string actualFileName, string email, string comments)
  725. {
  726. SetFileInfo result = new SetFileInfo()
  727. {
  728. errorNo = 0,
  729. errorMsg = "Success",
  730. };
  731. var handler = CreateFileHandler(fileStream, actualFileName);
  732. if (handler == null)
  733. {
  734. result.errorNo = 201;
  735. result.errorMsg = LastErrMsg;
  736. return result;
  737. }
  738. result.fileSize = fileStream.Length;
  739. return RemoveProtection(handler, actualFileName, email, comments, result);
  740. }
  741. public SetFileInfo RemoveProtection(IFileHandler handler, string actualFileName, string email, string comments, SetFileInfo result)
  742. {
  743. string ownerEmail = email;
  744. if (handler.Label != null && handler.Label.Label != null)
  745. {
  746. result.lableGuid = handler.Label.Label.Id;
  747. }
  748. if (handler.Protection != null)
  749. {
  750. ownerEmail = handler.Protection.Owner;
  751. }
  752. if (comments == "")
  753. {
  754. comments = "Delete Protection by " + ownerEmail;
  755. }
  756. LabelingOptions invokeLabelingOptions = new LabelingOptions()
  757. {
  758. AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  759. JustificationMessage = comments,
  760. IsDowngradeJustified = true,
  761. };
  762. var protectionSettings = new ProtectionSettings
  763. {
  764. PFileExtensionBehavior = PFileExtensionBehavior.Default,
  765. };
  766. if (ownerEmail != "")
  767. {
  768. protectionSettings.DelegatedUserEmail = ownerEmail;
  769. }
  770. try
  771. {
  772. if (handler.Protection != null)
  773. {
  774. // 원본 파일 형식이 레이블 지정을 지원하지 않는 경우 보호를 제거하면 레이블이 손실됩니다.
  775. // 기본 형식이 레이블 지정을 지원하는 경우 레이블 메타데이터가 유지됩니다.
  776. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  777. {
  778. handler.RemoveProtection();
  779. }
  780. //Use the GetTemporaryDecryptedStream() or GetTemporaryDecryptedFile() API to create a temp decrypted output to render in your application.
  781. }
  782. else
  783. {
  784. result.errorNo = 209;
  785. result.errorMsg = "파일에 암호화 정보가 없습니다.";
  786. return result;
  787. }
  788. }
  789. catch (Exception ex)
  790. {
  791. result.errorNo = 208;
  792. result.errorMsg = "FileManager::RemoveProtection Failed." + ex.Message;
  793. SetError(59, "FileManager::RemoveProtection Failed.", ex.Message);
  794. return result;
  795. }
  796. bool isCommited = false;
  797. if (handler.IsModified())
  798. {
  799. isCommited = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  800. }
  801. if (isCommited)
  802. {
  803. //handler.NotifyCommitSuccessful(fileName);
  804. result.newFileSize = GetFileSize(actualFileName);
  805. result.newFileLabelGuid = string.Empty;
  806. result.newFileName = actualFileName;
  807. result.newFileOwner = ownerEmail;
  808. result.newFileTemplateGuid = string.Empty;
  809. }
  810. else
  811. {
  812. result.errorNo = 204;
  813. result.errorMsg = "AIP File CommitAsync Failed.";
  814. SetError(53, "FileManager::RemoveProtection Failed.", "RemoveProtection Failed by " + ownerEmail);
  815. }
  816. AipFileInfo info = GetFileInfo(actualFileName);
  817. if (info != null)
  818. {
  819. if (info.Label != null)
  820. {
  821. result.newFileLabelGuid = info.Label.Id;
  822. }
  823. if (info.Protection != null)
  824. {
  825. result.newFileOwner = info.Protection.Owner;
  826. if (info.Protection.ProtectionDescriptor != null)
  827. {
  828. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  829. }
  830. }
  831. }
  832. return result;
  833. }
  834. public async Task<Stream> GetDecryptedStreamAsync(Stream inputStream, string filename)
  835. {
  836. var handler = CreateFileHandler(inputStream, filename);
  837. return await handler.GetDecryptedTemporaryStreamAsync();
  838. }
  839. // Protect the input bytes.
  840. public byte[] Protect(IProtectionHandler handler, byte[] data)
  841. {
  842. long buffersize = handler.GetProtectedContentLength(data.Length, true);
  843. byte[] outputBuffer = new byte[buffersize];
  844. handler.EncryptBuffer(0, data, outputBuffer, true);
  845. return outputBuffer;
  846. }
  847. public byte[] Unprotect(IProtectionHandler handler, byte[] data)
  848. {
  849. long buffersize = data.Length;
  850. byte[] clearBuffer = new byte[buffersize];
  851. var bytesDecrypted = handler.DecryptBuffer(0, data, clearBuffer, true);
  852. byte[] outputBuffer = new byte[bytesDecrypted];
  853. for (int i = 0; i < bytesDecrypted; i++)
  854. {
  855. outputBuffer[i] = clearBuffer[i];
  856. }
  857. return outputBuffer;
  858. }
  859. }
  860. }
  861. #if false
  862. public bool SetLabel(FileOptions options)
  863. {
  864. // LabelingOptions allows us to set the metadata associated with the labeling operations.
  865. // Review the API Spec at https://aka.ms/mipsdkdocs for details
  866. LabelingOptions labelingOptions = new LabelingOptions()
  867. {
  868. AssignmentMethod = options.AssignmentMethod
  869. };
  870. var handler = CreateFileHandler(options);
  871. // Use the SetLabel method on the handler, providing label ID and LabelingOptions
  872. // The handler already references a file, so those details aren't needed.
  873. try
  874. {
  875. handler.SetLabel(engine.GetLabelById(options.LabelId), labelingOptions, new ProtectionSettings());
  876. }
  877. catch (Microsoft.InformationProtection.Exceptions.JustificationRequiredException)
  878. {
  879. Console.Write("Please provide justification: ");
  880. string justification = Console.ReadLine();
  881. labelingOptions.IsDowngradeJustified = true;
  882. labelingOptions.JustificationMessage = justification;
  883. handler.SetLabel(engine.GetLabelById(options.LabelId), labelingOptions, new ProtectionSettings());
  884. }
  885. catch (Microsoft.InformationProtection.Exceptions.AdhocProtectionRequiredException)
  886. {
  887. List<string> users = new List<string>()
  888. {
  889. "user1@contoso.com",
  890. "user2@contoso.com"
  891. };
  892. List<string> roles = new List<string>()
  893. {
  894. Microsoft.InformationProtection.Protection.Roles.Viewer
  895. };
  896. List<UserRoles> userroles = new List<UserRoles>()
  897. {
  898. new UserRoles(users, roles)
  899. };
  900. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(userroles);
  901. handler.SetProtection(protectionDescriptor, new ProtectionSettings());
  902. handler.SetLabel(engine.GetLabelById(options.LabelId), labelingOptions, new ProtectionSettings());
  903. }
  904. // The change isn't committed to the file referenced by the handler until CommitAsync() is called.
  905. // Pass the desired output file name in to the CommitAsync() function.
  906. bool result = false;
  907. // Only call commit if the handler has been modified.
  908. if(handler.IsModified())
  909. {
  910. result = Task.Run(async () => await handler.CommitAsync(options.OutputName)).Result;
  911. }
  912. // If the commit was successful and GenerateChangeAuditEvents is true, call NotifyCommitSuccessful()
  913. if (result && options.GenerateChangeAuditEvent)
  914. {
  915. // Submits and audit event about the labeling action to Azure Information Protection Analytics
  916. handler.NotifyCommitSuccessful(options.FileName);
  917. }
  918. return result;
  919. }
  920. #endif