1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include "app.hpp"
19 #include "dbus_utility.hpp"
20 #include "error_messages.hpp"
21 #include "generated/enums/log_entry.hpp"
22 #include "gzfile.hpp"
23 #include "http_utility.hpp"
24 #include "human_sort.hpp"
25 #include "query.hpp"
26 #include "registries.hpp"
27 #include "registries/base_message_registry.hpp"
28 #include "registries/openbmc_message_registry.hpp"
29 #include "registries/privilege_registry.hpp"
30 #include "task.hpp"
31 #include "utils/dbus_utils.hpp"
32 #include "utils/time_utils.hpp"
33 
34 #include <systemd/sd-journal.h>
35 #include <tinyxml2.h>
36 #include <unistd.h>
37 
38 #include <boost/algorithm/string/case_conv.hpp>
39 #include <boost/algorithm/string/classification.hpp>
40 #include <boost/algorithm/string/replace.hpp>
41 #include <boost/algorithm/string/split.hpp>
42 #include <boost/beast/http/verb.hpp>
43 #include <boost/container/flat_map.hpp>
44 #include <boost/system/linux_error.hpp>
45 #include <sdbusplus/asio/property.hpp>
46 #include <sdbusplus/unpack_properties.hpp>
47 
48 #include <array>
49 #include <charconv>
50 #include <filesystem>
51 #include <optional>
52 #include <span>
53 #include <string_view>
54 #include <variant>
55 
56 namespace redfish
57 {
58 
59 constexpr char const* crashdumpObject = "com.intel.crashdump";
60 constexpr char const* crashdumpPath = "/com/intel/crashdump";
61 constexpr char const* crashdumpInterface = "com.intel.crashdump";
62 constexpr char const* deleteAllInterface =
63     "xyz.openbmc_project.Collection.DeleteAll";
64 constexpr char const* crashdumpOnDemandInterface =
65     "com.intel.crashdump.OnDemand";
66 constexpr char const* crashdumpTelemetryInterface =
67     "com.intel.crashdump.Telemetry";
68 
69 enum class DumpCreationProgress
70 {
71     DUMP_CREATE_SUCCESS,
72     DUMP_CREATE_FAILED,
73     DUMP_CREATE_INPROGRESS
74 };
75 
76 namespace fs = std::filesystem;
77 
78 inline std::string translateSeverityDbusToRedfish(const std::string& s)
79 {
80     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Alert") ||
81         (s == "xyz.openbmc_project.Logging.Entry.Level.Critical") ||
82         (s == "xyz.openbmc_project.Logging.Entry.Level.Emergency") ||
83         (s == "xyz.openbmc_project.Logging.Entry.Level.Error"))
84     {
85         return "Critical";
86     }
87     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Debug") ||
88         (s == "xyz.openbmc_project.Logging.Entry.Level.Informational") ||
89         (s == "xyz.openbmc_project.Logging.Entry.Level.Notice"))
90     {
91         return "OK";
92     }
93     if (s == "xyz.openbmc_project.Logging.Entry.Level.Warning")
94     {
95         return "Warning";
96     }
97     return "";
98 }
99 
100 inline std::optional<bool> getProviderNotifyAction(const std::string& notify)
101 {
102     std::optional<bool> notifyAction;
103     if (notify == "xyz.openbmc_project.Logging.Entry.Notify.Notify")
104     {
105         notifyAction = true;
106     }
107     else if (notify == "xyz.openbmc_project.Logging.Entry.Notify.Inhibit")
108     {
109         notifyAction = false;
110     }
111 
112     return notifyAction;
113 }
114 
115 inline static int getJournalMetadata(sd_journal* journal,
116                                      std::string_view field,
117                                      std::string_view& contents)
118 {
119     const char* data = nullptr;
120     size_t length = 0;
121     int ret = 0;
122     // Get the metadata from the requested field of the journal entry
123     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
124     const void** dataVoid = reinterpret_cast<const void**>(&data);
125 
126     ret = sd_journal_get_data(journal, field.data(), dataVoid, &length);
127     if (ret < 0)
128     {
129         return ret;
130     }
131     contents = std::string_view(data, length);
132     // Only use the content after the "=" character.
133     contents.remove_prefix(std::min(contents.find('=') + 1, contents.size()));
134     return ret;
135 }
136 
137 inline static int getJournalMetadata(sd_journal* journal,
138                                      std::string_view field, const int& base,
139                                      long int& contents)
140 {
141     int ret = 0;
142     std::string_view metadata;
143     // Get the metadata from the requested field of the journal entry
144     ret = getJournalMetadata(journal, field, metadata);
145     if (ret < 0)
146     {
147         return ret;
148     }
149     contents = strtol(metadata.data(), nullptr, base);
150     return ret;
151 }
152 
153 inline static bool getEntryTimestamp(sd_journal* journal,
154                                      std::string& entryTimestamp)
155 {
156     int ret = 0;
157     uint64_t timestamp = 0;
158     ret = sd_journal_get_realtime_usec(journal, &timestamp);
159     if (ret < 0)
160     {
161         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
162                          << strerror(-ret);
163         return false;
164     }
165     entryTimestamp = redfish::time_utils::getDateTimeUintUs(timestamp);
166     return true;
167 }
168 
169 inline static bool getUniqueEntryID(sd_journal* journal, std::string& entryID,
170                                     const bool firstEntry = true)
171 {
172     int ret = 0;
173     static uint64_t prevTs = 0;
174     static int index = 0;
175     if (firstEntry)
176     {
177         prevTs = 0;
178     }
179 
180     // Get the entry timestamp
181     uint64_t curTs = 0;
182     ret = sd_journal_get_realtime_usec(journal, &curTs);
183     if (ret < 0)
184     {
185         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
186                          << strerror(-ret);
187         return false;
188     }
189     // If the timestamp isn't unique, increment the index
190     if (curTs == prevTs)
191     {
192         index++;
193     }
194     else
195     {
196         // Otherwise, reset it
197         index = 0;
198     }
199     // Save the timestamp
200     prevTs = curTs;
201 
202     entryID = std::to_string(curTs);
203     if (index > 0)
204     {
205         entryID += "_" + std::to_string(index);
206     }
207     return true;
208 }
209 
210 static bool getUniqueEntryID(const std::string& logEntry, std::string& entryID,
211                              const bool firstEntry = true)
212 {
213     static time_t prevTs = 0;
214     static int index = 0;
215     if (firstEntry)
216     {
217         prevTs = 0;
218     }
219 
220     // Get the entry timestamp
221     std::time_t curTs = 0;
222     std::tm timeStruct = {};
223     std::istringstream entryStream(logEntry);
224     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
225     {
226         curTs = std::mktime(&timeStruct);
227     }
228     // If the timestamp isn't unique, increment the index
229     if (curTs == prevTs)
230     {
231         index++;
232     }
233     else
234     {
235         // Otherwise, reset it
236         index = 0;
237     }
238     // Save the timestamp
239     prevTs = curTs;
240 
241     entryID = std::to_string(curTs);
242     if (index > 0)
243     {
244         entryID += "_" + std::to_string(index);
245     }
246     return true;
247 }
248 
249 inline static bool
250     getTimestampFromID(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
251                        const std::string& entryID, uint64_t& timestamp,
252                        uint64_t& index)
253 {
254     if (entryID.empty())
255     {
256         return false;
257     }
258     // Convert the unique ID back to a timestamp to find the entry
259     std::string_view tsStr(entryID);
260 
261     auto underscorePos = tsStr.find('_');
262     if (underscorePos != std::string_view::npos)
263     {
264         // Timestamp has an index
265         tsStr.remove_suffix(tsStr.size() - underscorePos);
266         std::string_view indexStr(entryID);
267         indexStr.remove_prefix(underscorePos + 1);
268         auto [ptr, ec] = std::from_chars(
269             indexStr.data(), indexStr.data() + indexStr.size(), index);
270         if (ec != std::errc())
271         {
272             messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
273             return false;
274         }
275     }
276     // Timestamp has no index
277     auto [ptr, ec] =
278         std::from_chars(tsStr.data(), tsStr.data() + tsStr.size(), timestamp);
279     if (ec != std::errc())
280     {
281         messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
282         return false;
283     }
284     return true;
285 }
286 
287 static bool
288     getRedfishLogFiles(std::vector<std::filesystem::path>& redfishLogFiles)
289 {
290     static const std::filesystem::path redfishLogDir = "/var/log";
291     static const std::string redfishLogFilename = "redfish";
292 
293     // Loop through the directory looking for redfish log files
294     for (const std::filesystem::directory_entry& dirEnt :
295          std::filesystem::directory_iterator(redfishLogDir))
296     {
297         // If we find a redfish log file, save the path
298         std::string filename = dirEnt.path().filename();
299         if (filename.starts_with(redfishLogFilename))
300         {
301             redfishLogFiles.emplace_back(redfishLogDir / filename);
302         }
303     }
304     // As the log files rotate, they are appended with a ".#" that is higher for
305     // the older logs. Since we don't expect more than 10 log files, we
306     // can just sort the list to get them in order from newest to oldest
307     std::sort(redfishLogFiles.begin(), redfishLogFiles.end());
308 
309     return !redfishLogFiles.empty();
310 }
311 
312 inline log_entry::OriginatorTypes
313     mapDbusOriginatorTypeToRedfish(const std::string& originatorType)
314 {
315     if (originatorType ==
316         "xyz.openbmc_project.Common.OriginatedBy.OriginatorTypes.Client")
317     {
318         return log_entry::OriginatorTypes::Client;
319     }
320     if (originatorType ==
321         "xyz.openbmc_project.Common.OriginatedBy.OriginatorTypes.Internal")
322     {
323         return log_entry::OriginatorTypes::Internal;
324     }
325     if (originatorType ==
326         "xyz.openbmc_project.Common.OriginatedBy.OriginatorTypes.SupportingService")
327     {
328         return log_entry::OriginatorTypes::SupportingService;
329     }
330     return log_entry::OriginatorTypes::Invalid;
331 }
332 
333 inline void parseDumpEntryFromDbusObject(
334     const dbus::utility::ManagedObjectType::value_type& object,
335     std::string& dumpStatus, uint64_t& size, uint64_t& timestampUs,
336     std::string& originatorId, log_entry::OriginatorTypes& originatorType,
337     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
338 {
339     for (const auto& interfaceMap : object.second)
340     {
341         if (interfaceMap.first == "xyz.openbmc_project.Common.Progress")
342         {
343             for (const auto& propertyMap : interfaceMap.second)
344             {
345                 if (propertyMap.first == "Status")
346                 {
347                     const auto* status =
348                         std::get_if<std::string>(&propertyMap.second);
349                     if (status == nullptr)
350                     {
351                         messages::internalError(asyncResp->res);
352                         break;
353                     }
354                     dumpStatus = *status;
355                 }
356             }
357         }
358         else if (interfaceMap.first == "xyz.openbmc_project.Dump.Entry")
359         {
360             for (const auto& propertyMap : interfaceMap.second)
361             {
362                 if (propertyMap.first == "Size")
363                 {
364                     const auto* sizePtr =
365                         std::get_if<uint64_t>(&propertyMap.second);
366                     if (sizePtr == nullptr)
367                     {
368                         messages::internalError(asyncResp->res);
369                         break;
370                     }
371                     size = *sizePtr;
372                     break;
373                 }
374             }
375         }
376         else if (interfaceMap.first == "xyz.openbmc_project.Time.EpochTime")
377         {
378             for (const auto& propertyMap : interfaceMap.second)
379             {
380                 if (propertyMap.first == "Elapsed")
381                 {
382                     const uint64_t* usecsTimeStamp =
383                         std::get_if<uint64_t>(&propertyMap.second);
384                     if (usecsTimeStamp == nullptr)
385                     {
386                         messages::internalError(asyncResp->res);
387                         break;
388                     }
389                     timestampUs = *usecsTimeStamp;
390                     break;
391                 }
392             }
393         }
394         else if (interfaceMap.first ==
395                  "xyz.openbmc_project.Common.OriginatedBy")
396         {
397             for (const auto& propertyMap : interfaceMap.second)
398             {
399                 if (propertyMap.first == "OriginatorId")
400                 {
401                     const std::string* id =
402                         std::get_if<std::string>(&propertyMap.second);
403                     if (id == nullptr)
404                     {
405                         messages::internalError(asyncResp->res);
406                         break;
407                     }
408                     originatorId = *id;
409                 }
410 
411                 if (propertyMap.first == "OriginatorType")
412                 {
413                     const std::string* type =
414                         std::get_if<std::string>(&propertyMap.second);
415                     if (type == nullptr)
416                     {
417                         messages::internalError(asyncResp->res);
418                         break;
419                     }
420 
421                     originatorType = mapDbusOriginatorTypeToRedfish(*type);
422                     if (originatorType == log_entry::OriginatorTypes::Invalid)
423                     {
424                         messages::internalError(asyncResp->res);
425                         break;
426                     }
427                 }
428             }
429         }
430     }
431 }
432 
433 static std::string getDumpEntriesPath(const std::string& dumpType)
434 {
435     std::string entriesPath;
436 
437     if (dumpType == "BMC")
438     {
439         entriesPath = "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
440     }
441     else if (dumpType == "FaultLog")
442     {
443         entriesPath = "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/";
444     }
445     else if (dumpType == "System")
446     {
447         entriesPath = "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
448     }
449     else
450     {
451         BMCWEB_LOG_ERROR << "getDumpEntriesPath() invalid dump type: "
452                          << dumpType;
453     }
454 
455     // Returns empty string on error
456     return entriesPath;
457 }
458 
459 inline void
460     getDumpEntryCollection(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
461                            const std::string& dumpType)
462 {
463     std::string entriesPath = getDumpEntriesPath(dumpType);
464     if (entriesPath.empty())
465     {
466         messages::internalError(asyncResp->res);
467         return;
468     }
469 
470     crow::connections::systemBus->async_method_call(
471         [asyncResp, entriesPath,
472          dumpType](const boost::system::error_code& ec,
473                    dbus::utility::ManagedObjectType& resp) {
474         if (ec)
475         {
476             BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
477             messages::internalError(asyncResp->res);
478             return;
479         }
480 
481         // Remove ending slash
482         std::string odataIdStr = entriesPath;
483         if (!odataIdStr.empty())
484         {
485             odataIdStr.pop_back();
486         }
487 
488         asyncResp->res.jsonValue["@odata.type"] =
489             "#LogEntryCollection.LogEntryCollection";
490         asyncResp->res.jsonValue["@odata.id"] = std::move(odataIdStr);
491         asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entries";
492         asyncResp->res.jsonValue["Description"] =
493             "Collection of " + dumpType + " Dump Entries";
494 
495         nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
496         entriesArray = nlohmann::json::array();
497         std::string dumpEntryPath =
498             "/xyz/openbmc_project/dump/" +
499             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/";
500 
501         std::sort(resp.begin(), resp.end(), [](const auto& l, const auto& r) {
502             return AlphanumLess<std::string>()(l.first.filename(),
503                                                r.first.filename());
504         });
505 
506         for (auto& object : resp)
507         {
508             if (object.first.str.find(dumpEntryPath) == std::string::npos)
509             {
510                 continue;
511             }
512             uint64_t timestampUs = 0;
513             uint64_t size = 0;
514             std::string dumpStatus;
515             std::string originatorId;
516             log_entry::OriginatorTypes originatorType =
517                 log_entry::OriginatorTypes::Internal;
518             nlohmann::json::object_t thisEntry;
519 
520             std::string entryID = object.first.filename();
521             if (entryID.empty())
522             {
523                 continue;
524             }
525 
526             parseDumpEntryFromDbusObject(object, dumpStatus, size, timestampUs,
527                                          originatorId, originatorType,
528                                          asyncResp);
529 
530             if (dumpStatus !=
531                     "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
532                 !dumpStatus.empty())
533             {
534                 // Dump status is not Complete, no need to enumerate
535                 continue;
536             }
537 
538             thisEntry["@odata.type"] = "#LogEntry.v1_11_0.LogEntry";
539             thisEntry["@odata.id"] = entriesPath + entryID;
540             thisEntry["Id"] = entryID;
541             thisEntry["EntryType"] = "Event";
542             thisEntry["Name"] = dumpType + " Dump Entry";
543             thisEntry["Created"] =
544                 redfish::time_utils::getDateTimeUintUs(timestampUs);
545 
546             if (!originatorId.empty())
547             {
548                 thisEntry["Originator"] = originatorId;
549                 thisEntry["OriginatorType"] = originatorType;
550             }
551 
552             if (dumpType == "BMC")
553             {
554                 thisEntry["DiagnosticDataType"] = "Manager";
555                 thisEntry["AdditionalDataURI"] =
556                     entriesPath + entryID + "/attachment";
557                 thisEntry["AdditionalDataSizeBytes"] = size;
558             }
559             else if (dumpType == "System")
560             {
561                 thisEntry["DiagnosticDataType"] = "OEM";
562                 thisEntry["OEMDiagnosticDataType"] = "System";
563                 thisEntry["AdditionalDataURI"] =
564                     entriesPath + entryID + "/attachment";
565                 thisEntry["AdditionalDataSizeBytes"] = size;
566             }
567             entriesArray.push_back(std::move(thisEntry));
568         }
569         asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
570         },
571         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
572         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
573 }
574 
575 inline void
576     getDumpEntryById(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
577                      const std::string& entryID, const std::string& dumpType)
578 {
579     std::string entriesPath = getDumpEntriesPath(dumpType);
580     if (entriesPath.empty())
581     {
582         messages::internalError(asyncResp->res);
583         return;
584     }
585 
586     crow::connections::systemBus->async_method_call(
587         [asyncResp, entryID, dumpType,
588          entriesPath](const boost::system::error_code& ec,
589                       const dbus::utility::ManagedObjectType& resp) {
590         if (ec)
591         {
592             BMCWEB_LOG_ERROR << "DumpEntry resp_handler got error " << ec;
593             messages::internalError(asyncResp->res);
594             return;
595         }
596 
597         bool foundDumpEntry = false;
598         std::string dumpEntryPath =
599             "/xyz/openbmc_project/dump/" +
600             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/";
601 
602         for (const auto& objectPath : resp)
603         {
604             if (objectPath.first.str != dumpEntryPath + entryID)
605             {
606                 continue;
607             }
608 
609             foundDumpEntry = true;
610             uint64_t timestampUs = 0;
611             uint64_t size = 0;
612             std::string dumpStatus;
613             std::string originatorId;
614             log_entry::OriginatorTypes originatorType =
615                 log_entry::OriginatorTypes::Internal;
616 
617             parseDumpEntryFromDbusObject(objectPath, dumpStatus, size,
618                                          timestampUs, originatorId,
619                                          originatorType, asyncResp);
620 
621             if (dumpStatus !=
622                     "xyz.openbmc_project.Common.Progress.OperationStatus.Completed" &&
623                 !dumpStatus.empty())
624             {
625                 // Dump status is not Complete
626                 // return not found until status is changed to Completed
627                 messages::resourceNotFound(asyncResp->res, dumpType + " dump",
628                                            entryID);
629                 return;
630             }
631 
632             asyncResp->res.jsonValue["@odata.type"] =
633                 "#LogEntry.v1_11_0.LogEntry";
634             asyncResp->res.jsonValue["@odata.id"] = entriesPath + entryID;
635             asyncResp->res.jsonValue["Id"] = entryID;
636             asyncResp->res.jsonValue["EntryType"] = "Event";
637             asyncResp->res.jsonValue["Name"] = dumpType + " Dump Entry";
638             asyncResp->res.jsonValue["Created"] =
639                 redfish::time_utils::getDateTimeUintUs(timestampUs);
640 
641             if (!originatorId.empty())
642             {
643                 asyncResp->res.jsonValue["Originator"] = originatorId;
644                 asyncResp->res.jsonValue["OriginatorType"] = originatorType;
645             }
646 
647             if (dumpType == "BMC")
648             {
649                 asyncResp->res.jsonValue["DiagnosticDataType"] = "Manager";
650                 asyncResp->res.jsonValue["AdditionalDataURI"] =
651                     entriesPath + entryID + "/attachment";
652                 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size;
653             }
654             else if (dumpType == "System")
655             {
656                 asyncResp->res.jsonValue["DiagnosticDataType"] = "OEM";
657                 asyncResp->res.jsonValue["OEMDiagnosticDataType"] = "System";
658                 asyncResp->res.jsonValue["AdditionalDataURI"] =
659                     entriesPath + entryID + "/attachment";
660                 asyncResp->res.jsonValue["AdditionalDataSizeBytes"] = size;
661             }
662         }
663         if (!foundDumpEntry)
664         {
665             BMCWEB_LOG_ERROR << "Can't find Dump Entry";
666             messages::internalError(asyncResp->res);
667             return;
668         }
669         },
670         "xyz.openbmc_project.Dump.Manager", "/xyz/openbmc_project/dump",
671         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
672 }
673 
674 inline void deleteDumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
675                             const std::string& entryID,
676                             const std::string& dumpType)
677 {
678     auto respHandler =
679         [asyncResp, entryID](const boost::system::error_code& ec) {
680         BMCWEB_LOG_DEBUG << "Dump Entry doDelete callback: Done";
681         if (ec)
682         {
683             if (ec.value() == EBADR)
684             {
685                 messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
686                 return;
687             }
688             BMCWEB_LOG_ERROR << "Dump (DBus) doDelete respHandler got error "
689                              << ec << " entryID=" << entryID;
690             messages::internalError(asyncResp->res);
691             return;
692         }
693     };
694     crow::connections::systemBus->async_method_call(
695         respHandler, "xyz.openbmc_project.Dump.Manager",
696         "/xyz/openbmc_project/dump/" +
697             std::string(boost::algorithm::to_lower_copy(dumpType)) + "/entry/" +
698             entryID,
699         "xyz.openbmc_project.Object.Delete", "Delete");
700 }
701 
702 inline DumpCreationProgress
703     mapDbusStatusToDumpProgress(const std::string& status)
704 {
705     if (status ==
706             "xyz.openbmc_project.Common.Progress.OperationStatus.Failed" ||
707         status == "xyz.openbmc_project.Common.Progress.OperationStatus.Aborted")
708     {
709         return DumpCreationProgress::DUMP_CREATE_FAILED;
710     }
711     if (status ==
712         "xyz.openbmc_project.Common.Progress.OperationStatus.Completed")
713     {
714         return DumpCreationProgress::DUMP_CREATE_SUCCESS;
715     }
716     return DumpCreationProgress::DUMP_CREATE_INPROGRESS;
717 }
718 
719 inline DumpCreationProgress
720     getDumpCompletionStatus(const dbus::utility::DBusPropertiesMap& values)
721 {
722     for (const auto& [key, val] : values)
723     {
724         if (key == "Status")
725         {
726             const std::string* value = std::get_if<std::string>(&val);
727             if (value == nullptr)
728             {
729                 BMCWEB_LOG_ERROR << "Status property value is null";
730                 return DumpCreationProgress::DUMP_CREATE_FAILED;
731             }
732             return mapDbusStatusToDumpProgress(*value);
733         }
734     }
735     return DumpCreationProgress::DUMP_CREATE_INPROGRESS;
736 }
737 
738 inline std::string getDumpEntryPath(const std::string& dumpPath)
739 {
740     if (dumpPath == "/xyz/openbmc_project/dump/bmc/entry")
741     {
742         return "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/";
743     }
744     if (dumpPath == "/xyz/openbmc_project/dump/system/entry")
745     {
746         return "/redfish/v1/Systems/system/LogServices/Dump/Entries/";
747     }
748     return "";
749 }
750 
751 inline void createDumpTaskCallback(
752     task::Payload&& payload,
753     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
754     const sdbusplus::message::object_path& createdObjPath)
755 {
756     const std::string dumpPath = createdObjPath.parent_path().str;
757     const std::string dumpId = createdObjPath.filename();
758 
759     std::string dumpEntryPath = getDumpEntryPath(dumpPath);
760 
761     if (dumpEntryPath.empty())
762     {
763         BMCWEB_LOG_ERROR << "Invalid dump type received";
764         messages::internalError(asyncResp->res);
765         return;
766     }
767 
768     crow::connections::systemBus->async_method_call(
769         [asyncResp, payload, createdObjPath,
770          dumpEntryPath{std::move(dumpEntryPath)},
771          dumpId](const boost::system::error_code& ec,
772                  const std::string& introspectXml) {
773         if (ec)
774         {
775             BMCWEB_LOG_ERROR << "Introspect call failed with error: "
776                              << ec.message();
777             messages::internalError(asyncResp->res);
778             return;
779         }
780 
781         // Check if the created dump object has implemented Progress
782         // interface to track dump completion. If yes, fetch the "Status"
783         // property of the interface, modify the task state accordingly.
784         // Else, return task completed.
785         tinyxml2::XMLDocument doc;
786 
787         doc.Parse(introspectXml.data(), introspectXml.size());
788         tinyxml2::XMLNode* pRoot = doc.FirstChildElement("node");
789         if (pRoot == nullptr)
790         {
791             BMCWEB_LOG_ERROR << "XML document failed to parse";
792             messages::internalError(asyncResp->res);
793             return;
794         }
795         tinyxml2::XMLElement* interfaceNode =
796             pRoot->FirstChildElement("interface");
797 
798         bool isProgressIntfPresent = false;
799         while (interfaceNode != nullptr)
800         {
801             const char* thisInterfaceName = interfaceNode->Attribute("name");
802             if (thisInterfaceName != nullptr)
803             {
804                 if (thisInterfaceName ==
805                     std::string_view("xyz.openbmc_project.Common.Progress"))
806                 {
807                     interfaceNode =
808                         interfaceNode->NextSiblingElement("interface");
809                     continue;
810                 }
811                 isProgressIntfPresent = true;
812                 break;
813             }
814             interfaceNode = interfaceNode->NextSiblingElement("interface");
815         }
816 
817         std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
818             [createdObjPath, dumpEntryPath, dumpId, isProgressIntfPresent](
819                 const boost::system::error_code& err, sdbusplus::message_t& msg,
820                 const std::shared_ptr<task::TaskData>& taskData) {
821             if (err)
822             {
823                 BMCWEB_LOG_ERROR << createdObjPath.str
824                                  << ": Error in creating dump";
825                 taskData->messages.emplace_back(messages::internalError());
826                 taskData->state = "Cancelled";
827                 return task::completed;
828             }
829 
830             if (isProgressIntfPresent)
831             {
832                 dbus::utility::DBusPropertiesMap values;
833                 std::string prop;
834                 msg.read(prop, values);
835 
836                 DumpCreationProgress dumpStatus =
837                     getDumpCompletionStatus(values);
838                 if (dumpStatus == DumpCreationProgress::DUMP_CREATE_FAILED)
839                 {
840                     BMCWEB_LOG_ERROR << createdObjPath.str
841                                      << ": Error in creating dump";
842                     taskData->state = "Cancelled";
843                     return task::completed;
844                 }
845 
846                 if (dumpStatus == DumpCreationProgress::DUMP_CREATE_INPROGRESS)
847                 {
848                     BMCWEB_LOG_DEBUG << createdObjPath.str
849                                      << ": Dump creation task is in progress";
850                     return !task::completed;
851                 }
852             }
853 
854             nlohmann::json retMessage = messages::success();
855             taskData->messages.emplace_back(retMessage);
856 
857             std::string headerLoc =
858                 "Location: " + dumpEntryPath + http_helpers::urlEncode(dumpId);
859             taskData->payload->httpHeaders.emplace_back(std::move(headerLoc));
860 
861             BMCWEB_LOG_DEBUG << createdObjPath.str
862                              << ": Dump creation task completed";
863             taskData->state = "Completed";
864             return task::completed;
865             },
866             "type='signal',interface='org.freedesktop.DBus.Properties',"
867             "member='PropertiesChanged',path='" +
868                 createdObjPath.str + "'");
869 
870         // The task timer is set to max time limit within which the
871         // requested dump will be collected.
872         task->startTimer(std::chrono::minutes(6));
873         task->populateResp(asyncResp->res);
874         task->payload.emplace(payload);
875         },
876         "xyz.openbmc_project.Dump.Manager", createdObjPath,
877         "org.freedesktop.DBus.Introspectable", "Introspect");
878 }
879 
880 inline void createDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
881                        const crow::Request& req, const std::string& dumpType)
882 {
883     std::string dumpPath = getDumpEntriesPath(dumpType);
884     if (dumpPath.empty())
885     {
886         messages::internalError(asyncResp->res);
887         return;
888     }
889 
890     std::optional<std::string> diagnosticDataType;
891     std::optional<std::string> oemDiagnosticDataType;
892 
893     if (!redfish::json_util::readJsonAction(
894             req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
895             "OEMDiagnosticDataType", oemDiagnosticDataType))
896     {
897         return;
898     }
899 
900     if (dumpType == "System")
901     {
902         if (!oemDiagnosticDataType || !diagnosticDataType)
903         {
904             BMCWEB_LOG_ERROR
905                 << "CreateDump action parameter 'DiagnosticDataType'/'OEMDiagnosticDataType' value not found!";
906             messages::actionParameterMissing(
907                 asyncResp->res, "CollectDiagnosticData",
908                 "DiagnosticDataType & OEMDiagnosticDataType");
909             return;
910         }
911         if ((*oemDiagnosticDataType != "System") ||
912             (*diagnosticDataType != "OEM"))
913         {
914             BMCWEB_LOG_ERROR << "Wrong parameter values passed";
915             messages::internalError(asyncResp->res);
916             return;
917         }
918         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/";
919     }
920     else if (dumpType == "BMC")
921     {
922         if (!diagnosticDataType)
923         {
924             BMCWEB_LOG_ERROR
925                 << "CreateDump action parameter 'DiagnosticDataType' not found!";
926             messages::actionParameterMissing(
927                 asyncResp->res, "CollectDiagnosticData", "DiagnosticDataType");
928             return;
929         }
930         if (*diagnosticDataType != "Manager")
931         {
932             BMCWEB_LOG_ERROR
933                 << "Wrong parameter value passed for 'DiagnosticDataType'";
934             messages::internalError(asyncResp->res);
935             return;
936         }
937         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/";
938     }
939     else
940     {
941         BMCWEB_LOG_ERROR << "CreateDump failed. Unknown dump type";
942         messages::internalError(asyncResp->res);
943         return;
944     }
945 
946     std::vector<std::pair<std::string, std::variant<std::string, uint64_t>>>
947         createDumpParamVec;
948 
949     createDumpParamVec.emplace_back(
950         "xyz.openbmc_project.Dump.Create.CreateParameters.OriginatorId",
951         req.session->clientIp);
952     createDumpParamVec.emplace_back(
953         "xyz.openbmc_project.Dump.Create.CreateParameters.OriginatorType",
954         "xyz.openbmc_project.Common.OriginatedBy.OriginatorTypes.Client");
955 
956     crow::connections::systemBus->async_method_call(
957         [asyncResp, payload(task::Payload(req)),
958          dumpPath](const boost::system::error_code& ec,
959                    const sdbusplus::message_t& msg,
960                    const sdbusplus::message::object_path& objPath) mutable {
961         if (ec)
962         {
963             BMCWEB_LOG_ERROR << "CreateDump resp_handler got error " << ec;
964             const sd_bus_error* dbusError = msg.get_error();
965             if (dbusError == nullptr)
966             {
967                 messages::internalError(asyncResp->res);
968                 return;
969             }
970 
971             BMCWEB_LOG_ERROR << "CreateDump DBus error: " << dbusError->name
972                              << " and error msg: " << dbusError->message;
973             if (std::string_view(
974                     "xyz.openbmc_project.Common.Error.NotAllowed") ==
975                 dbusError->name)
976             {
977                 messages::resourceInStandby(asyncResp->res);
978                 return;
979             }
980             if (std::string_view(
981                     "xyz.openbmc_project.Dump.Create.Error.Disabled") ==
982                 dbusError->name)
983             {
984                 messages::serviceDisabled(asyncResp->res, dumpPath);
985                 return;
986             }
987             if (std::string_view(
988                     "xyz.openbmc_project.Common.Error.Unavailable") ==
989                 dbusError->name)
990             {
991                 messages::resourceInUse(asyncResp->res);
992                 return;
993             }
994             // Other Dbus errors such as:
995             // xyz.openbmc_project.Common.Error.InvalidArgument &
996             // org.freedesktop.DBus.Error.InvalidArgs are all related to
997             // the dbus call that is made here in the bmcweb
998             // implementation and has nothing to do with the client's
999             // input in the request. Hence, returning internal error
1000             // back to the client.
1001             messages::internalError(asyncResp->res);
1002             return;
1003         }
1004         BMCWEB_LOG_DEBUG << "Dump Created. Path: " << objPath.str;
1005         createDumpTaskCallback(std::move(payload), asyncResp, objPath);
1006         },
1007         "xyz.openbmc_project.Dump.Manager",
1008         "/xyz/openbmc_project/dump/" +
1009             std::string(boost::algorithm::to_lower_copy(dumpType)),
1010         "xyz.openbmc_project.Dump.Create", "CreateDump", createDumpParamVec);
1011 }
1012 
1013 inline void clearDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1014                       const std::string& dumpType)
1015 {
1016     std::string dumpTypeLowerCopy =
1017         std::string(boost::algorithm::to_lower_copy(dumpType));
1018 
1019     crow::connections::systemBus->async_method_call(
1020         [asyncResp](const boost::system::error_code& ec) {
1021         if (ec)
1022         {
1023             BMCWEB_LOG_ERROR << "clearDump resp_handler got error " << ec;
1024             messages::internalError(asyncResp->res);
1025             return;
1026         }
1027         },
1028         "xyz.openbmc_project.Dump.Manager",
1029         "/xyz/openbmc_project/dump/" + dumpTypeLowerCopy,
1030         "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
1031 }
1032 
1033 inline static void
1034     parseCrashdumpParameters(const dbus::utility::DBusPropertiesMap& params,
1035                              std::string& filename, std::string& timestamp,
1036                              std::string& logfile)
1037 {
1038     const std::string* filenamePtr = nullptr;
1039     const std::string* timestampPtr = nullptr;
1040     const std::string* logfilePtr = nullptr;
1041 
1042     const bool success = sdbusplus::unpackPropertiesNoThrow(
1043         dbus_utils::UnpackErrorPrinter(), params, "Timestamp", timestampPtr,
1044         "Filename", filenamePtr, "Log", logfilePtr);
1045 
1046     if (!success)
1047     {
1048         return;
1049     }
1050 
1051     if (filenamePtr != nullptr)
1052     {
1053         filename = *filenamePtr;
1054     }
1055 
1056     if (timestampPtr != nullptr)
1057     {
1058         timestamp = *timestampPtr;
1059     }
1060 
1061     if (logfilePtr != nullptr)
1062     {
1063         logfile = *logfilePtr;
1064     }
1065 }
1066 
1067 inline void requestRoutesSystemLogServiceCollection(App& app)
1068 {
1069     /**
1070      * Functions triggers appropriate requests on DBus
1071      */
1072     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/")
1073         .privileges(redfish::privileges::getLogServiceCollection)
1074         .methods(boost::beast::http::verb::get)(
1075             [&app](const crow::Request& req,
1076                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1077                    const std::string& systemName) {
1078         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1079         {
1080             return;
1081         }
1082         if (systemName != "system")
1083         {
1084             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1085                                        systemName);
1086             return;
1087         }
1088 
1089         // Collections don't include the static data added by SubRoute
1090         // because it has a duplicate entry for members
1091         asyncResp->res.jsonValue["@odata.type"] =
1092             "#LogServiceCollection.LogServiceCollection";
1093         asyncResp->res.jsonValue["@odata.id"] =
1094             "/redfish/v1/Systems/system/LogServices";
1095         asyncResp->res.jsonValue["Name"] = "System Log Services Collection";
1096         asyncResp->res.jsonValue["Description"] =
1097             "Collection of LogServices for this Computer System";
1098         nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
1099         logServiceArray = nlohmann::json::array();
1100         nlohmann::json::object_t eventLog;
1101         eventLog["@odata.id"] =
1102             "/redfish/v1/Systems/system/LogServices/EventLog";
1103         logServiceArray.push_back(std::move(eventLog));
1104 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
1105         nlohmann::json::object_t dumpLog;
1106         dumpLog["@odata.id"] = "/redfish/v1/Systems/system/LogServices/Dump";
1107         logServiceArray.push_back(std::move(dumpLog));
1108 #endif
1109 
1110 #ifdef BMCWEB_ENABLE_REDFISH_CPU_LOG
1111         nlohmann::json::object_t crashdump;
1112         crashdump["@odata.id"] =
1113             "/redfish/v1/Systems/system/LogServices/Crashdump";
1114         logServiceArray.push_back(std::move(crashdump));
1115 #endif
1116 
1117 #ifdef BMCWEB_ENABLE_REDFISH_HOST_LOGGER
1118         nlohmann::json::object_t hostlogger;
1119         hostlogger["@odata.id"] =
1120             "/redfish/v1/Systems/system/LogServices/HostLogger";
1121         logServiceArray.push_back(std::move(hostlogger));
1122 #endif
1123         asyncResp->res.jsonValue["Members@odata.count"] =
1124             logServiceArray.size();
1125 
1126         constexpr std::array<std::string_view, 1> interfaces = {
1127             "xyz.openbmc_project.State.Boot.PostCode"};
1128         dbus::utility::getSubTreePaths(
1129             "/", 0, interfaces,
1130             [asyncResp](const boost::system::error_code& ec,
1131                         const dbus::utility::MapperGetSubTreePathsResponse&
1132                             subtreePath) {
1133             if (ec)
1134             {
1135                 BMCWEB_LOG_ERROR << ec;
1136                 return;
1137             }
1138 
1139             for (const auto& pathStr : subtreePath)
1140             {
1141                 if (pathStr.find("PostCode") != std::string::npos)
1142                 {
1143                     nlohmann::json& logServiceArrayLocal =
1144                         asyncResp->res.jsonValue["Members"];
1145                     nlohmann::json::object_t member;
1146                     member["@odata.id"] =
1147                         "/redfish/v1/Systems/system/LogServices/PostCodes";
1148 
1149                     logServiceArrayLocal.push_back(std::move(member));
1150 
1151                     asyncResp->res.jsonValue["Members@odata.count"] =
1152                         logServiceArrayLocal.size();
1153                     return;
1154                 }
1155             }
1156             });
1157         });
1158 }
1159 
1160 inline void requestRoutesEventLogService(App& app)
1161 {
1162     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/")
1163         .privileges(redfish::privileges::getLogService)
1164         .methods(boost::beast::http::verb::get)(
1165             [&app](const crow::Request& req,
1166                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1167                    const std::string& systemName) {
1168         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1169         {
1170             return;
1171         }
1172         if (systemName != "system")
1173         {
1174             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1175                                        systemName);
1176             return;
1177         }
1178         asyncResp->res.jsonValue["@odata.id"] =
1179             "/redfish/v1/Systems/system/LogServices/EventLog";
1180         asyncResp->res.jsonValue["@odata.type"] =
1181             "#LogService.v1_1_0.LogService";
1182         asyncResp->res.jsonValue["Name"] = "Event Log Service";
1183         asyncResp->res.jsonValue["Description"] = "System Event Log Service";
1184         asyncResp->res.jsonValue["Id"] = "EventLog";
1185         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
1186 
1187         std::pair<std::string, std::string> redfishDateTimeOffset =
1188             redfish::time_utils::getDateTimeOffsetNow();
1189 
1190         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
1191         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
1192             redfishDateTimeOffset.second;
1193 
1194         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
1195             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1196         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
1197 
1198             {"target",
1199              "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog"}};
1200         });
1201 }
1202 
1203 inline void requestRoutesJournalEventLogClear(App& app)
1204 {
1205     BMCWEB_ROUTE(
1206         app,
1207         "/redfish/v1/Systems/<str>/LogServices/EventLog/Actions/LogService.ClearLog/")
1208         .privileges({{"ConfigureComponents"}})
1209         .methods(boost::beast::http::verb::post)(
1210             [&app](const crow::Request& req,
1211                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1212                    const std::string& systemName) {
1213         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1214         {
1215             return;
1216         }
1217         if (systemName != "system")
1218         {
1219             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1220                                        systemName);
1221             return;
1222         }
1223         // Clear the EventLog by deleting the log files
1224         std::vector<std::filesystem::path> redfishLogFiles;
1225         if (getRedfishLogFiles(redfishLogFiles))
1226         {
1227             for (const std::filesystem::path& file : redfishLogFiles)
1228             {
1229                 std::error_code ec;
1230                 std::filesystem::remove(file, ec);
1231             }
1232         }
1233 
1234         // Reload rsyslog so it knows to start new log files
1235         crow::connections::systemBus->async_method_call(
1236             [asyncResp](const boost::system::error_code& ec) {
1237             if (ec)
1238             {
1239                 BMCWEB_LOG_ERROR << "Failed to reload rsyslog: " << ec;
1240                 messages::internalError(asyncResp->res);
1241                 return;
1242             }
1243 
1244             messages::success(asyncResp->res);
1245             },
1246             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
1247             "org.freedesktop.systemd1.Manager", "ReloadUnit", "rsyslog.service",
1248             "replace");
1249         });
1250 }
1251 
1252 enum class LogParseError
1253 {
1254     success,
1255     parseFailed,
1256     messageIdNotInRegistry,
1257 };
1258 
1259 static LogParseError
1260     fillEventLogEntryJson(const std::string& logEntryID,
1261                           const std::string& logEntry,
1262                           nlohmann::json::object_t& logEntryJson)
1263 {
1264     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1265     // First get the Timestamp
1266     size_t space = logEntry.find_first_of(' ');
1267     if (space == std::string::npos)
1268     {
1269         return LogParseError::parseFailed;
1270     }
1271     std::string timestamp = logEntry.substr(0, space);
1272     // Then get the log contents
1273     size_t entryStart = logEntry.find_first_not_of(' ', space);
1274     if (entryStart == std::string::npos)
1275     {
1276         return LogParseError::parseFailed;
1277     }
1278     std::string_view entry(logEntry);
1279     entry.remove_prefix(entryStart);
1280     // Use split to separate the entry into its fields
1281     std::vector<std::string> logEntryFields;
1282     bmcweb::split(logEntryFields, entry, ',');
1283     // We need at least a MessageId to be valid
1284     if (logEntryFields.empty())
1285     {
1286         return LogParseError::parseFailed;
1287     }
1288     std::string& messageID = logEntryFields[0];
1289 
1290     // Get the Message from the MessageRegistry
1291     const registries::Message* message = registries::getMessage(messageID);
1292 
1293     if (message == nullptr)
1294     {
1295         BMCWEB_LOG_WARNING << "Log entry not found in registry: " << logEntry;
1296         return LogParseError::messageIdNotInRegistry;
1297     }
1298 
1299     std::string msg = message->message;
1300 
1301     // Get the MessageArgs from the log if there are any
1302     std::span<std::string> messageArgs;
1303     if (logEntryFields.size() > 1)
1304     {
1305         std::string& messageArgsStart = logEntryFields[1];
1306         // If the first string is empty, assume there are no MessageArgs
1307         std::size_t messageArgsSize = 0;
1308         if (!messageArgsStart.empty())
1309         {
1310             messageArgsSize = logEntryFields.size() - 1;
1311         }
1312 
1313         messageArgs = {&messageArgsStart, messageArgsSize};
1314 
1315         // Fill the MessageArgs into the Message
1316         int i = 0;
1317         for (const std::string& messageArg : messageArgs)
1318         {
1319             std::string argStr = "%" + std::to_string(++i);
1320             size_t argPos = msg.find(argStr);
1321             if (argPos != std::string::npos)
1322             {
1323                 msg.replace(argPos, argStr.length(), messageArg);
1324             }
1325         }
1326     }
1327 
1328     // Get the Created time from the timestamp. The log timestamp is in RFC3339
1329     // format which matches the Redfish format except for the fractional seconds
1330     // between the '.' and the '+', so just remove them.
1331     std::size_t dot = timestamp.find_first_of('.');
1332     std::size_t plus = timestamp.find_first_of('+');
1333     if (dot != std::string::npos && plus != std::string::npos)
1334     {
1335         timestamp.erase(dot, plus - dot);
1336     }
1337 
1338     // Fill in the log entry with the gathered data
1339     logEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
1340     logEntryJson["@odata.id"] = crow::utility::urlFromPieces(
1341         "redfish", "v1", "Systems", "system", "LogServices", "EventLog",
1342         "Entries", logEntryID);
1343     logEntryJson["Name"] = "System Event Log Entry";
1344     logEntryJson["Id"] = logEntryID;
1345     logEntryJson["Message"] = std::move(msg);
1346     logEntryJson["MessageId"] = std::move(messageID);
1347     logEntryJson["MessageArgs"] = messageArgs;
1348     logEntryJson["EntryType"] = "Event";
1349     logEntryJson["Severity"] = message->messageSeverity;
1350     logEntryJson["Created"] = std::move(timestamp);
1351     return LogParseError::success;
1352 }
1353 
1354 inline void requestRoutesJournalEventLogEntryCollection(App& app)
1355 {
1356     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/")
1357         .privileges(redfish::privileges::getLogEntryCollection)
1358         .methods(boost::beast::http::verb::get)(
1359             [&app](const crow::Request& req,
1360                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1361                    const std::string& systemName) {
1362         query_param::QueryCapabilities capabilities = {
1363             .canDelegateTop = true,
1364             .canDelegateSkip = true,
1365         };
1366         query_param::Query delegatedQuery;
1367         if (!redfish::setUpRedfishRouteWithDelegation(
1368                 app, req, asyncResp, delegatedQuery, capabilities))
1369         {
1370             return;
1371         }
1372         if (systemName != "system")
1373         {
1374             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1375                                        systemName);
1376             return;
1377         }
1378 
1379         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
1380         size_t skip = delegatedQuery.skip.value_or(0);
1381 
1382         // Collections don't include the static data added by SubRoute
1383         // because it has a duplicate entry for members
1384         asyncResp->res.jsonValue["@odata.type"] =
1385             "#LogEntryCollection.LogEntryCollection";
1386         asyncResp->res.jsonValue["@odata.id"] =
1387             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1388         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1389         asyncResp->res.jsonValue["Description"] =
1390             "Collection of System Event Log Entries";
1391 
1392         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
1393         logEntryArray = nlohmann::json::array();
1394         // Go through the log files and create a unique ID for each
1395         // entry
1396         std::vector<std::filesystem::path> redfishLogFiles;
1397         getRedfishLogFiles(redfishLogFiles);
1398         uint64_t entryCount = 0;
1399         std::string logEntry;
1400 
1401         // Oldest logs are in the last file, so start there and loop
1402         // backwards
1403         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1404              it++)
1405         {
1406             std::ifstream logStream(*it);
1407             if (!logStream.is_open())
1408             {
1409                 continue;
1410             }
1411 
1412             // Reset the unique ID on the first entry
1413             bool firstEntry = true;
1414             while (std::getline(logStream, logEntry))
1415             {
1416                 std::string idStr;
1417                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1418                 {
1419                     continue;
1420                 }
1421                 firstEntry = false;
1422 
1423                 nlohmann::json::object_t bmcLogEntry;
1424                 LogParseError status =
1425                     fillEventLogEntryJson(idStr, logEntry, bmcLogEntry);
1426                 if (status == LogParseError::messageIdNotInRegistry)
1427                 {
1428                     continue;
1429                 }
1430                 if (status != LogParseError::success)
1431                 {
1432                     messages::internalError(asyncResp->res);
1433                     return;
1434                 }
1435 
1436                 entryCount++;
1437                 // Handle paging using skip (number of entries to skip from the
1438                 // start) and top (number of entries to display)
1439                 if (entryCount <= skip || entryCount > skip + top)
1440                 {
1441                     continue;
1442                 }
1443 
1444                 logEntryArray.push_back(std::move(bmcLogEntry));
1445             }
1446         }
1447         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
1448         if (skip + top < entryCount)
1449         {
1450             asyncResp->res.jsonValue["Members@odata.nextLink"] =
1451                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries?$skip=" +
1452                 std::to_string(skip + top);
1453         }
1454         });
1455 }
1456 
1457 inline void requestRoutesJournalEventLogEntry(App& app)
1458 {
1459     BMCWEB_ROUTE(
1460         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1461         .privileges(redfish::privileges::getLogEntry)
1462         .methods(boost::beast::http::verb::get)(
1463             [&app](const crow::Request& req,
1464                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1465                    const std::string& systemName, const std::string& param) {
1466         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1467         {
1468             return;
1469         }
1470 
1471         if (systemName != "system")
1472         {
1473             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1474                                        systemName);
1475             return;
1476         }
1477 
1478         const std::string& targetID = param;
1479 
1480         // Go through the log files and check the unique ID for each
1481         // entry to find the target entry
1482         std::vector<std::filesystem::path> redfishLogFiles;
1483         getRedfishLogFiles(redfishLogFiles);
1484         std::string logEntry;
1485 
1486         // Oldest logs are in the last file, so start there and loop
1487         // backwards
1488         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1489              it++)
1490         {
1491             std::ifstream logStream(*it);
1492             if (!logStream.is_open())
1493             {
1494                 continue;
1495             }
1496 
1497             // Reset the unique ID on the first entry
1498             bool firstEntry = true;
1499             while (std::getline(logStream, logEntry))
1500             {
1501                 std::string idStr;
1502                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1503                 {
1504                     continue;
1505                 }
1506                 firstEntry = false;
1507 
1508                 if (idStr == targetID)
1509                 {
1510                     nlohmann::json::object_t bmcLogEntry;
1511                     LogParseError status =
1512                         fillEventLogEntryJson(idStr, logEntry, bmcLogEntry);
1513                     if (status != LogParseError::success)
1514                     {
1515                         messages::internalError(asyncResp->res);
1516                         return;
1517                     }
1518                     asyncResp->res.jsonValue.update(bmcLogEntry);
1519                     return;
1520                 }
1521             }
1522         }
1523         // Requested ID was not found
1524         messages::resourceNotFound(asyncResp->res, "LogEntry", targetID);
1525         });
1526 }
1527 
1528 inline void requestRoutesDBusEventLogEntryCollection(App& app)
1529 {
1530     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/")
1531         .privileges(redfish::privileges::getLogEntryCollection)
1532         .methods(boost::beast::http::verb::get)(
1533             [&app](const crow::Request& req,
1534                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1535                    const std::string& systemName) {
1536         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1537         {
1538             return;
1539         }
1540         if (systemName != "system")
1541         {
1542             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1543                                        systemName);
1544             return;
1545         }
1546 
1547         // Collections don't include the static data added by SubRoute
1548         // because it has a duplicate entry for members
1549         asyncResp->res.jsonValue["@odata.type"] =
1550             "#LogEntryCollection.LogEntryCollection";
1551         asyncResp->res.jsonValue["@odata.id"] =
1552             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1553         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1554         asyncResp->res.jsonValue["Description"] =
1555             "Collection of System Event Log Entries";
1556 
1557         // DBus implementation of EventLog/Entries
1558         // Make call to Logging Service to find all log entry objects
1559         crow::connections::systemBus->async_method_call(
1560             [asyncResp](const boost::system::error_code& ec,
1561                         const dbus::utility::ManagedObjectType& resp) {
1562             if (ec)
1563             {
1564                 // TODO Handle for specific error code
1565                 BMCWEB_LOG_ERROR
1566                     << "getLogEntriesIfaceData resp_handler got error " << ec;
1567                 messages::internalError(asyncResp->res);
1568                 return;
1569             }
1570             nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
1571             entriesArray = nlohmann::json::array();
1572             for (const auto& objectPath : resp)
1573             {
1574                 const uint32_t* id = nullptr;
1575                 const uint64_t* timestamp = nullptr;
1576                 const uint64_t* updateTimestamp = nullptr;
1577                 const std::string* severity = nullptr;
1578                 const std::string* message = nullptr;
1579                 const std::string* filePath = nullptr;
1580                 const std::string* resolution = nullptr;
1581                 bool resolved = false;
1582                 const std::string* notify = nullptr;
1583 
1584                 for (const auto& interfaceMap : objectPath.second)
1585                 {
1586                     if (interfaceMap.first ==
1587                         "xyz.openbmc_project.Logging.Entry")
1588                     {
1589                         for (const auto& propertyMap : interfaceMap.second)
1590                         {
1591                             if (propertyMap.first == "Id")
1592                             {
1593                                 id = std::get_if<uint32_t>(&propertyMap.second);
1594                             }
1595                             else if (propertyMap.first == "Timestamp")
1596                             {
1597                                 timestamp =
1598                                     std::get_if<uint64_t>(&propertyMap.second);
1599                             }
1600                             else if (propertyMap.first == "UpdateTimestamp")
1601                             {
1602                                 updateTimestamp =
1603                                     std::get_if<uint64_t>(&propertyMap.second);
1604                             }
1605                             else if (propertyMap.first == "Severity")
1606                             {
1607                                 severity = std::get_if<std::string>(
1608                                     &propertyMap.second);
1609                             }
1610                             else if (propertyMap.first == "Resolution")
1611                             {
1612                                 resolution = std::get_if<std::string>(
1613                                     &propertyMap.second);
1614                             }
1615                             else if (propertyMap.first == "Message")
1616                             {
1617                                 message = std::get_if<std::string>(
1618                                     &propertyMap.second);
1619                             }
1620                             else if (propertyMap.first == "Resolved")
1621                             {
1622                                 const bool* resolveptr =
1623                                     std::get_if<bool>(&propertyMap.second);
1624                                 if (resolveptr == nullptr)
1625                                 {
1626                                     messages::internalError(asyncResp->res);
1627                                     return;
1628                                 }
1629                                 resolved = *resolveptr;
1630                             }
1631                             else if (propertyMap.first ==
1632                                      "ServiceProviderNotify")
1633                             {
1634                                 notify = std::get_if<std::string>(
1635                                     &propertyMap.second);
1636                                 if (notify == nullptr)
1637                                 {
1638                                     messages::internalError(asyncResp->res);
1639                                     return;
1640                                 }
1641                             }
1642                         }
1643                         if (id == nullptr || message == nullptr ||
1644                             severity == nullptr)
1645                         {
1646                             messages::internalError(asyncResp->res);
1647                             return;
1648                         }
1649                     }
1650                     else if (interfaceMap.first ==
1651                              "xyz.openbmc_project.Common.FilePath")
1652                     {
1653                         for (const auto& propertyMap : interfaceMap.second)
1654                         {
1655                             if (propertyMap.first == "Path")
1656                             {
1657                                 filePath = std::get_if<std::string>(
1658                                     &propertyMap.second);
1659                             }
1660                         }
1661                     }
1662                 }
1663                 // Object path without the
1664                 // xyz.openbmc_project.Logging.Entry interface, ignore
1665                 // and continue.
1666                 if (id == nullptr || message == nullptr ||
1667                     severity == nullptr || timestamp == nullptr ||
1668                     updateTimestamp == nullptr)
1669                 {
1670                     continue;
1671                 }
1672                 entriesArray.push_back({});
1673                 nlohmann::json& thisEntry = entriesArray.back();
1674                 thisEntry["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
1675                 thisEntry["@odata.id"] = crow::utility::urlFromPieces(
1676                     "redfish", "v1", "Systems", "system", "LogServices",
1677                     "EventLog", "Entries", std::to_string(*id));
1678                 thisEntry["Name"] = "System Event Log Entry";
1679                 thisEntry["Id"] = std::to_string(*id);
1680                 thisEntry["Message"] = *message;
1681                 thisEntry["Resolved"] = resolved;
1682                 if ((resolution != nullptr) && (!(*resolution).empty()))
1683                 {
1684                     thisEntry["Resolution"] = *resolution;
1685                 }
1686                 std::optional<bool> notifyAction =
1687                     getProviderNotifyAction(*notify);
1688                 if (notifyAction)
1689                 {
1690                     thisEntry["ServiceProviderNotified"] = *notifyAction;
1691                 }
1692                 thisEntry["EntryType"] = "Event";
1693                 thisEntry["Severity"] =
1694                     translateSeverityDbusToRedfish(*severity);
1695                 thisEntry["Created"] =
1696                     redfish::time_utils::getDateTimeUintMs(*timestamp);
1697                 thisEntry["Modified"] =
1698                     redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1699                 if (filePath != nullptr)
1700                 {
1701                     thisEntry["AdditionalDataURI"] =
1702                         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1703                         std::to_string(*id) + "/attachment";
1704                 }
1705             }
1706             std::sort(
1707                 entriesArray.begin(), entriesArray.end(),
1708                 [](const nlohmann::json& left, const nlohmann::json& right) {
1709                 return (left["Id"] <= right["Id"]);
1710                 });
1711             asyncResp->res.jsonValue["Members@odata.count"] =
1712                 entriesArray.size();
1713             },
1714             "xyz.openbmc_project.Logging", "/xyz/openbmc_project/logging",
1715             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1716         });
1717 }
1718 
1719 inline void requestRoutesDBusEventLogEntry(App& app)
1720 {
1721     BMCWEB_ROUTE(
1722         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1723         .privileges(redfish::privileges::getLogEntry)
1724         .methods(boost::beast::http::verb::get)(
1725             [&app](const crow::Request& req,
1726                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1727                    const std::string& systemName, const std::string& param) {
1728         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1729         {
1730             return;
1731         }
1732         if (systemName != "system")
1733         {
1734             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1735                                        systemName);
1736             return;
1737         }
1738 
1739         std::string entryID = param;
1740         dbus::utility::escapePathForDbus(entryID);
1741 
1742         // DBus implementation of EventLog/Entries
1743         // Make call to Logging Service to find all log entry objects
1744         sdbusplus::asio::getAllProperties(
1745             *crow::connections::systemBus, "xyz.openbmc_project.Logging",
1746             "/xyz/openbmc_project/logging/entry/" + entryID, "",
1747             [asyncResp, entryID](const boost::system::error_code& ec,
1748                                  const dbus::utility::DBusPropertiesMap& resp) {
1749             if (ec.value() == EBADR)
1750             {
1751                 messages::resourceNotFound(asyncResp->res, "EventLogEntry",
1752                                            entryID);
1753                 return;
1754             }
1755             if (ec)
1756             {
1757                 BMCWEB_LOG_ERROR
1758                     << "EventLogEntry (DBus) resp_handler got error " << ec;
1759                 messages::internalError(asyncResp->res);
1760                 return;
1761             }
1762             const uint32_t* id = nullptr;
1763             const uint64_t* timestamp = nullptr;
1764             const uint64_t* updateTimestamp = nullptr;
1765             const std::string* severity = nullptr;
1766             const std::string* message = nullptr;
1767             const std::string* filePath = nullptr;
1768             const std::string* resolution = nullptr;
1769             bool resolved = false;
1770             const std::string* notify = nullptr;
1771 
1772             const bool success = sdbusplus::unpackPropertiesNoThrow(
1773                 dbus_utils::UnpackErrorPrinter(), resp, "Id", id, "Timestamp",
1774                 timestamp, "UpdateTimestamp", updateTimestamp, "Severity",
1775                 severity, "Message", message, "Resolved", resolved,
1776                 "Resolution", resolution, "Path", filePath,
1777                 "ServiceProviderNotify", notify);
1778 
1779             if (!success)
1780             {
1781                 messages::internalError(asyncResp->res);
1782                 return;
1783             }
1784 
1785             if (id == nullptr || message == nullptr || severity == nullptr ||
1786                 timestamp == nullptr || updateTimestamp == nullptr ||
1787                 notify == nullptr)
1788             {
1789                 messages::internalError(asyncResp->res);
1790                 return;
1791             }
1792 
1793             asyncResp->res.jsonValue["@odata.type"] =
1794                 "#LogEntry.v1_9_0.LogEntry";
1795             asyncResp->res.jsonValue["@odata.id"] =
1796                 crow::utility::urlFromPieces(
1797                     "redfish", "v1", "Systems", "system", "LogServices",
1798                     "EventLog", "Entries", std::to_string(*id));
1799             asyncResp->res.jsonValue["Name"] = "System Event Log Entry";
1800             asyncResp->res.jsonValue["Id"] = std::to_string(*id);
1801             asyncResp->res.jsonValue["Message"] = *message;
1802             asyncResp->res.jsonValue["Resolved"] = resolved;
1803             std::optional<bool> notifyAction = getProviderNotifyAction(*notify);
1804             if (notifyAction)
1805             {
1806                 asyncResp->res.jsonValue["ServiceProviderNotified"] =
1807                     *notifyAction;
1808             }
1809             if ((resolution != nullptr) && (!(*resolution).empty()))
1810             {
1811                 asyncResp->res.jsonValue["Resolution"] = *resolution;
1812             }
1813             asyncResp->res.jsonValue["EntryType"] = "Event";
1814             asyncResp->res.jsonValue["Severity"] =
1815                 translateSeverityDbusToRedfish(*severity);
1816             asyncResp->res.jsonValue["Created"] =
1817                 redfish::time_utils::getDateTimeUintMs(*timestamp);
1818             asyncResp->res.jsonValue["Modified"] =
1819                 redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1820             if (filePath != nullptr)
1821             {
1822                 asyncResp->res.jsonValue["AdditionalDataURI"] =
1823                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1824                     std::to_string(*id) + "/attachment";
1825             }
1826             });
1827         });
1828 
1829     BMCWEB_ROUTE(
1830         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1831         .privileges(redfish::privileges::patchLogEntry)
1832         .methods(boost::beast::http::verb::patch)(
1833             [&app](const crow::Request& req,
1834                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1835                    const std::string& systemName, const std::string& entryId) {
1836         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1837         {
1838             return;
1839         }
1840         if (systemName != "system")
1841         {
1842             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1843                                        systemName);
1844             return;
1845         }
1846         std::optional<bool> resolved;
1847 
1848         if (!json_util::readJsonPatch(req, asyncResp->res, "Resolved",
1849                                       resolved))
1850         {
1851             return;
1852         }
1853         BMCWEB_LOG_DEBUG << "Set Resolved";
1854 
1855         crow::connections::systemBus->async_method_call(
1856             [asyncResp, entryId](const boost::system::error_code& ec) {
1857             if (ec)
1858             {
1859                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1860                 messages::internalError(asyncResp->res);
1861                 return;
1862             }
1863             },
1864             "xyz.openbmc_project.Logging",
1865             "/xyz/openbmc_project/logging/entry/" + entryId,
1866             "org.freedesktop.DBus.Properties", "Set",
1867             "xyz.openbmc_project.Logging.Entry", "Resolved",
1868             dbus::utility::DbusVariantType(*resolved));
1869         });
1870 
1871     BMCWEB_ROUTE(
1872         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1873         .privileges(redfish::privileges::deleteLogEntry)
1874 
1875         .methods(boost::beast::http::verb::delete_)(
1876             [&app](const crow::Request& req,
1877                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1878                    const std::string& systemName, const std::string& param) {
1879         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1880         {
1881             return;
1882         }
1883         if (systemName != "system")
1884         {
1885             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1886                                        systemName);
1887             return;
1888         }
1889         BMCWEB_LOG_DEBUG << "Do delete single event entries.";
1890 
1891         std::string entryID = param;
1892 
1893         dbus::utility::escapePathForDbus(entryID);
1894 
1895         // Process response from Logging service.
1896         auto respHandler =
1897             [asyncResp, entryID](const boost::system::error_code& ec) {
1898             BMCWEB_LOG_DEBUG << "EventLogEntry (DBus) doDelete callback: Done";
1899             if (ec)
1900             {
1901                 if (ec.value() == EBADR)
1902                 {
1903                     messages::resourceNotFound(asyncResp->res, "LogEntry",
1904                                                entryID);
1905                     return;
1906                 }
1907                 // TODO Handle for specific error code
1908                 BMCWEB_LOG_ERROR
1909                     << "EventLogEntry (DBus) doDelete respHandler got error "
1910                     << ec;
1911                 asyncResp->res.result(
1912                     boost::beast::http::status::internal_server_error);
1913                 return;
1914             }
1915 
1916             asyncResp->res.result(boost::beast::http::status::ok);
1917         };
1918 
1919         // Make call to Logging service to request Delete Log
1920         crow::connections::systemBus->async_method_call(
1921             respHandler, "xyz.openbmc_project.Logging",
1922             "/xyz/openbmc_project/logging/entry/" + entryID,
1923             "xyz.openbmc_project.Object.Delete", "Delete");
1924         });
1925 }
1926 
1927 inline void requestRoutesDBusEventLogEntryDownload(App& app)
1928 {
1929     BMCWEB_ROUTE(
1930         app,
1931         "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/attachment")
1932         .privileges(redfish::privileges::getLogEntry)
1933         .methods(boost::beast::http::verb::get)(
1934             [&app](const crow::Request& req,
1935                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1936                    const std::string& systemName, const std::string& param) {
1937         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1938         {
1939             return;
1940         }
1941         if (http_helpers::isContentTypeAllowed(
1942                 req.getHeaderValue("Accept"),
1943                 http_helpers::ContentType::OctetStream, true))
1944         {
1945             asyncResp->res.result(boost::beast::http::status::bad_request);
1946             return;
1947         }
1948         if (systemName != "system")
1949         {
1950             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1951                                        systemName);
1952             return;
1953         }
1954 
1955         std::string entryID = param;
1956         dbus::utility::escapePathForDbus(entryID);
1957 
1958         crow::connections::systemBus->async_method_call(
1959             [asyncResp, entryID](const boost::system::error_code& ec,
1960                                  const sdbusplus::message::unix_fd& unixfd) {
1961             if (ec.value() == EBADR)
1962             {
1963                 messages::resourceNotFound(asyncResp->res, "EventLogAttachment",
1964                                            entryID);
1965                 return;
1966             }
1967             if (ec)
1968             {
1969                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1970                 messages::internalError(asyncResp->res);
1971                 return;
1972             }
1973 
1974             int fd = -1;
1975             fd = dup(unixfd);
1976             if (fd == -1)
1977             {
1978                 messages::internalError(asyncResp->res);
1979                 return;
1980             }
1981 
1982             long long int size = lseek(fd, 0, SEEK_END);
1983             if (size == -1)
1984             {
1985                 messages::internalError(asyncResp->res);
1986                 return;
1987             }
1988 
1989             // Arbitrary max size of 64kb
1990             constexpr int maxFileSize = 65536;
1991             if (size > maxFileSize)
1992             {
1993                 BMCWEB_LOG_ERROR << "File size exceeds maximum allowed size of "
1994                                  << maxFileSize;
1995                 messages::internalError(asyncResp->res);
1996                 return;
1997             }
1998             std::vector<char> data(static_cast<size_t>(size));
1999             long long int rc = lseek(fd, 0, SEEK_SET);
2000             if (rc == -1)
2001             {
2002                 messages::internalError(asyncResp->res);
2003                 return;
2004             }
2005             rc = read(fd, data.data(), data.size());
2006             if ((rc == -1) || (rc != size))
2007             {
2008                 messages::internalError(asyncResp->res);
2009                 return;
2010             }
2011             close(fd);
2012 
2013             std::string_view strData(data.data(), data.size());
2014             std::string output = crow::utility::base64encode(strData);
2015 
2016             asyncResp->res.addHeader(boost::beast::http::field::content_type,
2017                                      "application/octet-stream");
2018             asyncResp->res.addHeader(
2019                 boost::beast::http::field::content_transfer_encoding, "Base64");
2020             asyncResp->res.body() = std::move(output);
2021             },
2022             "xyz.openbmc_project.Logging",
2023             "/xyz/openbmc_project/logging/entry/" + entryID,
2024             "xyz.openbmc_project.Logging.Entry", "GetEntry");
2025         });
2026 }
2027 
2028 constexpr const char* hostLoggerFolderPath = "/var/log/console";
2029 
2030 inline bool
2031     getHostLoggerFiles(const std::string& hostLoggerFilePath,
2032                        std::vector<std::filesystem::path>& hostLoggerFiles)
2033 {
2034     std::error_code ec;
2035     std::filesystem::directory_iterator logPath(hostLoggerFilePath, ec);
2036     if (ec)
2037     {
2038         BMCWEB_LOG_ERROR << ec.message();
2039         return false;
2040     }
2041     for (const std::filesystem::directory_entry& it : logPath)
2042     {
2043         std::string filename = it.path().filename();
2044         // Prefix of each log files is "log". Find the file and save the
2045         // path
2046         if (filename.starts_with("log"))
2047         {
2048             hostLoggerFiles.emplace_back(it.path());
2049         }
2050     }
2051     // As the log files rotate, they are appended with a ".#" that is higher for
2052     // the older logs. Since we start from oldest logs, sort the name in
2053     // descending order.
2054     std::sort(hostLoggerFiles.rbegin(), hostLoggerFiles.rend(),
2055               AlphanumLess<std::string>());
2056 
2057     return true;
2058 }
2059 
2060 inline bool getHostLoggerEntries(
2061     const std::vector<std::filesystem::path>& hostLoggerFiles, uint64_t skip,
2062     uint64_t top, std::vector<std::string>& logEntries, size_t& logCount)
2063 {
2064     GzFileReader logFile;
2065 
2066     // Go though all log files and expose host logs.
2067     for (const std::filesystem::path& it : hostLoggerFiles)
2068     {
2069         if (!logFile.gzGetLines(it.string(), skip, top, logEntries, logCount))
2070         {
2071             BMCWEB_LOG_ERROR << "fail to expose host logs";
2072             return false;
2073         }
2074     }
2075     // Get lastMessage from constructor by getter
2076     std::string lastMessage = logFile.getLastMessage();
2077     if (!lastMessage.empty())
2078     {
2079         logCount++;
2080         if (logCount > skip && logCount <= (skip + top))
2081         {
2082             logEntries.push_back(lastMessage);
2083         }
2084     }
2085     return true;
2086 }
2087 
2088 inline void fillHostLoggerEntryJson(const std::string& logEntryID,
2089                                     const std::string& msg,
2090                                     nlohmann::json::object_t& logEntryJson)
2091 {
2092     // Fill in the log entry with the gathered data.
2093     logEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
2094     logEntryJson["@odata.id"] = crow::utility::urlFromPieces(
2095         "redfish", "v1", "Systems", "system", "LogServices", "HostLogger",
2096         "Entries", logEntryID);
2097     logEntryJson["Name"] = "Host Logger Entry";
2098     logEntryJson["Id"] = logEntryID;
2099     logEntryJson["Message"] = msg;
2100     logEntryJson["EntryType"] = "Oem";
2101     logEntryJson["Severity"] = "OK";
2102     logEntryJson["OemRecordFormat"] = "Host Logger Entry";
2103 }
2104 
2105 inline void requestRoutesSystemHostLogger(App& app)
2106 {
2107     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/HostLogger/")
2108         .privileges(redfish::privileges::getLogService)
2109         .methods(boost::beast::http::verb::get)(
2110             [&app](const crow::Request& req,
2111                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2112                    const std::string& systemName) {
2113         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2114         {
2115             return;
2116         }
2117         if (systemName != "system")
2118         {
2119             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2120                                        systemName);
2121             return;
2122         }
2123         asyncResp->res.jsonValue["@odata.id"] =
2124             "/redfish/v1/Systems/system/LogServices/HostLogger";
2125         asyncResp->res.jsonValue["@odata.type"] =
2126             "#LogService.v1_1_0.LogService";
2127         asyncResp->res.jsonValue["Name"] = "Host Logger Service";
2128         asyncResp->res.jsonValue["Description"] = "Host Logger Service";
2129         asyncResp->res.jsonValue["Id"] = "HostLogger";
2130         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2131             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
2132         });
2133 }
2134 
2135 inline void requestRoutesSystemHostLoggerCollection(App& app)
2136 {
2137     BMCWEB_ROUTE(app,
2138                  "/redfish/v1/Systems/<str>/LogServices/HostLogger/Entries/")
2139         .privileges(redfish::privileges::getLogEntry)
2140         .methods(boost::beast::http::verb::get)(
2141             [&app](const crow::Request& req,
2142                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2143                    const std::string& systemName) {
2144         query_param::QueryCapabilities capabilities = {
2145             .canDelegateTop = true,
2146             .canDelegateSkip = true,
2147         };
2148         query_param::Query delegatedQuery;
2149         if (!redfish::setUpRedfishRouteWithDelegation(
2150                 app, req, asyncResp, delegatedQuery, capabilities))
2151         {
2152             return;
2153         }
2154         if (systemName != "system")
2155         {
2156             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2157                                        systemName);
2158             return;
2159         }
2160         asyncResp->res.jsonValue["@odata.id"] =
2161             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
2162         asyncResp->res.jsonValue["@odata.type"] =
2163             "#LogEntryCollection.LogEntryCollection";
2164         asyncResp->res.jsonValue["Name"] = "HostLogger Entries";
2165         asyncResp->res.jsonValue["Description"] =
2166             "Collection of HostLogger Entries";
2167         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2168         logEntryArray = nlohmann::json::array();
2169         asyncResp->res.jsonValue["Members@odata.count"] = 0;
2170 
2171         std::vector<std::filesystem::path> hostLoggerFiles;
2172         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
2173         {
2174             BMCWEB_LOG_ERROR << "fail to get host log file path";
2175             return;
2176         }
2177         // If we weren't provided top and skip limits, use the defaults.
2178         size_t skip = delegatedQuery.skip.value_or(0);
2179         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
2180         size_t logCount = 0;
2181         // This vector only store the entries we want to expose that
2182         // control by skip and top.
2183         std::vector<std::string> logEntries;
2184         if (!getHostLoggerEntries(hostLoggerFiles, skip, top, logEntries,
2185                                   logCount))
2186         {
2187             messages::internalError(asyncResp->res);
2188             return;
2189         }
2190         // If vector is empty, that means skip value larger than total
2191         // log count
2192         if (logEntries.empty())
2193         {
2194             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
2195             return;
2196         }
2197         if (!logEntries.empty())
2198         {
2199             for (size_t i = 0; i < logEntries.size(); i++)
2200             {
2201                 nlohmann::json::object_t hostLogEntry;
2202                 fillHostLoggerEntryJson(std::to_string(skip + i), logEntries[i],
2203                                         hostLogEntry);
2204                 logEntryArray.push_back(std::move(hostLogEntry));
2205             }
2206 
2207             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
2208             if (skip + top < logCount)
2209             {
2210                 asyncResp->res.jsonValue["Members@odata.nextLink"] =
2211                     "/redfish/v1/Systems/system/LogServices/HostLogger/Entries?$skip=" +
2212                     std::to_string(skip + top);
2213             }
2214         }
2215         });
2216 }
2217 
2218 inline void requestRoutesSystemHostLoggerLogEntry(App& app)
2219 {
2220     BMCWEB_ROUTE(
2221         app, "/redfish/v1/Systems/<str>/LogServices/HostLogger/Entries/<str>/")
2222         .privileges(redfish::privileges::getLogEntry)
2223         .methods(boost::beast::http::verb::get)(
2224             [&app](const crow::Request& req,
2225                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2226                    const std::string& systemName, const std::string& param) {
2227         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2228         {
2229             return;
2230         }
2231         if (systemName != "system")
2232         {
2233             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2234                                        systemName);
2235             return;
2236         }
2237         const std::string& targetID = param;
2238 
2239         uint64_t idInt = 0;
2240 
2241         // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
2242         const char* end = targetID.data() + targetID.size();
2243 
2244         auto [ptr, ec] = std::from_chars(targetID.data(), end, idInt);
2245         if (ec == std::errc::invalid_argument ||
2246             ec == std::errc::result_out_of_range)
2247         {
2248             messages::resourceNotFound(asyncResp->res, "LogEntry", param);
2249             return;
2250         }
2251 
2252         std::vector<std::filesystem::path> hostLoggerFiles;
2253         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
2254         {
2255             BMCWEB_LOG_ERROR << "fail to get host log file path";
2256             return;
2257         }
2258 
2259         size_t logCount = 0;
2260         size_t top = 1;
2261         std::vector<std::string> logEntries;
2262         // We can get specific entry by skip and top. For example, if we
2263         // want to get nth entry, we can set skip = n-1 and top = 1 to
2264         // get that entry
2265         if (!getHostLoggerEntries(hostLoggerFiles, idInt, top, logEntries,
2266                                   logCount))
2267         {
2268             messages::internalError(asyncResp->res);
2269             return;
2270         }
2271 
2272         if (!logEntries.empty())
2273         {
2274             nlohmann::json::object_t hostLogEntry;
2275             fillHostLoggerEntryJson(targetID, logEntries[0], hostLogEntry);
2276             asyncResp->res.jsonValue.update(hostLogEntry);
2277             return;
2278         }
2279 
2280         // Requested ID was not found
2281         messages::resourceNotFound(asyncResp->res, "LogEntry", param);
2282         });
2283 }
2284 
2285 inline void handleBMCLogServicesCollectionGet(
2286     crow::App& app, const crow::Request& req,
2287     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2288 {
2289     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2290     {
2291         return;
2292     }
2293     // Collections don't include the static data added by SubRoute
2294     // because it has a duplicate entry for members
2295     asyncResp->res.jsonValue["@odata.type"] =
2296         "#LogServiceCollection.LogServiceCollection";
2297     asyncResp->res.jsonValue["@odata.id"] =
2298         "/redfish/v1/Managers/bmc/LogServices";
2299     asyncResp->res.jsonValue["Name"] = "Open BMC Log Services Collection";
2300     asyncResp->res.jsonValue["Description"] =
2301         "Collection of LogServices for this Manager";
2302     nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
2303     logServiceArray = nlohmann::json::array();
2304 
2305 #ifdef BMCWEB_ENABLE_REDFISH_BMC_JOURNAL
2306     nlohmann::json::object_t journal;
2307     journal["@odata.id"] = "/redfish/v1/Managers/bmc/LogServices/Journal";
2308     logServiceArray.push_back(std::move(journal));
2309 #endif
2310 
2311     asyncResp->res.jsonValue["Members@odata.count"] = logServiceArray.size();
2312 
2313 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
2314     constexpr std::array<std::string_view, 1> interfaces = {
2315         "xyz.openbmc_project.Collection.DeleteAll"};
2316     dbus::utility::getSubTreePaths(
2317         "/xyz/openbmc_project/dump", 0, interfaces,
2318         [asyncResp](
2319             const boost::system::error_code& ec,
2320             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
2321         if (ec)
2322         {
2323             BMCWEB_LOG_ERROR
2324                 << "handleBMCLogServicesCollectionGet respHandler got error "
2325                 << ec;
2326             // Assume that getting an error simply means there are no dump
2327             // LogServices. Return without adding any error response.
2328             return;
2329         }
2330 
2331         nlohmann::json& logServiceArrayLocal =
2332             asyncResp->res.jsonValue["Members"];
2333 
2334         for (const std::string& path : subTreePaths)
2335         {
2336             if (path == "/xyz/openbmc_project/dump/bmc")
2337             {
2338                 nlohmann::json::object_t member;
2339                 member["@odata.id"] =
2340                     "/redfish/v1/Managers/bmc/LogServices/Dump";
2341                 logServiceArrayLocal.push_back(std::move(member));
2342             }
2343             else if (path == "/xyz/openbmc_project/dump/faultlog")
2344             {
2345                 nlohmann::json::object_t member;
2346                 member["@odata.id"] =
2347                     "/redfish/v1/Managers/bmc/LogServices/FaultLog";
2348                 logServiceArrayLocal.push_back(std::move(member));
2349             }
2350         }
2351 
2352         asyncResp->res.jsonValue["Members@odata.count"] =
2353             logServiceArrayLocal.size();
2354         });
2355 #endif
2356 }
2357 
2358 inline void requestRoutesBMCLogServiceCollection(App& app)
2359 {
2360     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/")
2361         .privileges(redfish::privileges::getLogServiceCollection)
2362         .methods(boost::beast::http::verb::get)(
2363             std::bind_front(handleBMCLogServicesCollectionGet, std::ref(app)));
2364 }
2365 
2366 inline void requestRoutesBMCJournalLogService(App& app)
2367 {
2368     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/")
2369         .privileges(redfish::privileges::getLogService)
2370         .methods(boost::beast::http::verb::get)(
2371             [&app](const crow::Request& req,
2372                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2373         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2374         {
2375             return;
2376         }
2377         asyncResp->res.jsonValue["@odata.type"] =
2378             "#LogService.v1_1_0.LogService";
2379         asyncResp->res.jsonValue["@odata.id"] =
2380             "/redfish/v1/Managers/bmc/LogServices/Journal";
2381         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Log Service";
2382         asyncResp->res.jsonValue["Description"] = "BMC Journal Log Service";
2383         asyncResp->res.jsonValue["Id"] = "Journal";
2384         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2385 
2386         std::pair<std::string, std::string> redfishDateTimeOffset =
2387             redfish::time_utils::getDateTimeOffsetNow();
2388         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2389         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2390             redfishDateTimeOffset.second;
2391 
2392         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2393             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2394         });
2395 }
2396 
2397 static int
2398     fillBMCJournalLogEntryJson(const std::string& bmcJournalLogEntryID,
2399                                sd_journal* journal,
2400                                nlohmann::json::object_t& bmcJournalLogEntryJson)
2401 {
2402     // Get the Log Entry contents
2403     int ret = 0;
2404 
2405     std::string message;
2406     std::string_view syslogID;
2407     ret = getJournalMetadata(journal, "SYSLOG_IDENTIFIER", syslogID);
2408     if (ret < 0)
2409     {
2410         BMCWEB_LOG_ERROR << "Failed to read SYSLOG_IDENTIFIER field: "
2411                          << strerror(-ret);
2412     }
2413     if (!syslogID.empty())
2414     {
2415         message += std::string(syslogID) + ": ";
2416     }
2417 
2418     std::string_view msg;
2419     ret = getJournalMetadata(journal, "MESSAGE", msg);
2420     if (ret < 0)
2421     {
2422         BMCWEB_LOG_ERROR << "Failed to read MESSAGE field: " << strerror(-ret);
2423         return 1;
2424     }
2425     message += std::string(msg);
2426 
2427     // Get the severity from the PRIORITY field
2428     long int severity = 8; // Default to an invalid priority
2429     ret = getJournalMetadata(journal, "PRIORITY", 10, severity);
2430     if (ret < 0)
2431     {
2432         BMCWEB_LOG_ERROR << "Failed to read PRIORITY field: " << strerror(-ret);
2433     }
2434 
2435     // Get the Created time from the timestamp
2436     std::string entryTimeStr;
2437     if (!getEntryTimestamp(journal, entryTimeStr))
2438     {
2439         return 1;
2440     }
2441 
2442     // Fill in the log entry with the gathered data
2443     bmcJournalLogEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
2444     bmcJournalLogEntryJson["@odata.id"] = crow::utility::urlFromPieces(
2445         "redfish", "v1", "Managers", "bmc", "LogServices", "Journal", "Entries",
2446         bmcJournalLogEntryID);
2447     bmcJournalLogEntryJson["Name"] = "BMC Journal Entry";
2448     bmcJournalLogEntryJson["Id"] = bmcJournalLogEntryID;
2449     bmcJournalLogEntryJson["Message"] = std::move(message);
2450     bmcJournalLogEntryJson["EntryType"] = "Oem";
2451     bmcJournalLogEntryJson["Severity"] = severity <= 2   ? "Critical"
2452                                          : severity <= 4 ? "Warning"
2453                                                          : "OK";
2454     bmcJournalLogEntryJson["OemRecordFormat"] = "BMC Journal Entry";
2455     bmcJournalLogEntryJson["Created"] = std::move(entryTimeStr);
2456     return 0;
2457 }
2458 
2459 inline void requestRoutesBMCJournalLogEntryCollection(App& app)
2460 {
2461     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/")
2462         .privileges(redfish::privileges::getLogEntryCollection)
2463         .methods(boost::beast::http::verb::get)(
2464             [&app](const crow::Request& req,
2465                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2466         query_param::QueryCapabilities capabilities = {
2467             .canDelegateTop = true,
2468             .canDelegateSkip = true,
2469         };
2470         query_param::Query delegatedQuery;
2471         if (!redfish::setUpRedfishRouteWithDelegation(
2472                 app, req, asyncResp, delegatedQuery, capabilities))
2473         {
2474             return;
2475         }
2476 
2477         size_t skip = delegatedQuery.skip.value_or(0);
2478         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
2479 
2480         // Collections don't include the static data added by SubRoute
2481         // because it has a duplicate entry for members
2482         asyncResp->res.jsonValue["@odata.type"] =
2483             "#LogEntryCollection.LogEntryCollection";
2484         asyncResp->res.jsonValue["@odata.id"] =
2485             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2486         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Entries";
2487         asyncResp->res.jsonValue["Description"] =
2488             "Collection of BMC Journal Entries";
2489         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2490         logEntryArray = nlohmann::json::array();
2491 
2492         // Go through the journal and use the timestamp to create a
2493         // unique ID for each entry
2494         sd_journal* journalTmp = nullptr;
2495         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2496         if (ret < 0)
2497         {
2498             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2499             messages::internalError(asyncResp->res);
2500             return;
2501         }
2502         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2503             journalTmp, sd_journal_close);
2504         journalTmp = nullptr;
2505         uint64_t entryCount = 0;
2506         // Reset the unique ID on the first entry
2507         bool firstEntry = true;
2508         SD_JOURNAL_FOREACH(journal.get())
2509         {
2510             entryCount++;
2511             // Handle paging using skip (number of entries to skip from
2512             // the start) and top (number of entries to display)
2513             if (entryCount <= skip || entryCount > skip + top)
2514             {
2515                 continue;
2516             }
2517 
2518             std::string idStr;
2519             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2520             {
2521                 continue;
2522             }
2523             firstEntry = false;
2524 
2525             nlohmann::json::object_t bmcJournalLogEntry;
2526             if (fillBMCJournalLogEntryJson(idStr, journal.get(),
2527                                            bmcJournalLogEntry) != 0)
2528             {
2529                 messages::internalError(asyncResp->res);
2530                 return;
2531             }
2532             logEntryArray.push_back(std::move(bmcJournalLogEntry));
2533         }
2534         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
2535         if (skip + top < entryCount)
2536         {
2537             asyncResp->res.jsonValue["Members@odata.nextLink"] =
2538                 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries?$skip=" +
2539                 std::to_string(skip + top);
2540         }
2541         });
2542 }
2543 
2544 inline void requestRoutesBMCJournalLogEntry(App& app)
2545 {
2546     BMCWEB_ROUTE(app,
2547                  "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/<str>/")
2548         .privileges(redfish::privileges::getLogEntry)
2549         .methods(boost::beast::http::verb::get)(
2550             [&app](const crow::Request& req,
2551                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2552                    const std::string& entryID) {
2553         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2554         {
2555             return;
2556         }
2557         // Convert the unique ID back to a timestamp to find the entry
2558         uint64_t ts = 0;
2559         uint64_t index = 0;
2560         if (!getTimestampFromID(asyncResp, entryID, ts, index))
2561         {
2562             return;
2563         }
2564 
2565         sd_journal* journalTmp = nullptr;
2566         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2567         if (ret < 0)
2568         {
2569             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2570             messages::internalError(asyncResp->res);
2571             return;
2572         }
2573         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2574             journalTmp, sd_journal_close);
2575         journalTmp = nullptr;
2576         // Go to the timestamp in the log and move to the entry at the
2577         // index tracking the unique ID
2578         std::string idStr;
2579         bool firstEntry = true;
2580         ret = sd_journal_seek_realtime_usec(journal.get(), ts);
2581         if (ret < 0)
2582         {
2583             BMCWEB_LOG_ERROR << "failed to seek to an entry in journal"
2584                              << strerror(-ret);
2585             messages::internalError(asyncResp->res);
2586             return;
2587         }
2588         for (uint64_t i = 0; i <= index; i++)
2589         {
2590             sd_journal_next(journal.get());
2591             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2592             {
2593                 messages::internalError(asyncResp->res);
2594                 return;
2595             }
2596             firstEntry = false;
2597         }
2598         // Confirm that the entry ID matches what was requested
2599         if (idStr != entryID)
2600         {
2601             messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
2602             return;
2603         }
2604 
2605         nlohmann::json::object_t bmcJournalLogEntry;
2606         if (fillBMCJournalLogEntryJson(entryID, journal.get(),
2607                                        bmcJournalLogEntry) != 0)
2608         {
2609             messages::internalError(asyncResp->res);
2610             return;
2611         }
2612         asyncResp->res.jsonValue.update(bmcJournalLogEntry);
2613         });
2614 }
2615 
2616 inline void
2617     getDumpServiceInfo(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2618                        const std::string& dumpType)
2619 {
2620     std::string dumpPath;
2621     std::string overWritePolicy;
2622     bool collectDiagnosticDataSupported = false;
2623 
2624     if (dumpType == "BMC")
2625     {
2626         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump";
2627         overWritePolicy = "WrapsWhenFull";
2628         collectDiagnosticDataSupported = true;
2629     }
2630     else if (dumpType == "FaultLog")
2631     {
2632         dumpPath = "/redfish/v1/Managers/bmc/LogServices/FaultLog";
2633         overWritePolicy = "Unknown";
2634         collectDiagnosticDataSupported = false;
2635     }
2636     else if (dumpType == "System")
2637     {
2638         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump";
2639         overWritePolicy = "WrapsWhenFull";
2640         collectDiagnosticDataSupported = true;
2641     }
2642     else
2643     {
2644         BMCWEB_LOG_ERROR << "getDumpServiceInfo() invalid dump type: "
2645                          << dumpType;
2646         messages::internalError(asyncResp->res);
2647         return;
2648     }
2649 
2650     asyncResp->res.jsonValue["@odata.id"] = dumpPath;
2651     asyncResp->res.jsonValue["@odata.type"] = "#LogService.v1_2_0.LogService";
2652     asyncResp->res.jsonValue["Name"] = "Dump LogService";
2653     asyncResp->res.jsonValue["Description"] = dumpType + " Dump LogService";
2654     asyncResp->res.jsonValue["Id"] = std::filesystem::path(dumpPath).filename();
2655     asyncResp->res.jsonValue["OverWritePolicy"] = std::move(overWritePolicy);
2656 
2657     std::pair<std::string, std::string> redfishDateTimeOffset =
2658         redfish::time_utils::getDateTimeOffsetNow();
2659     asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2660     asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2661         redfishDateTimeOffset.second;
2662 
2663     asyncResp->res.jsonValue["Entries"]["@odata.id"] = dumpPath + "/Entries";
2664 
2665     if (collectDiagnosticDataSupported)
2666     {
2667         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
2668                                 ["target"] =
2669             dumpPath + "/Actions/LogService.CollectDiagnosticData";
2670     }
2671 
2672     constexpr std::array<std::string_view, 1> interfaces = {deleteAllInterface};
2673     dbus::utility::getSubTreePaths(
2674         "/xyz/openbmc_project/dump", 0, interfaces,
2675         [asyncResp, dumpType, dumpPath](
2676             const boost::system::error_code& ec,
2677             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
2678         if (ec)
2679         {
2680             BMCWEB_LOG_ERROR << "getDumpServiceInfo respHandler got error "
2681                              << ec;
2682             // Assume that getting an error simply means there are no dump
2683             // LogServices. Return without adding any error response.
2684             return;
2685         }
2686 
2687         const std::string dbusDumpPath =
2688             "/xyz/openbmc_project/dump/" +
2689             boost::algorithm::to_lower_copy(dumpType);
2690 
2691         for (const std::string& path : subTreePaths)
2692         {
2693             if (path == dbusDumpPath)
2694             {
2695                 asyncResp->res
2696                     .jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
2697                     dumpPath + "/Actions/LogService.ClearLog";
2698                 break;
2699             }
2700         }
2701         });
2702 }
2703 
2704 inline void handleLogServicesDumpServiceGet(
2705     crow::App& app, const std::string& dumpType, const crow::Request& req,
2706     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2707 {
2708     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2709     {
2710         return;
2711     }
2712     getDumpServiceInfo(asyncResp, dumpType);
2713 }
2714 
2715 inline void handleLogServicesDumpServiceComputerSystemGet(
2716     crow::App& app, const crow::Request& req,
2717     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2718     const std::string& chassisId)
2719 {
2720     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2721     {
2722         return;
2723     }
2724     if (chassisId != "system")
2725     {
2726         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2727         return;
2728     }
2729     getDumpServiceInfo(asyncResp, "System");
2730 }
2731 
2732 inline void handleLogServicesDumpEntriesCollectionGet(
2733     crow::App& app, const std::string& dumpType, const crow::Request& req,
2734     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2735 {
2736     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2737     {
2738         return;
2739     }
2740     getDumpEntryCollection(asyncResp, dumpType);
2741 }
2742 
2743 inline void handleLogServicesDumpEntriesCollectionComputerSystemGet(
2744     crow::App& app, const crow::Request& req,
2745     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2746     const std::string& chassisId)
2747 {
2748     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2749     {
2750         return;
2751     }
2752     if (chassisId != "system")
2753     {
2754         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2755         return;
2756     }
2757     getDumpEntryCollection(asyncResp, "System");
2758 }
2759 
2760 inline void handleLogServicesDumpEntryGet(
2761     crow::App& app, const std::string& dumpType, const crow::Request& req,
2762     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2763     const std::string& dumpId)
2764 {
2765     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2766     {
2767         return;
2768     }
2769     getDumpEntryById(asyncResp, dumpId, dumpType);
2770 }
2771 inline void handleLogServicesDumpEntryComputerSystemGet(
2772     crow::App& app, const crow::Request& req,
2773     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2774     const std::string& chassisId, const std::string& dumpId)
2775 {
2776     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2777     {
2778         return;
2779     }
2780     if (chassisId != "system")
2781     {
2782         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2783         return;
2784     }
2785     getDumpEntryById(asyncResp, dumpId, "System");
2786 }
2787 
2788 inline void handleLogServicesDumpEntryDelete(
2789     crow::App& app, const std::string& dumpType, const crow::Request& req,
2790     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2791     const std::string& dumpId)
2792 {
2793     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2794     {
2795         return;
2796     }
2797     deleteDumpEntry(asyncResp, dumpId, dumpType);
2798 }
2799 
2800 inline void handleLogServicesDumpEntryComputerSystemDelete(
2801     crow::App& app, const crow::Request& req,
2802     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2803     const std::string& chassisId, const std::string& dumpId)
2804 {
2805     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2806     {
2807         return;
2808     }
2809     if (chassisId != "system")
2810     {
2811         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2812         return;
2813     }
2814     deleteDumpEntry(asyncResp, dumpId, "System");
2815 }
2816 
2817 inline void handleLogServicesDumpCollectDiagnosticDataPost(
2818     crow::App& app, const std::string& dumpType, const crow::Request& req,
2819     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2820 {
2821     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2822     {
2823         return;
2824     }
2825     createDump(asyncResp, req, dumpType);
2826 }
2827 
2828 inline void handleLogServicesDumpCollectDiagnosticDataComputerSystemPost(
2829     crow::App& app, const crow::Request& req,
2830     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2831     const std::string& chassisId)
2832 {
2833     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2834     {
2835         return;
2836     }
2837     if (chassisId != "system")
2838     {
2839         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2840         return;
2841     }
2842     createDump(asyncResp, req, "System");
2843 }
2844 
2845 inline void handleLogServicesDumpClearLogPost(
2846     crow::App& app, const std::string& dumpType, const crow::Request& req,
2847     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2848 {
2849     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2850     {
2851         return;
2852     }
2853     clearDump(asyncResp, dumpType);
2854 }
2855 
2856 inline void handleLogServicesDumpClearLogComputerSystemPost(
2857     crow::App& app, const crow::Request& req,
2858     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2859     const std::string& chassisId)
2860 {
2861     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2862     {
2863         return;
2864     }
2865     if (chassisId != "system")
2866     {
2867         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2868         return;
2869     }
2870     clearDump(asyncResp, "System");
2871 }
2872 
2873 inline void requestRoutesBMCDumpService(App& app)
2874 {
2875     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/")
2876         .privileges(redfish::privileges::getLogService)
2877         .methods(boost::beast::http::verb::get)(std::bind_front(
2878             handleLogServicesDumpServiceGet, std::ref(app), "BMC"));
2879 }
2880 
2881 inline void requestRoutesBMCDumpEntryCollection(App& app)
2882 {
2883     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/")
2884         .privileges(redfish::privileges::getLogEntryCollection)
2885         .methods(boost::beast::http::verb::get)(std::bind_front(
2886             handleLogServicesDumpEntriesCollectionGet, std::ref(app), "BMC"));
2887 }
2888 
2889 inline void requestRoutesBMCDumpEntry(App& app)
2890 {
2891     BMCWEB_ROUTE(app,
2892                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2893         .privileges(redfish::privileges::getLogEntry)
2894         .methods(boost::beast::http::verb::get)(std::bind_front(
2895             handleLogServicesDumpEntryGet, std::ref(app), "BMC"));
2896 
2897     BMCWEB_ROUTE(app,
2898                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2899         .privileges(redfish::privileges::deleteLogEntry)
2900         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2901             handleLogServicesDumpEntryDelete, std::ref(app), "BMC"));
2902 }
2903 
2904 inline void requestRoutesBMCDumpCreate(App& app)
2905 {
2906     BMCWEB_ROUTE(
2907         app,
2908         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2909         .privileges(redfish::privileges::postLogService)
2910         .methods(boost::beast::http::verb::post)(
2911             std::bind_front(handleLogServicesDumpCollectDiagnosticDataPost,
2912                             std::ref(app), "BMC"));
2913 }
2914 
2915 inline void requestRoutesBMCDumpClear(App& app)
2916 {
2917     BMCWEB_ROUTE(
2918         app,
2919         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog/")
2920         .privileges(redfish::privileges::postLogService)
2921         .methods(boost::beast::http::verb::post)(std::bind_front(
2922             handleLogServicesDumpClearLogPost, std::ref(app), "BMC"));
2923 }
2924 
2925 inline void requestRoutesFaultLogDumpService(App& app)
2926 {
2927     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/")
2928         .privileges(redfish::privileges::getLogService)
2929         .methods(boost::beast::http::verb::get)(std::bind_front(
2930             handleLogServicesDumpServiceGet, std::ref(app), "FaultLog"));
2931 }
2932 
2933 inline void requestRoutesFaultLogDumpEntryCollection(App& app)
2934 {
2935     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/")
2936         .privileges(redfish::privileges::getLogEntryCollection)
2937         .methods(boost::beast::http::verb::get)(
2938             std::bind_front(handleLogServicesDumpEntriesCollectionGet,
2939                             std::ref(app), "FaultLog"));
2940 }
2941 
2942 inline void requestRoutesFaultLogDumpEntry(App& app)
2943 {
2944     BMCWEB_ROUTE(app,
2945                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2946         .privileges(redfish::privileges::getLogEntry)
2947         .methods(boost::beast::http::verb::get)(std::bind_front(
2948             handleLogServicesDumpEntryGet, std::ref(app), "FaultLog"));
2949 
2950     BMCWEB_ROUTE(app,
2951                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2952         .privileges(redfish::privileges::deleteLogEntry)
2953         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2954             handleLogServicesDumpEntryDelete, std::ref(app), "FaultLog"));
2955 }
2956 
2957 inline void requestRoutesFaultLogDumpClear(App& app)
2958 {
2959     BMCWEB_ROUTE(
2960         app,
2961         "/redfish/v1/Managers/bmc/LogServices/FaultLog/Actions/LogService.ClearLog/")
2962         .privileges(redfish::privileges::postLogService)
2963         .methods(boost::beast::http::verb::post)(std::bind_front(
2964             handleLogServicesDumpClearLogPost, std::ref(app), "FaultLog"));
2965 }
2966 
2967 inline void requestRoutesSystemDumpService(App& app)
2968 {
2969     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Dump/")
2970         .privileges(redfish::privileges::getLogService)
2971         .methods(boost::beast::http::verb::get)(std::bind_front(
2972             handleLogServicesDumpServiceComputerSystemGet, std::ref(app)));
2973 }
2974 
2975 inline void requestRoutesSystemDumpEntryCollection(App& app)
2976 {
2977     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/")
2978         .privileges(redfish::privileges::getLogEntryCollection)
2979         .methods(boost::beast::http::verb::get)(std::bind_front(
2980             handleLogServicesDumpEntriesCollectionComputerSystemGet,
2981             std::ref(app)));
2982 }
2983 
2984 inline void requestRoutesSystemDumpEntry(App& app)
2985 {
2986     BMCWEB_ROUTE(app,
2987                  "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/<str>/")
2988         .privileges(redfish::privileges::getLogEntry)
2989         .methods(boost::beast::http::verb::get)(std::bind_front(
2990             handleLogServicesDumpEntryComputerSystemGet, std::ref(app)));
2991 
2992     BMCWEB_ROUTE(app,
2993                  "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/<str>/")
2994         .privileges(redfish::privileges::deleteLogEntry)
2995         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2996             handleLogServicesDumpEntryComputerSystemDelete, std::ref(app)));
2997 }
2998 
2999 inline void requestRoutesSystemDumpCreate(App& app)
3000 {
3001     BMCWEB_ROUTE(
3002         app,
3003         "/redfish/v1/Systems/<str>/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
3004         .privileges(redfish::privileges::postLogService)
3005         .methods(boost::beast::http::verb::post)(std::bind_front(
3006             handleLogServicesDumpCollectDiagnosticDataComputerSystemPost,
3007             std::ref(app)));
3008 }
3009 
3010 inline void requestRoutesSystemDumpClear(App& app)
3011 {
3012     BMCWEB_ROUTE(
3013         app,
3014         "/redfish/v1/Systems/<str>/LogServices/Dump/Actions/LogService.ClearLog/")
3015         .privileges(redfish::privileges::postLogService)
3016         .methods(boost::beast::http::verb::post)(std::bind_front(
3017             handleLogServicesDumpClearLogComputerSystemPost, std::ref(app)));
3018 }
3019 
3020 inline void requestRoutesCrashdumpService(App& app)
3021 {
3022     // Note: Deviated from redfish privilege registry for GET & HEAD
3023     // method for security reasons.
3024     /**
3025      * Functions triggers appropriate requests on DBus
3026      */
3027     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Crashdump/")
3028         // This is incorrect, should be:
3029         //.privileges(redfish::privileges::getLogService)
3030         .privileges({{"ConfigureManager"}})
3031         .methods(boost::beast::http::verb::get)(
3032             [&app](const crow::Request& req,
3033                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3034                    const std::string& systemName) {
3035         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3036         {
3037             return;
3038         }
3039         if (systemName != "system")
3040         {
3041             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3042                                        systemName);
3043             return;
3044         }
3045 
3046         // Copy over the static data to include the entries added by
3047         // SubRoute
3048         asyncResp->res.jsonValue["@odata.id"] =
3049             "/redfish/v1/Systems/system/LogServices/Crashdump";
3050         asyncResp->res.jsonValue["@odata.type"] =
3051             "#LogService.v1_2_0.LogService";
3052         asyncResp->res.jsonValue["Name"] = "Open BMC Oem Crashdump Service";
3053         asyncResp->res.jsonValue["Description"] = "Oem Crashdump Service";
3054         asyncResp->res.jsonValue["Id"] = "Oem Crashdump";
3055         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
3056         asyncResp->res.jsonValue["MaxNumberOfRecords"] = 3;
3057 
3058         std::pair<std::string, std::string> redfishDateTimeOffset =
3059             redfish::time_utils::getDateTimeOffsetNow();
3060         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3061         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3062             redfishDateTimeOffset.second;
3063 
3064         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
3065             crow::utility::urlFromPieces("redfish", "v1", "Systems", "system",
3066                                          "LogServices", "Crashdump", "Entries");
3067         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
3068             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog";
3069         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
3070                                 ["target"] =
3071             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData";
3072         });
3073 }
3074 
3075 void inline requestRoutesCrashdumpClear(App& app)
3076 {
3077     BMCWEB_ROUTE(
3078         app,
3079         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Actions/LogService.ClearLog/")
3080         // This is incorrect, should be:
3081         //.privileges(redfish::privileges::postLogService)
3082         .privileges({{"ConfigureComponents"}})
3083         .methods(boost::beast::http::verb::post)(
3084             [&app](const crow::Request& req,
3085                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3086                    const std::string& systemName) {
3087         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3088         {
3089             return;
3090         }
3091         if (systemName != "system")
3092         {
3093             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3094                                        systemName);
3095             return;
3096         }
3097         crow::connections::systemBus->async_method_call(
3098             [asyncResp](const boost::system::error_code& ec,
3099                         const std::string&) {
3100             if (ec)
3101             {
3102                 messages::internalError(asyncResp->res);
3103                 return;
3104             }
3105             messages::success(asyncResp->res);
3106             },
3107             crashdumpObject, crashdumpPath, deleteAllInterface, "DeleteAll");
3108         });
3109 }
3110 
3111 static void
3112     logCrashdumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3113                       const std::string& logID, nlohmann::json& logEntryJson)
3114 {
3115     auto getStoredLogCallback =
3116         [asyncResp, logID,
3117          &logEntryJson](const boost::system::error_code& ec,
3118                         const dbus::utility::DBusPropertiesMap& params) {
3119         if (ec)
3120         {
3121             BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
3122             if (ec.value() ==
3123                 boost::system::linux_error::bad_request_descriptor)
3124             {
3125                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3126             }
3127             else
3128             {
3129                 messages::internalError(asyncResp->res);
3130             }
3131             return;
3132         }
3133 
3134         std::string timestamp{};
3135         std::string filename{};
3136         std::string logfile{};
3137         parseCrashdumpParameters(params, filename, timestamp, logfile);
3138 
3139         if (filename.empty() || timestamp.empty())
3140         {
3141             messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3142             return;
3143         }
3144 
3145         std::string crashdumpURI =
3146             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" +
3147             logID + "/" + filename;
3148         nlohmann::json::object_t logEntry;
3149         logEntry["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
3150         logEntry["@odata.id"] = crow::utility::urlFromPieces(
3151             "redfish", "v1", "Systems", "system", "LogServices", "Crashdump",
3152             "Entries", logID);
3153         logEntry["Name"] = "CPU Crashdump";
3154         logEntry["Id"] = logID;
3155         logEntry["EntryType"] = "Oem";
3156         logEntry["AdditionalDataURI"] = std::move(crashdumpURI);
3157         logEntry["DiagnosticDataType"] = "OEM";
3158         logEntry["OEMDiagnosticDataType"] = "PECICrashdump";
3159         logEntry["Created"] = std::move(timestamp);
3160 
3161         // If logEntryJson references an array of LogEntry resources
3162         // ('Members' list), then push this as a new entry, otherwise set it
3163         // directly
3164         if (logEntryJson.is_array())
3165         {
3166             logEntryJson.push_back(logEntry);
3167             asyncResp->res.jsonValue["Members@odata.count"] =
3168                 logEntryJson.size();
3169         }
3170         else
3171         {
3172             logEntryJson.update(logEntry);
3173         }
3174     };
3175     sdbusplus::asio::getAllProperties(
3176         *crow::connections::systemBus, crashdumpObject,
3177         crashdumpPath + std::string("/") + logID, crashdumpInterface,
3178         std::move(getStoredLogCallback));
3179 }
3180 
3181 inline void requestRoutesCrashdumpEntryCollection(App& app)
3182 {
3183     // Note: Deviated from redfish privilege registry for GET & HEAD
3184     // method for security reasons.
3185     /**
3186      * Functions triggers appropriate requests on DBus
3187      */
3188     BMCWEB_ROUTE(app,
3189                  "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/")
3190         // This is incorrect, should be.
3191         //.privileges(redfish::privileges::postLogEntryCollection)
3192         .privileges({{"ConfigureComponents"}})
3193         .methods(boost::beast::http::verb::get)(
3194             [&app](const crow::Request& req,
3195                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3196                    const std::string& systemName) {
3197         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3198         {
3199             return;
3200         }
3201         if (systemName != "system")
3202         {
3203             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3204                                        systemName);
3205             return;
3206         }
3207 
3208         constexpr std::array<std::string_view, 1> interfaces = {
3209             crashdumpInterface};
3210         dbus::utility::getSubTreePaths(
3211             "/", 0, interfaces,
3212             [asyncResp](const boost::system::error_code& ec,
3213                         const std::vector<std::string>& resp) {
3214             if (ec)
3215             {
3216                 if (ec.value() !=
3217                     boost::system::errc::no_such_file_or_directory)
3218                 {
3219                     BMCWEB_LOG_DEBUG << "failed to get entries ec: "
3220                                      << ec.message();
3221                     messages::internalError(asyncResp->res);
3222                     return;
3223                 }
3224             }
3225             asyncResp->res.jsonValue["@odata.type"] =
3226                 "#LogEntryCollection.LogEntryCollection";
3227             asyncResp->res.jsonValue["@odata.id"] =
3228                 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
3229             asyncResp->res.jsonValue["Name"] = "Open BMC Crashdump Entries";
3230             asyncResp->res.jsonValue["Description"] =
3231                 "Collection of Crashdump Entries";
3232             asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3233             asyncResp->res.jsonValue["Members@odata.count"] = 0;
3234 
3235             for (const std::string& path : resp)
3236             {
3237                 const sdbusplus::message::object_path objPath(path);
3238                 // Get the log ID
3239                 std::string logID = objPath.filename();
3240                 if (logID.empty())
3241                 {
3242                     continue;
3243                 }
3244                 // Add the log entry to the array
3245                 logCrashdumpEntry(asyncResp, logID,
3246                                   asyncResp->res.jsonValue["Members"]);
3247             }
3248             });
3249         });
3250 }
3251 
3252 inline void requestRoutesCrashdumpEntry(App& app)
3253 {
3254     // Note: Deviated from redfish privilege registry for GET & HEAD
3255     // method for security reasons.
3256 
3257     BMCWEB_ROUTE(
3258         app, "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/<str>/")
3259         // this is incorrect, should be
3260         // .privileges(redfish::privileges::getLogEntry)
3261         .privileges({{"ConfigureComponents"}})
3262         .methods(boost::beast::http::verb::get)(
3263             [&app](const crow::Request& req,
3264                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3265                    const std::string& systemName, const std::string& param) {
3266         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3267         {
3268             return;
3269         }
3270         if (systemName != "system")
3271         {
3272             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3273                                        systemName);
3274             return;
3275         }
3276         const std::string& logID = param;
3277         logCrashdumpEntry(asyncResp, logID, asyncResp->res.jsonValue);
3278         });
3279 }
3280 
3281 inline void requestRoutesCrashdumpFile(App& app)
3282 {
3283     // Note: Deviated from redfish privilege registry for GET & HEAD
3284     // method for security reasons.
3285     BMCWEB_ROUTE(
3286         app,
3287         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/<str>/<str>/")
3288         .privileges(redfish::privileges::getLogEntry)
3289         .methods(boost::beast::http::verb::get)(
3290             [](const crow::Request& req,
3291                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3292                const std::string& systemName, const std::string& logID,
3293                const std::string& fileName) {
3294         // Do not call getRedfishRoute here since the crashdump file is not a
3295         // Redfish resource.
3296 
3297         if (systemName != "system")
3298         {
3299             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3300                                        systemName);
3301             return;
3302         }
3303 
3304         auto getStoredLogCallback =
3305             [asyncResp, logID, fileName, url(boost::urls::url(req.url()))](
3306                 const boost::system::error_code& ec,
3307                 const std::vector<
3308                     std::pair<std::string, dbus::utility::DbusVariantType>>&
3309                     resp) {
3310             if (ec)
3311             {
3312                 BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
3313                 messages::internalError(asyncResp->res);
3314                 return;
3315             }
3316 
3317             std::string dbusFilename{};
3318             std::string dbusTimestamp{};
3319             std::string dbusFilepath{};
3320 
3321             parseCrashdumpParameters(resp, dbusFilename, dbusTimestamp,
3322                                      dbusFilepath);
3323 
3324             if (dbusFilename.empty() || dbusTimestamp.empty() ||
3325                 dbusFilepath.empty())
3326             {
3327                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3328                 return;
3329             }
3330 
3331             // Verify the file name parameter is correct
3332             if (fileName != dbusFilename)
3333             {
3334                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3335                 return;
3336             }
3337 
3338             if (!std::filesystem::exists(dbusFilepath))
3339             {
3340                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3341                 return;
3342             }
3343             std::ifstream ifs(dbusFilepath, std::ios::in | std::ios::binary);
3344             asyncResp->res.body() =
3345                 std::string(std::istreambuf_iterator<char>{ifs}, {});
3346 
3347             // Configure this to be a file download when accessed
3348             // from a browser
3349             asyncResp->res.addHeader(
3350                 boost::beast::http::field::content_disposition, "attachment");
3351         };
3352         sdbusplus::asio::getAllProperties(
3353             *crow::connections::systemBus, crashdumpObject,
3354             crashdumpPath + std::string("/") + logID, crashdumpInterface,
3355             std::move(getStoredLogCallback));
3356         });
3357 }
3358 
3359 enum class OEMDiagnosticType
3360 {
3361     onDemand,
3362     telemetry,
3363     invalid,
3364 };
3365 
3366 inline OEMDiagnosticType getOEMDiagnosticType(std::string_view oemDiagStr)
3367 {
3368     if (oemDiagStr == "OnDemand")
3369     {
3370         return OEMDiagnosticType::onDemand;
3371     }
3372     if (oemDiagStr == "Telemetry")
3373     {
3374         return OEMDiagnosticType::telemetry;
3375     }
3376 
3377     return OEMDiagnosticType::invalid;
3378 }
3379 
3380 inline void requestRoutesCrashdumpCollect(App& app)
3381 {
3382     // Note: Deviated from redfish privilege registry for GET & HEAD
3383     // method for security reasons.
3384     BMCWEB_ROUTE(
3385         app,
3386         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData/")
3387         // The below is incorrect;  Should be ConfigureManager
3388         //.privileges(redfish::privileges::postLogService)
3389         .privileges({{"ConfigureComponents"}})
3390         .methods(boost::beast::http::verb::post)(
3391             [&app](const crow::Request& req,
3392                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3393                    const std::string& systemName) {
3394         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3395         {
3396             return;
3397         }
3398 
3399         if (systemName != "system")
3400         {
3401             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3402                                        systemName);
3403             return;
3404         }
3405 
3406         std::string diagnosticDataType;
3407         std::string oemDiagnosticDataType;
3408         if (!redfish::json_util::readJsonAction(
3409                 req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
3410                 "OEMDiagnosticDataType", oemDiagnosticDataType))
3411         {
3412             return;
3413         }
3414 
3415         if (diagnosticDataType != "OEM")
3416         {
3417             BMCWEB_LOG_ERROR
3418                 << "Only OEM DiagnosticDataType supported for Crashdump";
3419             messages::actionParameterValueFormatError(
3420                 asyncResp->res, diagnosticDataType, "DiagnosticDataType",
3421                 "CollectDiagnosticData");
3422             return;
3423         }
3424 
3425         OEMDiagnosticType oemDiagType =
3426             getOEMDiagnosticType(oemDiagnosticDataType);
3427 
3428         std::string iface;
3429         std::string method;
3430         std::string taskMatchStr;
3431         if (oemDiagType == OEMDiagnosticType::onDemand)
3432         {
3433             iface = crashdumpOnDemandInterface;
3434             method = "GenerateOnDemandLog";
3435             taskMatchStr = "type='signal',"
3436                            "interface='org.freedesktop.DBus.Properties',"
3437                            "member='PropertiesChanged',"
3438                            "arg0namespace='com.intel.crashdump'";
3439         }
3440         else if (oemDiagType == OEMDiagnosticType::telemetry)
3441         {
3442             iface = crashdumpTelemetryInterface;
3443             method = "GenerateTelemetryLog";
3444             taskMatchStr = "type='signal',"
3445                            "interface='org.freedesktop.DBus.Properties',"
3446                            "member='PropertiesChanged',"
3447                            "arg0namespace='com.intel.crashdump'";
3448         }
3449         else
3450         {
3451             BMCWEB_LOG_ERROR << "Unsupported OEMDiagnosticDataType: "
3452                              << oemDiagnosticDataType;
3453             messages::actionParameterValueFormatError(
3454                 asyncResp->res, oemDiagnosticDataType, "OEMDiagnosticDataType",
3455                 "CollectDiagnosticData");
3456             return;
3457         }
3458 
3459         auto collectCrashdumpCallback =
3460             [asyncResp, payload(task::Payload(req)),
3461              taskMatchStr](const boost::system::error_code& ec,
3462                            const std::string&) mutable {
3463             if (ec)
3464             {
3465                 if (ec.value() == boost::system::errc::operation_not_supported)
3466                 {
3467                     messages::resourceInStandby(asyncResp->res);
3468                 }
3469                 else if (ec.value() ==
3470                          boost::system::errc::device_or_resource_busy)
3471                 {
3472                     messages::serviceTemporarilyUnavailable(asyncResp->res,
3473                                                             "60");
3474                 }
3475                 else
3476                 {
3477                     messages::internalError(asyncResp->res);
3478                 }
3479                 return;
3480             }
3481             std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
3482                 [](const boost::system::error_code& err, sdbusplus::message_t&,
3483                    const std::shared_ptr<task::TaskData>& taskData) {
3484                 if (!err)
3485                 {
3486                     taskData->messages.emplace_back(messages::taskCompletedOK(
3487                         std::to_string(taskData->index)));
3488                     taskData->state = "Completed";
3489                 }
3490                 return task::completed;
3491                 },
3492                 taskMatchStr);
3493 
3494             task->startTimer(std::chrono::minutes(5));
3495             task->populateResp(asyncResp->res);
3496             task->payload.emplace(std::move(payload));
3497         };
3498 
3499         crow::connections::systemBus->async_method_call(
3500             std::move(collectCrashdumpCallback), crashdumpObject, crashdumpPath,
3501             iface, method);
3502         });
3503 }
3504 
3505 /**
3506  * DBusLogServiceActionsClear class supports POST method for ClearLog action.
3507  */
3508 inline void requestRoutesDBusLogServiceActionsClear(App& app)
3509 {
3510     /**
3511      * Function handles POST method request.
3512      * The Clear Log actions does not require any parameter.The action deletes
3513      * all entries found in the Entries collection for this Log Service.
3514      */
3515 
3516     BMCWEB_ROUTE(
3517         app,
3518         "/redfish/v1/Systems/<str>/LogServices/EventLog/Actions/LogService.ClearLog/")
3519         .privileges(redfish::privileges::postLogService)
3520         .methods(boost::beast::http::verb::post)(
3521             [&app](const crow::Request& req,
3522                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3523                    const std::string& systemName) {
3524         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3525         {
3526             return;
3527         }
3528         if (systemName != "system")
3529         {
3530             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3531                                        systemName);
3532             return;
3533         }
3534         BMCWEB_LOG_DEBUG << "Do delete all entries.";
3535 
3536         // Process response from Logging service.
3537         auto respHandler = [asyncResp](const boost::system::error_code& ec) {
3538             BMCWEB_LOG_DEBUG << "doClearLog resp_handler callback: Done";
3539             if (ec)
3540             {
3541                 // TODO Handle for specific error code
3542                 BMCWEB_LOG_ERROR << "doClearLog resp_handler got error " << ec;
3543                 asyncResp->res.result(
3544                     boost::beast::http::status::internal_server_error);
3545                 return;
3546             }
3547 
3548             asyncResp->res.result(boost::beast::http::status::no_content);
3549         };
3550 
3551         // Make call to Logging service to request Clear Log
3552         crow::connections::systemBus->async_method_call(
3553             respHandler, "xyz.openbmc_project.Logging",
3554             "/xyz/openbmc_project/logging",
3555             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3556         });
3557 }
3558 
3559 /****************************************************
3560  * Redfish PostCode interfaces
3561  * using DBUS interface: getPostCodesTS
3562  ******************************************************/
3563 inline void requestRoutesPostCodesLogService(App& app)
3564 {
3565     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/PostCodes/")
3566         .privileges(redfish::privileges::getLogService)
3567         .methods(boost::beast::http::verb::get)(
3568             [&app](const crow::Request& req,
3569                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3570                    const std::string& systemName) {
3571         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3572         {
3573             return;
3574         }
3575         if (systemName != "system")
3576         {
3577             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3578                                        systemName);
3579             return;
3580         }
3581         asyncResp->res.jsonValue["@odata.id"] =
3582             "/redfish/v1/Systems/system/LogServices/PostCodes";
3583         asyncResp->res.jsonValue["@odata.type"] =
3584             "#LogService.v1_1_0.LogService";
3585         asyncResp->res.jsonValue["Name"] = "POST Code Log Service";
3586         asyncResp->res.jsonValue["Description"] = "POST Code Log Service";
3587         asyncResp->res.jsonValue["Id"] = "PostCodes";
3588         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
3589         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
3590             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3591 
3592         std::pair<std::string, std::string> redfishDateTimeOffset =
3593             redfish::time_utils::getDateTimeOffsetNow();
3594         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3595         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3596             redfishDateTimeOffset.second;
3597 
3598         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
3599             {"target",
3600              "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog"}};
3601         });
3602 }
3603 
3604 inline void requestRoutesPostCodesClear(App& app)
3605 {
3606     BMCWEB_ROUTE(
3607         app,
3608         "/redfish/v1/Systems/<str>/LogServices/PostCodes/Actions/LogService.ClearLog/")
3609         // The following privilege is incorrect;  It should be ConfigureManager
3610         //.privileges(redfish::privileges::postLogService)
3611         .privileges({{"ConfigureComponents"}})
3612         .methods(boost::beast::http::verb::post)(
3613             [&app](const crow::Request& req,
3614                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3615                    const std::string& systemName) {
3616         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3617         {
3618             return;
3619         }
3620         if (systemName != "system")
3621         {
3622             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3623                                        systemName);
3624             return;
3625         }
3626         BMCWEB_LOG_DEBUG << "Do delete all postcodes entries.";
3627 
3628         // Make call to post-code service to request clear all
3629         crow::connections::systemBus->async_method_call(
3630             [asyncResp](const boost::system::error_code& ec) {
3631             if (ec)
3632             {
3633                 // TODO Handle for specific error code
3634                 BMCWEB_LOG_ERROR << "doClearPostCodes resp_handler got error "
3635                                  << ec;
3636                 asyncResp->res.result(
3637                     boost::beast::http::status::internal_server_error);
3638                 messages::internalError(asyncResp->res);
3639                 return;
3640             }
3641             },
3642             "xyz.openbmc_project.State.Boot.PostCode0",
3643             "/xyz/openbmc_project/State/Boot/PostCode0",
3644             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3645         });
3646 }
3647 
3648 /**
3649  * @brief Parse post code ID and get the current value and index value
3650  *        eg: postCodeID=B1-2, currentValue=1, index=2
3651  *
3652  * @param[in]  postCodeID     Post Code ID
3653  * @param[out] currentValue   Current value
3654  * @param[out] index          Index value
3655  *
3656  * @return bool true if the parsing is successful, false the parsing fails
3657  */
3658 inline static bool parsePostCode(const std::string& postCodeID,
3659                                  uint64_t& currentValue, uint16_t& index)
3660 {
3661     std::vector<std::string> split;
3662     bmcweb::split(split, postCodeID, '-');
3663     if (split.size() != 2 || split[0].length() < 2 || split[0].front() != 'B')
3664     {
3665         return false;
3666     }
3667 
3668     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3669     const char* start = split[0].data() + 1;
3670     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3671     const char* end = split[0].data() + split[0].size();
3672     auto [ptrIndex, ecIndex] = std::from_chars(start, end, index);
3673 
3674     if (ptrIndex != end || ecIndex != std::errc())
3675     {
3676         return false;
3677     }
3678 
3679     start = split[1].data();
3680 
3681     // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
3682     end = split[1].data() + split[1].size();
3683     auto [ptrValue, ecValue] = std::from_chars(start, end, currentValue);
3684 
3685     return ptrValue == end && ecValue == std::errc();
3686 }
3687 
3688 static bool fillPostCodeEntry(
3689     const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3690     const boost::container::flat_map<
3691         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>& postcode,
3692     const uint16_t bootIndex, const uint64_t codeIndex = 0,
3693     const uint64_t skip = 0, const uint64_t top = 0)
3694 {
3695     // Get the Message from the MessageRegistry
3696     const registries::Message* message =
3697         registries::getMessage("OpenBMC.0.2.BIOSPOSTCode");
3698 
3699     uint64_t currentCodeIndex = 0;
3700     uint64_t firstCodeTimeUs = 0;
3701     for (const std::pair<uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3702              code : postcode)
3703     {
3704         currentCodeIndex++;
3705         std::string postcodeEntryID =
3706             "B" + std::to_string(bootIndex) + "-" +
3707             std::to_string(currentCodeIndex); // 1 based index in EntryID string
3708 
3709         uint64_t usecSinceEpoch = code.first;
3710         uint64_t usTimeOffset = 0;
3711 
3712         if (1 == currentCodeIndex)
3713         { // already incremented
3714             firstCodeTimeUs = code.first;
3715         }
3716         else
3717         {
3718             usTimeOffset = code.first - firstCodeTimeUs;
3719         }
3720 
3721         // skip if no specific codeIndex is specified and currentCodeIndex does
3722         // not fall between top and skip
3723         if ((codeIndex == 0) &&
3724             (currentCodeIndex <= skip || currentCodeIndex > top))
3725         {
3726             continue;
3727         }
3728 
3729         // skip if a specific codeIndex is specified and does not match the
3730         // currentIndex
3731         if ((codeIndex > 0) && (currentCodeIndex != codeIndex))
3732         {
3733             // This is done for simplicity. 1st entry is needed to calculate
3734             // time offset. To improve efficiency, one can get to the entry
3735             // directly (possibly with flatmap's nth method)
3736             continue;
3737         }
3738 
3739         // currentCodeIndex is within top and skip or equal to specified code
3740         // index
3741 
3742         // Get the Created time from the timestamp
3743         std::string entryTimeStr;
3744         entryTimeStr = redfish::time_utils::getDateTimeUintUs(usecSinceEpoch);
3745 
3746         // assemble messageArgs: BootIndex, TimeOffset(100us), PostCode(hex)
3747         std::ostringstream hexCode;
3748         hexCode << "0x" << std::setfill('0') << std::setw(2) << std::hex
3749                 << std::get<0>(code.second);
3750         std::ostringstream timeOffsetStr;
3751         // Set Fixed -Point Notation
3752         timeOffsetStr << std::fixed;
3753         // Set precision to 4 digits
3754         timeOffsetStr << std::setprecision(4);
3755         // Add double to stream
3756         timeOffsetStr << static_cast<double>(usTimeOffset) / 1000 / 1000;
3757         std::vector<std::string> messageArgs = {
3758             std::to_string(bootIndex), timeOffsetStr.str(), hexCode.str()};
3759 
3760         // Get MessageArgs template from message registry
3761         std::string msg;
3762         if (message != nullptr)
3763         {
3764             msg = message->message;
3765 
3766             // fill in this post code value
3767             int i = 0;
3768             for (const std::string& messageArg : messageArgs)
3769             {
3770                 std::string argStr = "%" + std::to_string(++i);
3771                 size_t argPos = msg.find(argStr);
3772                 if (argPos != std::string::npos)
3773                 {
3774                     msg.replace(argPos, argStr.length(), messageArg);
3775                 }
3776             }
3777         }
3778 
3779         // Get Severity template from message registry
3780         std::string severity;
3781         if (message != nullptr)
3782         {
3783             severity = message->messageSeverity;
3784         }
3785 
3786         // Format entry
3787         nlohmann::json::object_t bmcLogEntry;
3788         bmcLogEntry["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
3789         bmcLogEntry["@odata.id"] = crow::utility::urlFromPieces(
3790             "redfish", "v1", "Systems", "system", "LogServices", "PostCodes",
3791             "Entries", postcodeEntryID);
3792         bmcLogEntry["Name"] = "POST Code Log Entry";
3793         bmcLogEntry["Id"] = postcodeEntryID;
3794         bmcLogEntry["Message"] = std::move(msg);
3795         bmcLogEntry["MessageId"] = "OpenBMC.0.2.BIOSPOSTCode";
3796         bmcLogEntry["MessageArgs"] = std::move(messageArgs);
3797         bmcLogEntry["EntryType"] = "Event";
3798         bmcLogEntry["Severity"] = std::move(severity);
3799         bmcLogEntry["Created"] = entryTimeStr;
3800         if (!std::get<std::vector<uint8_t>>(code.second).empty())
3801         {
3802             bmcLogEntry["AdditionalDataURI"] =
3803                 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/" +
3804                 postcodeEntryID + "/attachment";
3805         }
3806 
3807         // codeIndex is only specified when querying single entry, return only
3808         // that entry in this case
3809         if (codeIndex != 0)
3810         {
3811             aResp->res.jsonValue.update(bmcLogEntry);
3812             return true;
3813         }
3814 
3815         nlohmann::json& logEntryArray = aResp->res.jsonValue["Members"];
3816         logEntryArray.push_back(std::move(bmcLogEntry));
3817     }
3818 
3819     // Return value is always false when querying multiple entries
3820     return false;
3821 }
3822 
3823 static void getPostCodeForEntry(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3824                                 const std::string& entryId)
3825 {
3826     uint16_t bootIndex = 0;
3827     uint64_t codeIndex = 0;
3828     if (!parsePostCode(entryId, codeIndex, bootIndex))
3829     {
3830         // Requested ID was not found
3831         messages::resourceNotFound(aResp->res, "LogEntry", entryId);
3832         return;
3833     }
3834 
3835     if (bootIndex == 0 || codeIndex == 0)
3836     {
3837         // 0 is an invalid index
3838         messages::resourceNotFound(aResp->res, "LogEntry", entryId);
3839         return;
3840     }
3841 
3842     crow::connections::systemBus->async_method_call(
3843         [aResp, entryId, bootIndex,
3844          codeIndex](const boost::system::error_code& ec,
3845                     const boost::container::flat_map<
3846                         uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3847                         postcode) {
3848         if (ec)
3849         {
3850             BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3851             messages::internalError(aResp->res);
3852             return;
3853         }
3854 
3855         if (postcode.empty())
3856         {
3857             messages::resourceNotFound(aResp->res, "LogEntry", entryId);
3858             return;
3859         }
3860 
3861         if (!fillPostCodeEntry(aResp, postcode, bootIndex, codeIndex))
3862         {
3863             messages::resourceNotFound(aResp->res, "LogEntry", entryId);
3864             return;
3865         }
3866         },
3867         "xyz.openbmc_project.State.Boot.PostCode0",
3868         "/xyz/openbmc_project/State/Boot/PostCode0",
3869         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3870         bootIndex);
3871 }
3872 
3873 static void getPostCodeForBoot(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3874                                const uint16_t bootIndex,
3875                                const uint16_t bootCount,
3876                                const uint64_t entryCount, size_t skip,
3877                                size_t top)
3878 {
3879     crow::connections::systemBus->async_method_call(
3880         [aResp, bootIndex, bootCount, entryCount, skip,
3881          top](const boost::system::error_code& ec,
3882               const boost::container::flat_map<
3883                   uint64_t, std::tuple<uint64_t, std::vector<uint8_t>>>&
3884                   postcode) {
3885         if (ec)
3886         {
3887             BMCWEB_LOG_DEBUG << "DBUS POST CODE PostCode response error";
3888             messages::internalError(aResp->res);
3889             return;
3890         }
3891 
3892         uint64_t endCount = entryCount;
3893         if (!postcode.empty())
3894         {
3895             endCount = entryCount + postcode.size();
3896             if (skip < endCount && (top + skip) > entryCount)
3897             {
3898                 uint64_t thisBootSkip =
3899                     std::max(static_cast<uint64_t>(skip), entryCount) -
3900                     entryCount;
3901                 uint64_t thisBootTop =
3902                     std::min(static_cast<uint64_t>(top + skip), endCount) -
3903                     entryCount;
3904 
3905                 fillPostCodeEntry(aResp, postcode, bootIndex, 0, thisBootSkip,
3906                                   thisBootTop);
3907             }
3908             aResp->res.jsonValue["Members@odata.count"] = endCount;
3909         }
3910 
3911         // continue to previous bootIndex
3912         if (bootIndex < bootCount)
3913         {
3914             getPostCodeForBoot(aResp, static_cast<uint16_t>(bootIndex + 1),
3915                                bootCount, endCount, skip, top);
3916         }
3917         else if (skip + top < endCount)
3918         {
3919             aResp->res.jsonValue["Members@odata.nextLink"] =
3920                 "/redfish/v1/Systems/system/LogServices/PostCodes/Entries?$skip=" +
3921                 std::to_string(skip + top);
3922         }
3923         },
3924         "xyz.openbmc_project.State.Boot.PostCode0",
3925         "/xyz/openbmc_project/State/Boot/PostCode0",
3926         "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodesWithTimeStamp",
3927         bootIndex);
3928 }
3929 
3930 static void
3931     getCurrentBootNumber(const std::shared_ptr<bmcweb::AsyncResp>& aResp,
3932                          size_t skip, size_t top)
3933 {
3934     uint64_t entryCount = 0;
3935     sdbusplus::asio::getProperty<uint16_t>(
3936         *crow::connections::systemBus,
3937         "xyz.openbmc_project.State.Boot.PostCode0",
3938         "/xyz/openbmc_project/State/Boot/PostCode0",
3939         "xyz.openbmc_project.State.Boot.PostCode", "CurrentBootCycleCount",
3940         [aResp, entryCount, skip, top](const boost::system::error_code& ec,
3941                                        const uint16_t bootCount) {
3942         if (ec)
3943         {
3944             BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
3945             messages::internalError(aResp->res);
3946             return;
3947         }
3948         getPostCodeForBoot(aResp, 1, bootCount, entryCount, skip, top);
3949         });
3950 }
3951 
3952 inline void requestRoutesPostCodesEntryCollection(App& app)
3953 {
3954     BMCWEB_ROUTE(app,
3955                  "/redfish/v1/Systems/<str>/LogServices/PostCodes/Entries/")
3956         .privileges(redfish::privileges::getLogEntryCollection)
3957         .methods(boost::beast::http::verb::get)(
3958             [&app](const crow::Request& req,
3959                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3960                    const std::string& systemName) {
3961         query_param::QueryCapabilities capabilities = {
3962             .canDelegateTop = true,
3963             .canDelegateSkip = true,
3964         };
3965         query_param::Query delegatedQuery;
3966         if (!redfish::setUpRedfishRouteWithDelegation(
3967                 app, req, asyncResp, delegatedQuery, capabilities))
3968         {
3969             return;
3970         }
3971 
3972         if (systemName != "system")
3973         {
3974             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3975                                        systemName);
3976             return;
3977         }
3978         asyncResp->res.jsonValue["@odata.type"] =
3979             "#LogEntryCollection.LogEntryCollection";
3980         asyncResp->res.jsonValue["@odata.id"] =
3981             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3982         asyncResp->res.jsonValue["Name"] = "BIOS POST Code Log Entries";
3983         asyncResp->res.jsonValue["Description"] =
3984             "Collection of POST Code Log Entries";
3985         asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3986         asyncResp->res.jsonValue["Members@odata.count"] = 0;
3987         size_t skip = delegatedQuery.skip.value_or(0);
3988         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
3989         getCurrentBootNumber(asyncResp, skip, top);
3990         });
3991 }
3992 
3993 inline void requestRoutesPostCodesEntryAdditionalData(App& app)
3994 {
3995     BMCWEB_ROUTE(
3996         app,
3997         "/redfish/v1/Systems/<str>/LogServices/PostCodes/Entries/<str>/attachment/")
3998         .privileges(redfish::privileges::getLogEntry)
3999         .methods(boost::beast::http::verb::get)(
4000             [&app](const crow::Request& req,
4001                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
4002                    const std::string& systemName,
4003                    const std::string& postCodeID) {
4004         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
4005         {
4006             return;
4007         }
4008         if (http_helpers::isContentTypeAllowed(
4009                 req.getHeaderValue("Accept"),
4010                 http_helpers::ContentType::OctetStream, true))
4011         {
4012             asyncResp->res.result(boost::beast::http::status::bad_request);
4013             return;
4014         }
4015         if (systemName != "system")
4016         {
4017             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
4018                                        systemName);
4019             return;
4020         }
4021 
4022         uint64_t currentValue = 0;
4023         uint16_t index = 0;
4024         if (!parsePostCode(postCodeID, currentValue, index))
4025         {
4026             messages::resourceNotFound(asyncResp->res, "LogEntry", postCodeID);
4027             return;
4028         }
4029 
4030         crow::connections::systemBus->async_method_call(
4031             [asyncResp, postCodeID, currentValue](
4032                 const boost::system::error_code& ec,
4033                 const std::vector<std::tuple<uint64_t, std::vector<uint8_t>>>&
4034                     postcodes) {
4035             if (ec.value() == EBADR)
4036             {
4037                 messages::resourceNotFound(asyncResp->res, "LogEntry",
4038                                            postCodeID);
4039                 return;
4040             }
4041             if (ec)
4042             {
4043                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
4044                 messages::internalError(asyncResp->res);
4045                 return;
4046             }
4047 
4048             size_t value = static_cast<size_t>(currentValue) - 1;
4049             if (value == std::string::npos || postcodes.size() < currentValue)
4050             {
4051                 BMCWEB_LOG_WARNING << "Wrong currentValue value";
4052                 messages::resourceNotFound(asyncResp->res, "LogEntry",
4053                                            postCodeID);
4054                 return;
4055             }
4056 
4057             const auto& [tID, c] = postcodes[value];
4058             if (c.empty())
4059             {
4060                 BMCWEB_LOG_WARNING << "No found post code data";
4061                 messages::resourceNotFound(asyncResp->res, "LogEntry",
4062                                            postCodeID);
4063                 return;
4064             }
4065             // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
4066             const char* d = reinterpret_cast<const char*>(c.data());
4067             std::string_view strData(d, c.size());
4068 
4069             asyncResp->res.addHeader(boost::beast::http::field::content_type,
4070                                      "application/octet-stream");
4071             asyncResp->res.addHeader(
4072                 boost::beast::http::field::content_transfer_encoding, "Base64");
4073             asyncResp->res.body() = crow::utility::base64encode(strData);
4074             },
4075             "xyz.openbmc_project.State.Boot.PostCode0",
4076             "/xyz/openbmc_project/State/Boot/PostCode0",
4077             "xyz.openbmc_project.State.Boot.PostCode", "GetPostCodes", index);
4078         });
4079 }
4080 
4081 inline void requestRoutesPostCodesEntry(App& app)
4082 {
4083     BMCWEB_ROUTE(
4084         app, "/redfish/v1/Systems/<str>/LogServices/PostCodes/Entries/<str>/")
4085         .privileges(redfish::privileges::getLogEntry)
4086         .methods(boost::beast::http::verb::get)(
4087             [&app](const crow::Request& req,
4088                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
4089                    const std::string& systemName, const std::string& targetID) {
4090         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
4091         {
4092             return;
4093         }
4094         if (systemName != "system")
4095         {
4096             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
4097                                        systemName);
4098             return;
4099         }
4100 
4101         getPostCodeForEntry(asyncResp, targetID);
4102         });
4103 }
4104 
4105 } // namespace redfish
4106