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 <boost/url/format.hpp>
46 #include <sdbusplus/asio/property.hpp>
47 #include <sdbusplus/unpack_properties.hpp>
48 
49 #include <array>
50 #include <charconv>
51 #include <filesystem>
52 #include <optional>
53 #include <span>
54 #include <string_view>
55 #include <variant>
56 
57 namespace redfish
58 {
59 
60 constexpr const char* crashdumpObject = "com.intel.crashdump";
61 constexpr const char* crashdumpPath = "/com/intel/crashdump";
62 constexpr const char* crashdumpInterface = "com.intel.crashdump";
63 constexpr const char* deleteAllInterface =
64     "xyz.openbmc_project.Collection.DeleteAll";
65 constexpr const char* crashdumpOnDemandInterface =
66     "com.intel.crashdump.OnDemand";
67 constexpr const char* crashdumpTelemetryInterface =
68     "com.intel.crashdump.Telemetry";
69 
70 enum class DumpCreationProgress
71 {
72     DUMP_CREATE_SUCCESS,
73     DUMP_CREATE_FAILED,
74     DUMP_CREATE_INPROGRESS
75 };
76 
77 namespace fs = std::filesystem;
78 
79 inline std::string translateSeverityDbusToRedfish(const std::string& s)
80 {
81     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Alert") ||
82         (s == "xyz.openbmc_project.Logging.Entry.Level.Critical") ||
83         (s == "xyz.openbmc_project.Logging.Entry.Level.Emergency") ||
84         (s == "xyz.openbmc_project.Logging.Entry.Level.Error"))
85     {
86         return "Critical";
87     }
88     if ((s == "xyz.openbmc_project.Logging.Entry.Level.Debug") ||
89         (s == "xyz.openbmc_project.Logging.Entry.Level.Informational") ||
90         (s == "xyz.openbmc_project.Logging.Entry.Level.Notice"))
91     {
92         return "OK";
93     }
94     if (s == "xyz.openbmc_project.Logging.Entry.Level.Warning")
95     {
96         return "Warning";
97     }
98     return "";
99 }
100 
101 inline std::optional<bool> getProviderNotifyAction(const std::string& notify)
102 {
103     std::optional<bool> notifyAction;
104     if (notify == "xyz.openbmc_project.Logging.Entry.Notify.Notify")
105     {
106         notifyAction = true;
107     }
108     else if (notify == "xyz.openbmc_project.Logging.Entry.Notify.Inhibit")
109     {
110         notifyAction = false;
111     }
112 
113     return notifyAction;
114 }
115 
116 inline static int getJournalMetadata(sd_journal* journal,
117                                      std::string_view field,
118                                      std::string_view& contents)
119 {
120     const char* data = nullptr;
121     size_t length = 0;
122     int ret = 0;
123     // Get the metadata from the requested field of the journal entry
124     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
125     const void** dataVoid = reinterpret_cast<const void**>(&data);
126 
127     ret = sd_journal_get_data(journal, field.data(), dataVoid, &length);
128     if (ret < 0)
129     {
130         return ret;
131     }
132     contents = std::string_view(data, length);
133     // Only use the content after the "=" character.
134     contents.remove_prefix(std::min(contents.find('=') + 1, contents.size()));
135     return ret;
136 }
137 
138 inline static int getJournalMetadata(sd_journal* journal,
139                                      std::string_view field, const int& base,
140                                      long int& contents)
141 {
142     int ret = 0;
143     std::string_view metadata;
144     // Get the metadata from the requested field of the journal entry
145     ret = getJournalMetadata(journal, field, metadata);
146     if (ret < 0)
147     {
148         return ret;
149     }
150     contents = strtol(metadata.data(), nullptr, base);
151     return ret;
152 }
153 
154 inline static bool getEntryTimestamp(sd_journal* journal,
155                                      std::string& entryTimestamp)
156 {
157     int ret = 0;
158     uint64_t timestamp = 0;
159     ret = sd_journal_get_realtime_usec(journal, &timestamp);
160     if (ret < 0)
161     {
162         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
163                          << strerror(-ret);
164         return false;
165     }
166     entryTimestamp = redfish::time_utils::getDateTimeUintUs(timestamp);
167     return true;
168 }
169 
170 inline static bool getUniqueEntryID(sd_journal* journal, std::string& entryID,
171                                     const bool firstEntry = true)
172 {
173     int ret = 0;
174     static uint64_t prevTs = 0;
175     static int index = 0;
176     if (firstEntry)
177     {
178         prevTs = 0;
179     }
180 
181     // Get the entry timestamp
182     uint64_t curTs = 0;
183     ret = sd_journal_get_realtime_usec(journal, &curTs);
184     if (ret < 0)
185     {
186         BMCWEB_LOG_ERROR << "Failed to read entry timestamp: "
187                          << strerror(-ret);
188         return false;
189     }
190     // If the timestamp isn't unique, increment the index
191     if (curTs == prevTs)
192     {
193         index++;
194     }
195     else
196     {
197         // Otherwise, reset it
198         index = 0;
199     }
200     // Save the timestamp
201     prevTs = curTs;
202 
203     entryID = std::to_string(curTs);
204     if (index > 0)
205     {
206         entryID += "_" + std::to_string(index);
207     }
208     return true;
209 }
210 
211 static bool getUniqueEntryID(const std::string& logEntry, std::string& entryID,
212                              const bool firstEntry = true)
213 {
214     static time_t prevTs = 0;
215     static int index = 0;
216     if (firstEntry)
217     {
218         prevTs = 0;
219     }
220 
221     // Get the entry timestamp
222     std::time_t curTs = 0;
223     std::tm timeStruct = {};
224     std::istringstream entryStream(logEntry);
225     if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
226     {
227         curTs = std::mktime(&timeStruct);
228     }
229     // If the timestamp isn't unique, increment the index
230     if (curTs == prevTs)
231     {
232         index++;
233     }
234     else
235     {
236         // Otherwise, reset it
237         index = 0;
238     }
239     // Save the timestamp
240     prevTs = curTs;
241 
242     entryID = std::to_string(curTs);
243     if (index > 0)
244     {
245         entryID += "_" + std::to_string(index);
246     }
247     return true;
248 }
249 
250 inline static bool
251     getTimestampFromID(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
252                        const std::string& entryID, uint64_t& timestamp,
253                        uint64_t& index)
254 {
255     if (entryID.empty())
256     {
257         return false;
258     }
259     // Convert the unique ID back to a timestamp to find the entry
260     std::string_view tsStr(entryID);
261 
262     auto underscorePos = tsStr.find('_');
263     if (underscorePos != std::string_view::npos)
264     {
265         // Timestamp has an index
266         tsStr.remove_suffix(tsStr.size() - underscorePos);
267         std::string_view indexStr(entryID);
268         indexStr.remove_prefix(underscorePos + 1);
269         auto [ptr, ec] = std::from_chars(indexStr.begin(), indexStr.end(),
270                                          index);
271         if (ec != std::errc())
272         {
273             messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
274             return false;
275         }
276     }
277     // Timestamp has no index
278     auto [ptr, ec] = std::from_chars(tsStr.begin(), tsStr.end(), 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"] = "Collection of " + dumpType +
493                                                   " 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"] = entriesPath + entryID +
556                                                  "/attachment";
557                 thisEntry["AdditionalDataSizeBytes"] = size;
558             }
559             else if (dumpType == "System")
560             {
561                 thisEntry["DiagnosticDataType"] = "OEM";
562                 thisEntry["OEMDiagnosticDataType"] = "System";
563                 thisEntry["AdditionalDataURI"] = entriesPath + entryID +
564                                                  "/attachment";
565                 thisEntry["AdditionalDataSizeBytes"] = size;
566             }
567             entriesArray.emplace_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             boost::urls::url url = boost::urls::format(
858                 "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/{}", dumpId);
859 
860             std::string headerLoc = "Location: ";
861             headerLoc += url.buffer();
862 
863             taskData->payload->httpHeaders.emplace_back(std::move(headerLoc));
864 
865             BMCWEB_LOG_DEBUG << createdObjPath.str
866                              << ": Dump creation task completed";
867             taskData->state = "Completed";
868             return task::completed;
869             },
870             "type='signal',interface='org.freedesktop.DBus.Properties',"
871             "member='PropertiesChanged',path='" +
872                 createdObjPath.str + "'");
873 
874         // The task timer is set to max time limit within which the
875         // requested dump will be collected.
876         task->startTimer(std::chrono::minutes(6));
877         task->populateResp(asyncResp->res);
878         task->payload.emplace(payload);
879         },
880         "xyz.openbmc_project.Dump.Manager", createdObjPath,
881         "org.freedesktop.DBus.Introspectable", "Introspect");
882 }
883 
884 inline void createDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
885                        const crow::Request& req, const std::string& dumpType)
886 {
887     std::string dumpPath = getDumpEntriesPath(dumpType);
888     if (dumpPath.empty())
889     {
890         messages::internalError(asyncResp->res);
891         return;
892     }
893 
894     std::optional<std::string> diagnosticDataType;
895     std::optional<std::string> oemDiagnosticDataType;
896 
897     if (!redfish::json_util::readJsonAction(
898             req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
899             "OEMDiagnosticDataType", oemDiagnosticDataType))
900     {
901         return;
902     }
903 
904     if (dumpType == "System")
905     {
906         if (!oemDiagnosticDataType || !diagnosticDataType)
907         {
908             BMCWEB_LOG_ERROR
909                 << "CreateDump action parameter 'DiagnosticDataType'/'OEMDiagnosticDataType' value not found!";
910             messages::actionParameterMissing(
911                 asyncResp->res, "CollectDiagnosticData",
912                 "DiagnosticDataType & OEMDiagnosticDataType");
913             return;
914         }
915         if ((*oemDiagnosticDataType != "System") ||
916             (*diagnosticDataType != "OEM"))
917         {
918             BMCWEB_LOG_ERROR << "Wrong parameter values passed";
919             messages::internalError(asyncResp->res);
920             return;
921         }
922         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump/";
923     }
924     else if (dumpType == "BMC")
925     {
926         if (!diagnosticDataType)
927         {
928             BMCWEB_LOG_ERROR
929                 << "CreateDump action parameter 'DiagnosticDataType' not found!";
930             messages::actionParameterMissing(
931                 asyncResp->res, "CollectDiagnosticData", "DiagnosticDataType");
932             return;
933         }
934         if (*diagnosticDataType != "Manager")
935         {
936             BMCWEB_LOG_ERROR
937                 << "Wrong parameter value passed for 'DiagnosticDataType'";
938             messages::internalError(asyncResp->res);
939             return;
940         }
941         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump/";
942     }
943     else
944     {
945         BMCWEB_LOG_ERROR << "CreateDump failed. Unknown dump type";
946         messages::internalError(asyncResp->res);
947         return;
948     }
949 
950     std::vector<std::pair<std::string, std::variant<std::string, uint64_t>>>
951         createDumpParamVec;
952 
953     if (req.session != nullptr)
954     {
955         createDumpParamVec.emplace_back(
956             "xyz.openbmc_project.Dump.Create.CreateParameters.OriginatorId",
957             req.session->clientIp);
958         createDumpParamVec.emplace_back(
959             "xyz.openbmc_project.Dump.Create.CreateParameters.OriginatorType",
960             "xyz.openbmc_project.Common.OriginatedBy.OriginatorTypes.Client");
961     }
962 
963     crow::connections::systemBus->async_method_call(
964         [asyncResp, payload(task::Payload(req)),
965          dumpPath](const boost::system::error_code& ec,
966                    const sdbusplus::message_t& msg,
967                    const sdbusplus::message::object_path& objPath) mutable {
968         if (ec)
969         {
970             BMCWEB_LOG_ERROR << "CreateDump resp_handler got error " << ec;
971             const sd_bus_error* dbusError = msg.get_error();
972             if (dbusError == nullptr)
973             {
974                 messages::internalError(asyncResp->res);
975                 return;
976             }
977 
978             BMCWEB_LOG_ERROR << "CreateDump DBus error: " << dbusError->name
979                              << " and error msg: " << dbusError->message;
980             if (std::string_view(
981                     "xyz.openbmc_project.Common.Error.NotAllowed") ==
982                 dbusError->name)
983             {
984                 messages::resourceInStandby(asyncResp->res);
985                 return;
986             }
987             if (std::string_view(
988                     "xyz.openbmc_project.Dump.Create.Error.Disabled") ==
989                 dbusError->name)
990             {
991                 messages::serviceDisabled(asyncResp->res, dumpPath);
992                 return;
993             }
994             if (std::string_view(
995                     "xyz.openbmc_project.Common.Error.Unavailable") ==
996                 dbusError->name)
997             {
998                 messages::resourceInUse(asyncResp->res);
999                 return;
1000             }
1001             // Other Dbus errors such as:
1002             // xyz.openbmc_project.Common.Error.InvalidArgument &
1003             // org.freedesktop.DBus.Error.InvalidArgs are all related to
1004             // the dbus call that is made here in the bmcweb
1005             // implementation and has nothing to do with the client's
1006             // input in the request. Hence, returning internal error
1007             // back to the client.
1008             messages::internalError(asyncResp->res);
1009             return;
1010         }
1011         BMCWEB_LOG_DEBUG << "Dump Created. Path: " << objPath.str;
1012         createDumpTaskCallback(std::move(payload), asyncResp, objPath);
1013         },
1014         "xyz.openbmc_project.Dump.Manager",
1015         "/xyz/openbmc_project/dump/" +
1016             std::string(boost::algorithm::to_lower_copy(dumpType)),
1017         "xyz.openbmc_project.Dump.Create", "CreateDump", createDumpParamVec);
1018 }
1019 
1020 inline void clearDump(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1021                       const std::string& dumpType)
1022 {
1023     std::string dumpTypeLowerCopy =
1024         std::string(boost::algorithm::to_lower_copy(dumpType));
1025 
1026     crow::connections::systemBus->async_method_call(
1027         [asyncResp](const boost::system::error_code& ec) {
1028         if (ec)
1029         {
1030             BMCWEB_LOG_ERROR << "clearDump resp_handler got error " << ec;
1031             messages::internalError(asyncResp->res);
1032             return;
1033         }
1034         },
1035         "xyz.openbmc_project.Dump.Manager",
1036         "/xyz/openbmc_project/dump/" + dumpTypeLowerCopy,
1037         "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
1038 }
1039 
1040 inline static void
1041     parseCrashdumpParameters(const dbus::utility::DBusPropertiesMap& params,
1042                              std::string& filename, std::string& timestamp,
1043                              std::string& logfile)
1044 {
1045     const std::string* filenamePtr = nullptr;
1046     const std::string* timestampPtr = nullptr;
1047     const std::string* logfilePtr = nullptr;
1048 
1049     const bool success = sdbusplus::unpackPropertiesNoThrow(
1050         dbus_utils::UnpackErrorPrinter(), params, "Timestamp", timestampPtr,
1051         "Filename", filenamePtr, "Log", logfilePtr);
1052 
1053     if (!success)
1054     {
1055         return;
1056     }
1057 
1058     if (filenamePtr != nullptr)
1059     {
1060         filename = *filenamePtr;
1061     }
1062 
1063     if (timestampPtr != nullptr)
1064     {
1065         timestamp = *timestampPtr;
1066     }
1067 
1068     if (logfilePtr != nullptr)
1069     {
1070         logfile = *logfilePtr;
1071     }
1072 }
1073 
1074 inline void requestRoutesSystemLogServiceCollection(App& app)
1075 {
1076     /**
1077      * Functions triggers appropriate requests on DBus
1078      */
1079     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/")
1080         .privileges(redfish::privileges::getLogServiceCollection)
1081         .methods(boost::beast::http::verb::get)(
1082             [&app](const crow::Request& req,
1083                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1084                    const std::string& systemName) {
1085         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1086         {
1087             return;
1088         }
1089         if (systemName != "system")
1090         {
1091             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1092                                        systemName);
1093             return;
1094         }
1095 
1096         // Collections don't include the static data added by SubRoute
1097         // because it has a duplicate entry for members
1098         asyncResp->res.jsonValue["@odata.type"] =
1099             "#LogServiceCollection.LogServiceCollection";
1100         asyncResp->res.jsonValue["@odata.id"] =
1101             "/redfish/v1/Systems/system/LogServices";
1102         asyncResp->res.jsonValue["Name"] = "System Log Services Collection";
1103         asyncResp->res.jsonValue["Description"] =
1104             "Collection of LogServices for this Computer System";
1105         nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
1106         logServiceArray = nlohmann::json::array();
1107         nlohmann::json::object_t eventLog;
1108         eventLog["@odata.id"] =
1109             "/redfish/v1/Systems/system/LogServices/EventLog";
1110         logServiceArray.emplace_back(std::move(eventLog));
1111 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
1112         nlohmann::json::object_t dumpLog;
1113         dumpLog["@odata.id"] = "/redfish/v1/Systems/system/LogServices/Dump";
1114         logServiceArray.emplace_back(std::move(dumpLog));
1115 #endif
1116 
1117 #ifdef BMCWEB_ENABLE_REDFISH_CPU_LOG
1118         nlohmann::json::object_t crashdump;
1119         crashdump["@odata.id"] =
1120             "/redfish/v1/Systems/system/LogServices/Crashdump";
1121         logServiceArray.emplace_back(std::move(crashdump));
1122 #endif
1123 
1124 #ifdef BMCWEB_ENABLE_REDFISH_HOST_LOGGER
1125         nlohmann::json::object_t hostlogger;
1126         hostlogger["@odata.id"] =
1127             "/redfish/v1/Systems/system/LogServices/HostLogger";
1128         logServiceArray.emplace_back(std::move(hostlogger));
1129 #endif
1130         asyncResp->res.jsonValue["Members@odata.count"] =
1131             logServiceArray.size();
1132 
1133         constexpr std::array<std::string_view, 1> interfaces = {
1134             "xyz.openbmc_project.State.Boot.PostCode"};
1135         dbus::utility::getSubTreePaths(
1136             "/", 0, interfaces,
1137             [asyncResp](const boost::system::error_code& ec,
1138                         const dbus::utility::MapperGetSubTreePathsResponse&
1139                             subtreePath) {
1140             if (ec)
1141             {
1142                 BMCWEB_LOG_ERROR << ec;
1143                 return;
1144             }
1145 
1146             for (const auto& pathStr : subtreePath)
1147             {
1148                 if (pathStr.find("PostCode") != std::string::npos)
1149                 {
1150                     nlohmann::json& logServiceArrayLocal =
1151                         asyncResp->res.jsonValue["Members"];
1152                     nlohmann::json::object_t member;
1153                     member["@odata.id"] =
1154                         "/redfish/v1/Systems/system/LogServices/PostCodes";
1155 
1156                     logServiceArrayLocal.emplace_back(std::move(member));
1157 
1158                     asyncResp->res.jsonValue["Members@odata.count"] =
1159                         logServiceArrayLocal.size();
1160                     return;
1161                 }
1162             }
1163             });
1164         });
1165 }
1166 
1167 inline void requestRoutesEventLogService(App& app)
1168 {
1169     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/")
1170         .privileges(redfish::privileges::getLogService)
1171         .methods(boost::beast::http::verb::get)(
1172             [&app](const crow::Request& req,
1173                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1174                    const std::string& systemName) {
1175         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1176         {
1177             return;
1178         }
1179         if (systemName != "system")
1180         {
1181             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1182                                        systemName);
1183             return;
1184         }
1185         asyncResp->res.jsonValue["@odata.id"] =
1186             "/redfish/v1/Systems/system/LogServices/EventLog";
1187         asyncResp->res.jsonValue["@odata.type"] =
1188             "#LogService.v1_1_0.LogService";
1189         asyncResp->res.jsonValue["Name"] = "Event Log Service";
1190         asyncResp->res.jsonValue["Description"] = "System Event Log Service";
1191         asyncResp->res.jsonValue["Id"] = "EventLog";
1192         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
1193 
1194         std::pair<std::string, std::string> redfishDateTimeOffset =
1195             redfish::time_utils::getDateTimeOffsetNow();
1196 
1197         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
1198         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
1199             redfishDateTimeOffset.second;
1200 
1201         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
1202             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1203         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
1204 
1205             {"target",
1206              "/redfish/v1/Systems/system/LogServices/EventLog/Actions/LogService.ClearLog"}};
1207         });
1208 }
1209 
1210 inline void requestRoutesJournalEventLogClear(App& app)
1211 {
1212     BMCWEB_ROUTE(
1213         app,
1214         "/redfish/v1/Systems/<str>/LogServices/EventLog/Actions/LogService.ClearLog/")
1215         .privileges({{"ConfigureComponents"}})
1216         .methods(boost::beast::http::verb::post)(
1217             [&app](const crow::Request& req,
1218                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1219                    const std::string& systemName) {
1220         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1221         {
1222             return;
1223         }
1224         if (systemName != "system")
1225         {
1226             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1227                                        systemName);
1228             return;
1229         }
1230         // Clear the EventLog by deleting the log files
1231         std::vector<std::filesystem::path> redfishLogFiles;
1232         if (getRedfishLogFiles(redfishLogFiles))
1233         {
1234             for (const std::filesystem::path& file : redfishLogFiles)
1235             {
1236                 std::error_code ec;
1237                 std::filesystem::remove(file, ec);
1238             }
1239         }
1240 
1241         // Reload rsyslog so it knows to start new log files
1242         crow::connections::systemBus->async_method_call(
1243             [asyncResp](const boost::system::error_code& ec) {
1244             if (ec)
1245             {
1246                 BMCWEB_LOG_ERROR << "Failed to reload rsyslog: " << ec;
1247                 messages::internalError(asyncResp->res);
1248                 return;
1249             }
1250 
1251             messages::success(asyncResp->res);
1252             },
1253             "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
1254             "org.freedesktop.systemd1.Manager", "ReloadUnit", "rsyslog.service",
1255             "replace");
1256         });
1257 }
1258 
1259 enum class LogParseError
1260 {
1261     success,
1262     parseFailed,
1263     messageIdNotInRegistry,
1264 };
1265 
1266 static LogParseError
1267     fillEventLogEntryJson(const std::string& logEntryID,
1268                           const std::string& logEntry,
1269                           nlohmann::json::object_t& logEntryJson)
1270 {
1271     // The redfish log format is "<Timestamp> <MessageId>,<MessageArgs>"
1272     // First get the Timestamp
1273     size_t space = logEntry.find_first_of(' ');
1274     if (space == std::string::npos)
1275     {
1276         return LogParseError::parseFailed;
1277     }
1278     std::string timestamp = logEntry.substr(0, space);
1279     // Then get the log contents
1280     size_t entryStart = logEntry.find_first_not_of(' ', space);
1281     if (entryStart == std::string::npos)
1282     {
1283         return LogParseError::parseFailed;
1284     }
1285     std::string_view entry(logEntry);
1286     entry.remove_prefix(entryStart);
1287     // Use split to separate the entry into its fields
1288     std::vector<std::string> logEntryFields;
1289     bmcweb::split(logEntryFields, entry, ',');
1290     // We need at least a MessageId to be valid
1291     if (logEntryFields.empty())
1292     {
1293         return LogParseError::parseFailed;
1294     }
1295     std::string& messageID = logEntryFields[0];
1296 
1297     // Get the Message from the MessageRegistry
1298     const registries::Message* message = registries::getMessage(messageID);
1299 
1300     if (message == nullptr)
1301     {
1302         BMCWEB_LOG_WARNING << "Log entry not found in registry: " << logEntry;
1303         return LogParseError::messageIdNotInRegistry;
1304     }
1305 
1306     std::string msg = message->message;
1307 
1308     // Get the MessageArgs from the log if there are any
1309     std::span<std::string> messageArgs;
1310     if (logEntryFields.size() > 1)
1311     {
1312         std::string& messageArgsStart = logEntryFields[1];
1313         // If the first string is empty, assume there are no MessageArgs
1314         std::size_t messageArgsSize = 0;
1315         if (!messageArgsStart.empty())
1316         {
1317             messageArgsSize = logEntryFields.size() - 1;
1318         }
1319 
1320         messageArgs = {&messageArgsStart, messageArgsSize};
1321 
1322         // Fill the MessageArgs into the Message
1323         int i = 0;
1324         for (const std::string& messageArg : messageArgs)
1325         {
1326             std::string argStr = "%" + std::to_string(++i);
1327             size_t argPos = msg.find(argStr);
1328             if (argPos != std::string::npos)
1329             {
1330                 msg.replace(argPos, argStr.length(), messageArg);
1331             }
1332         }
1333     }
1334 
1335     // Get the Created time from the timestamp. The log timestamp is in RFC3339
1336     // format which matches the Redfish format except for the fractional seconds
1337     // between the '.' and the '+', so just remove them.
1338     std::size_t dot = timestamp.find_first_of('.');
1339     std::size_t plus = timestamp.find_first_of('+');
1340     if (dot != std::string::npos && plus != std::string::npos)
1341     {
1342         timestamp.erase(dot, plus - dot);
1343     }
1344 
1345     // Fill in the log entry with the gathered data
1346     logEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
1347     logEntryJson["@odata.id"] = boost::urls::format(
1348         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/{}",
1349         logEntryID);
1350     logEntryJson["Name"] = "System Event Log Entry";
1351     logEntryJson["Id"] = logEntryID;
1352     logEntryJson["Message"] = std::move(msg);
1353     logEntryJson["MessageId"] = std::move(messageID);
1354     logEntryJson["MessageArgs"] = messageArgs;
1355     logEntryJson["EntryType"] = "Event";
1356     logEntryJson["Severity"] = message->messageSeverity;
1357     logEntryJson["Created"] = std::move(timestamp);
1358     return LogParseError::success;
1359 }
1360 
1361 inline void requestRoutesJournalEventLogEntryCollection(App& app)
1362 {
1363     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/")
1364         .privileges(redfish::privileges::getLogEntryCollection)
1365         .methods(boost::beast::http::verb::get)(
1366             [&app](const crow::Request& req,
1367                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1368                    const std::string& systemName) {
1369         query_param::QueryCapabilities capabilities = {
1370             .canDelegateTop = true,
1371             .canDelegateSkip = true,
1372         };
1373         query_param::Query delegatedQuery;
1374         if (!redfish::setUpRedfishRouteWithDelegation(
1375                 app, req, asyncResp, delegatedQuery, capabilities))
1376         {
1377             return;
1378         }
1379         if (systemName != "system")
1380         {
1381             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1382                                        systemName);
1383             return;
1384         }
1385 
1386         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
1387         size_t skip = delegatedQuery.skip.value_or(0);
1388 
1389         // Collections don't include the static data added by SubRoute
1390         // because it has a duplicate entry for members
1391         asyncResp->res.jsonValue["@odata.type"] =
1392             "#LogEntryCollection.LogEntryCollection";
1393         asyncResp->res.jsonValue["@odata.id"] =
1394             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1395         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1396         asyncResp->res.jsonValue["Description"] =
1397             "Collection of System Event Log Entries";
1398 
1399         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
1400         logEntryArray = nlohmann::json::array();
1401         // Go through the log files and create a unique ID for each
1402         // entry
1403         std::vector<std::filesystem::path> redfishLogFiles;
1404         getRedfishLogFiles(redfishLogFiles);
1405         uint64_t entryCount = 0;
1406         std::string logEntry;
1407 
1408         // Oldest logs are in the last file, so start there and loop
1409         // backwards
1410         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1411              it++)
1412         {
1413             std::ifstream logStream(*it);
1414             if (!logStream.is_open())
1415             {
1416                 continue;
1417             }
1418 
1419             // Reset the unique ID on the first entry
1420             bool firstEntry = true;
1421             while (std::getline(logStream, logEntry))
1422             {
1423                 std::string idStr;
1424                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1425                 {
1426                     continue;
1427                 }
1428                 firstEntry = false;
1429 
1430                 nlohmann::json::object_t bmcLogEntry;
1431                 LogParseError status = fillEventLogEntryJson(idStr, logEntry,
1432                                                              bmcLogEntry);
1433                 if (status == LogParseError::messageIdNotInRegistry)
1434                 {
1435                     continue;
1436                 }
1437                 if (status != LogParseError::success)
1438                 {
1439                     messages::internalError(asyncResp->res);
1440                     return;
1441                 }
1442 
1443                 entryCount++;
1444                 // Handle paging using skip (number of entries to skip from the
1445                 // start) and top (number of entries to display)
1446                 if (entryCount <= skip || entryCount > skip + top)
1447                 {
1448                     continue;
1449                 }
1450 
1451                 logEntryArray.emplace_back(std::move(bmcLogEntry));
1452             }
1453         }
1454         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
1455         if (skip + top < entryCount)
1456         {
1457             asyncResp->res.jsonValue["Members@odata.nextLink"] =
1458                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries?$skip=" +
1459                 std::to_string(skip + top);
1460         }
1461         });
1462 }
1463 
1464 inline void requestRoutesJournalEventLogEntry(App& app)
1465 {
1466     BMCWEB_ROUTE(
1467         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1468         .privileges(redfish::privileges::getLogEntry)
1469         .methods(boost::beast::http::verb::get)(
1470             [&app](const crow::Request& req,
1471                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1472                    const std::string& systemName, const std::string& param) {
1473         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1474         {
1475             return;
1476         }
1477 
1478         if (systemName != "system")
1479         {
1480             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1481                                        systemName);
1482             return;
1483         }
1484 
1485         const std::string& targetID = param;
1486 
1487         // Go through the log files and check the unique ID for each
1488         // entry to find the target entry
1489         std::vector<std::filesystem::path> redfishLogFiles;
1490         getRedfishLogFiles(redfishLogFiles);
1491         std::string logEntry;
1492 
1493         // Oldest logs are in the last file, so start there and loop
1494         // backwards
1495         for (auto it = redfishLogFiles.rbegin(); it < redfishLogFiles.rend();
1496              it++)
1497         {
1498             std::ifstream logStream(*it);
1499             if (!logStream.is_open())
1500             {
1501                 continue;
1502             }
1503 
1504             // Reset the unique ID on the first entry
1505             bool firstEntry = true;
1506             while (std::getline(logStream, logEntry))
1507             {
1508                 std::string idStr;
1509                 if (!getUniqueEntryID(logEntry, idStr, firstEntry))
1510                 {
1511                     continue;
1512                 }
1513                 firstEntry = false;
1514 
1515                 if (idStr == targetID)
1516                 {
1517                     nlohmann::json::object_t bmcLogEntry;
1518                     LogParseError status =
1519                         fillEventLogEntryJson(idStr, logEntry, bmcLogEntry);
1520                     if (status != LogParseError::success)
1521                     {
1522                         messages::internalError(asyncResp->res);
1523                         return;
1524                     }
1525                     asyncResp->res.jsonValue.update(bmcLogEntry);
1526                     return;
1527                 }
1528             }
1529         }
1530         // Requested ID was not found
1531         messages::resourceNotFound(asyncResp->res, "LogEntry", targetID);
1532         });
1533 }
1534 
1535 inline void requestRoutesDBusEventLogEntryCollection(App& app)
1536 {
1537     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/")
1538         .privileges(redfish::privileges::getLogEntryCollection)
1539         .methods(boost::beast::http::verb::get)(
1540             [&app](const crow::Request& req,
1541                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1542                    const std::string& systemName) {
1543         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1544         {
1545             return;
1546         }
1547         if (systemName != "system")
1548         {
1549             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1550                                        systemName);
1551             return;
1552         }
1553 
1554         // Collections don't include the static data added by SubRoute
1555         // because it has a duplicate entry for members
1556         asyncResp->res.jsonValue["@odata.type"] =
1557             "#LogEntryCollection.LogEntryCollection";
1558         asyncResp->res.jsonValue["@odata.id"] =
1559             "/redfish/v1/Systems/system/LogServices/EventLog/Entries";
1560         asyncResp->res.jsonValue["Name"] = "System Event Log Entries";
1561         asyncResp->res.jsonValue["Description"] =
1562             "Collection of System Event Log Entries";
1563 
1564         // DBus implementation of EventLog/Entries
1565         // Make call to Logging Service to find all log entry objects
1566         crow::connections::systemBus->async_method_call(
1567             [asyncResp](const boost::system::error_code& ec,
1568                         const dbus::utility::ManagedObjectType& resp) {
1569             if (ec)
1570             {
1571                 // TODO Handle for specific error code
1572                 BMCWEB_LOG_ERROR
1573                     << "getLogEntriesIfaceData resp_handler got error " << ec;
1574                 messages::internalError(asyncResp->res);
1575                 return;
1576             }
1577             nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
1578             entriesArray = nlohmann::json::array();
1579             for (const auto& objectPath : resp)
1580             {
1581                 const uint32_t* id = nullptr;
1582                 const uint64_t* timestamp = nullptr;
1583                 const uint64_t* updateTimestamp = nullptr;
1584                 const std::string* severity = nullptr;
1585                 const std::string* message = nullptr;
1586                 const std::string* filePath = nullptr;
1587                 const std::string* resolution = nullptr;
1588                 bool resolved = false;
1589                 const std::string* notify = nullptr;
1590 
1591                 for (const auto& interfaceMap : objectPath.second)
1592                 {
1593                     if (interfaceMap.first ==
1594                         "xyz.openbmc_project.Logging.Entry")
1595                     {
1596                         for (const auto& propertyMap : interfaceMap.second)
1597                         {
1598                             if (propertyMap.first == "Id")
1599                             {
1600                                 id = std::get_if<uint32_t>(&propertyMap.second);
1601                             }
1602                             else if (propertyMap.first == "Timestamp")
1603                             {
1604                                 timestamp =
1605                                     std::get_if<uint64_t>(&propertyMap.second);
1606                             }
1607                             else if (propertyMap.first == "UpdateTimestamp")
1608                             {
1609                                 updateTimestamp =
1610                                     std::get_if<uint64_t>(&propertyMap.second);
1611                             }
1612                             else if (propertyMap.first == "Severity")
1613                             {
1614                                 severity = std::get_if<std::string>(
1615                                     &propertyMap.second);
1616                             }
1617                             else if (propertyMap.first == "Resolution")
1618                             {
1619                                 resolution = std::get_if<std::string>(
1620                                     &propertyMap.second);
1621                             }
1622                             else if (propertyMap.first == "Message")
1623                             {
1624                                 message = std::get_if<std::string>(
1625                                     &propertyMap.second);
1626                             }
1627                             else if (propertyMap.first == "Resolved")
1628                             {
1629                                 const bool* resolveptr =
1630                                     std::get_if<bool>(&propertyMap.second);
1631                                 if (resolveptr == nullptr)
1632                                 {
1633                                     messages::internalError(asyncResp->res);
1634                                     return;
1635                                 }
1636                                 resolved = *resolveptr;
1637                             }
1638                             else if (propertyMap.first ==
1639                                      "ServiceProviderNotify")
1640                             {
1641                                 notify = std::get_if<std::string>(
1642                                     &propertyMap.second);
1643                                 if (notify == nullptr)
1644                                 {
1645                                     messages::internalError(asyncResp->res);
1646                                     return;
1647                                 }
1648                             }
1649                         }
1650                         if (id == nullptr || message == nullptr ||
1651                             severity == nullptr)
1652                         {
1653                             messages::internalError(asyncResp->res);
1654                             return;
1655                         }
1656                     }
1657                     else if (interfaceMap.first ==
1658                              "xyz.openbmc_project.Common.FilePath")
1659                     {
1660                         for (const auto& propertyMap : interfaceMap.second)
1661                         {
1662                             if (propertyMap.first == "Path")
1663                             {
1664                                 filePath = std::get_if<std::string>(
1665                                     &propertyMap.second);
1666                             }
1667                         }
1668                     }
1669                 }
1670                 // Object path without the
1671                 // xyz.openbmc_project.Logging.Entry interface, ignore
1672                 // and continue.
1673                 if (id == nullptr || message == nullptr ||
1674                     severity == nullptr || timestamp == nullptr ||
1675                     updateTimestamp == nullptr)
1676                 {
1677                     continue;
1678                 }
1679                 entriesArray.push_back({});
1680                 nlohmann::json& thisEntry = entriesArray.back();
1681                 thisEntry["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
1682                 thisEntry["@odata.id"] = boost::urls::format(
1683                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries/{}",
1684                     std::to_string(*id));
1685                 thisEntry["Name"] = "System Event Log Entry";
1686                 thisEntry["Id"] = std::to_string(*id);
1687                 thisEntry["Message"] = *message;
1688                 thisEntry["Resolved"] = resolved;
1689                 if ((resolution != nullptr) && (!(*resolution).empty()))
1690                 {
1691                     thisEntry["Resolution"] = *resolution;
1692                 }
1693                 std::optional<bool> notifyAction =
1694                     getProviderNotifyAction(*notify);
1695                 if (notifyAction)
1696                 {
1697                     thisEntry["ServiceProviderNotified"] = *notifyAction;
1698                 }
1699                 thisEntry["EntryType"] = "Event";
1700                 thisEntry["Severity"] =
1701                     translateSeverityDbusToRedfish(*severity);
1702                 thisEntry["Created"] =
1703                     redfish::time_utils::getDateTimeUintMs(*timestamp);
1704                 thisEntry["Modified"] =
1705                     redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1706                 if (filePath != nullptr)
1707                 {
1708                     thisEntry["AdditionalDataURI"] =
1709                         "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1710                         std::to_string(*id) + "/attachment";
1711                 }
1712             }
1713             std::sort(
1714                 entriesArray.begin(), entriesArray.end(),
1715                 [](const nlohmann::json& left, const nlohmann::json& right) {
1716                 return (left["Id"] <= right["Id"]);
1717                 });
1718             asyncResp->res.jsonValue["Members@odata.count"] =
1719                 entriesArray.size();
1720             },
1721             "xyz.openbmc_project.Logging", "/xyz/openbmc_project/logging",
1722             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1723         });
1724 }
1725 
1726 inline void requestRoutesDBusEventLogEntry(App& app)
1727 {
1728     BMCWEB_ROUTE(
1729         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1730         .privileges(redfish::privileges::getLogEntry)
1731         .methods(boost::beast::http::verb::get)(
1732             [&app](const crow::Request& req,
1733                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1734                    const std::string& systemName, const std::string& param) {
1735         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1736         {
1737             return;
1738         }
1739         if (systemName != "system")
1740         {
1741             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1742                                        systemName);
1743             return;
1744         }
1745 
1746         std::string entryID = param;
1747         dbus::utility::escapePathForDbus(entryID);
1748 
1749         // DBus implementation of EventLog/Entries
1750         // Make call to Logging Service to find all log entry objects
1751         sdbusplus::asio::getAllProperties(
1752             *crow::connections::systemBus, "xyz.openbmc_project.Logging",
1753             "/xyz/openbmc_project/logging/entry/" + entryID, "",
1754             [asyncResp, entryID](const boost::system::error_code& ec,
1755                                  const dbus::utility::DBusPropertiesMap& resp) {
1756             if (ec.value() == EBADR)
1757             {
1758                 messages::resourceNotFound(asyncResp->res, "EventLogEntry",
1759                                            entryID);
1760                 return;
1761             }
1762             if (ec)
1763             {
1764                 BMCWEB_LOG_ERROR
1765                     << "EventLogEntry (DBus) resp_handler got error " << ec;
1766                 messages::internalError(asyncResp->res);
1767                 return;
1768             }
1769             const uint32_t* id = nullptr;
1770             const uint64_t* timestamp = nullptr;
1771             const uint64_t* updateTimestamp = nullptr;
1772             const std::string* severity = nullptr;
1773             const std::string* message = nullptr;
1774             const std::string* filePath = nullptr;
1775             const std::string* resolution = nullptr;
1776             bool resolved = false;
1777             const std::string* notify = nullptr;
1778 
1779             const bool success = sdbusplus::unpackPropertiesNoThrow(
1780                 dbus_utils::UnpackErrorPrinter(), resp, "Id", id, "Timestamp",
1781                 timestamp, "UpdateTimestamp", updateTimestamp, "Severity",
1782                 severity, "Message", message, "Resolved", resolved,
1783                 "Resolution", resolution, "Path", filePath,
1784                 "ServiceProviderNotify", notify);
1785 
1786             if (!success)
1787             {
1788                 messages::internalError(asyncResp->res);
1789                 return;
1790             }
1791 
1792             if (id == nullptr || message == nullptr || severity == nullptr ||
1793                 timestamp == nullptr || updateTimestamp == nullptr ||
1794                 notify == nullptr)
1795             {
1796                 messages::internalError(asyncResp->res);
1797                 return;
1798             }
1799 
1800             asyncResp->res.jsonValue["@odata.type"] =
1801                 "#LogEntry.v1_9_0.LogEntry";
1802             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
1803                 "/redfish/v1/Systems/system/LogServices/EventLog/Entries/{}",
1804                 std::to_string(*id));
1805             asyncResp->res.jsonValue["Name"] = "System Event Log Entry";
1806             asyncResp->res.jsonValue["Id"] = std::to_string(*id);
1807             asyncResp->res.jsonValue["Message"] = *message;
1808             asyncResp->res.jsonValue["Resolved"] = resolved;
1809             std::optional<bool> notifyAction = getProviderNotifyAction(*notify);
1810             if (notifyAction)
1811             {
1812                 asyncResp->res.jsonValue["ServiceProviderNotified"] =
1813                     *notifyAction;
1814             }
1815             if ((resolution != nullptr) && (!(*resolution).empty()))
1816             {
1817                 asyncResp->res.jsonValue["Resolution"] = *resolution;
1818             }
1819             asyncResp->res.jsonValue["EntryType"] = "Event";
1820             asyncResp->res.jsonValue["Severity"] =
1821                 translateSeverityDbusToRedfish(*severity);
1822             asyncResp->res.jsonValue["Created"] =
1823                 redfish::time_utils::getDateTimeUintMs(*timestamp);
1824             asyncResp->res.jsonValue["Modified"] =
1825                 redfish::time_utils::getDateTimeUintMs(*updateTimestamp);
1826             if (filePath != nullptr)
1827             {
1828                 asyncResp->res.jsonValue["AdditionalDataURI"] =
1829                     "/redfish/v1/Systems/system/LogServices/EventLog/Entries/" +
1830                     std::to_string(*id) + "/attachment";
1831             }
1832             });
1833         });
1834 
1835     BMCWEB_ROUTE(
1836         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1837         .privileges(redfish::privileges::patchLogEntry)
1838         .methods(boost::beast::http::verb::patch)(
1839             [&app](const crow::Request& req,
1840                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1841                    const std::string& systemName, const std::string& entryId) {
1842         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1843         {
1844             return;
1845         }
1846         if (systemName != "system")
1847         {
1848             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1849                                        systemName);
1850             return;
1851         }
1852         std::optional<bool> resolved;
1853 
1854         if (!json_util::readJsonPatch(req, asyncResp->res, "Resolved",
1855                                       resolved))
1856         {
1857             return;
1858         }
1859         BMCWEB_LOG_DEBUG << "Set Resolved";
1860 
1861         crow::connections::systemBus->async_method_call(
1862             [asyncResp, entryId](const boost::system::error_code& ec) {
1863             if (ec)
1864             {
1865                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1866                 messages::internalError(asyncResp->res);
1867                 return;
1868             }
1869             },
1870             "xyz.openbmc_project.Logging",
1871             "/xyz/openbmc_project/logging/entry/" + entryId,
1872             "org.freedesktop.DBus.Properties", "Set",
1873             "xyz.openbmc_project.Logging.Entry", "Resolved",
1874             dbus::utility::DbusVariantType(*resolved));
1875         });
1876 
1877     BMCWEB_ROUTE(
1878         app, "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/")
1879         .privileges(redfish::privileges::deleteLogEntry)
1880 
1881         .methods(boost::beast::http::verb::delete_)(
1882             [&app](const crow::Request& req,
1883                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1884                    const std::string& systemName, const std::string& param) {
1885         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1886         {
1887             return;
1888         }
1889         if (systemName != "system")
1890         {
1891             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1892                                        systemName);
1893             return;
1894         }
1895         BMCWEB_LOG_DEBUG << "Do delete single event entries.";
1896 
1897         std::string entryID = param;
1898 
1899         dbus::utility::escapePathForDbus(entryID);
1900 
1901         // Process response from Logging service.
1902         auto respHandler =
1903             [asyncResp, entryID](const boost::system::error_code& ec) {
1904             BMCWEB_LOG_DEBUG << "EventLogEntry (DBus) doDelete callback: Done";
1905             if (ec)
1906             {
1907                 if (ec.value() == EBADR)
1908                 {
1909                     messages::resourceNotFound(asyncResp->res, "LogEntry",
1910                                                entryID);
1911                     return;
1912                 }
1913                 // TODO Handle for specific error code
1914                 BMCWEB_LOG_ERROR
1915                     << "EventLogEntry (DBus) doDelete respHandler got error "
1916                     << ec;
1917                 asyncResp->res.result(
1918                     boost::beast::http::status::internal_server_error);
1919                 return;
1920             }
1921 
1922             asyncResp->res.result(boost::beast::http::status::ok);
1923         };
1924 
1925         // Make call to Logging service to request Delete Log
1926         crow::connections::systemBus->async_method_call(
1927             respHandler, "xyz.openbmc_project.Logging",
1928             "/xyz/openbmc_project/logging/entry/" + entryID,
1929             "xyz.openbmc_project.Object.Delete", "Delete");
1930         });
1931 }
1932 
1933 inline void requestRoutesDBusEventLogEntryDownload(App& app)
1934 {
1935     BMCWEB_ROUTE(
1936         app,
1937         "/redfish/v1/Systems/<str>/LogServices/EventLog/Entries/<str>/attachment")
1938         .privileges(redfish::privileges::getLogEntry)
1939         .methods(boost::beast::http::verb::get)(
1940             [&app](const crow::Request& req,
1941                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1942                    const std::string& systemName, const std::string& param) {
1943         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
1944         {
1945             return;
1946         }
1947         if (!http_helpers::isContentTypeAllowed(
1948                 req.getHeaderValue("Accept"),
1949                 http_helpers::ContentType::OctetStream, true))
1950         {
1951             asyncResp->res.result(boost::beast::http::status::bad_request);
1952             return;
1953         }
1954         if (systemName != "system")
1955         {
1956             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
1957                                        systemName);
1958             return;
1959         }
1960 
1961         std::string entryID = param;
1962         dbus::utility::escapePathForDbus(entryID);
1963 
1964         crow::connections::systemBus->async_method_call(
1965             [asyncResp, entryID](const boost::system::error_code& ec,
1966                                  const sdbusplus::message::unix_fd& unixfd) {
1967             if (ec.value() == EBADR)
1968             {
1969                 messages::resourceNotFound(asyncResp->res, "EventLogAttachment",
1970                                            entryID);
1971                 return;
1972             }
1973             if (ec)
1974             {
1975                 BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
1976                 messages::internalError(asyncResp->res);
1977                 return;
1978             }
1979 
1980             int fd = -1;
1981             fd = dup(unixfd);
1982             if (fd == -1)
1983             {
1984                 messages::internalError(asyncResp->res);
1985                 return;
1986             }
1987 
1988             long long int size = lseek(fd, 0, SEEK_END);
1989             if (size == -1)
1990             {
1991                 messages::internalError(asyncResp->res);
1992                 return;
1993             }
1994 
1995             // Arbitrary max size of 64kb
1996             constexpr int maxFileSize = 65536;
1997             if (size > maxFileSize)
1998             {
1999                 BMCWEB_LOG_ERROR << "File size exceeds maximum allowed size of "
2000                                  << maxFileSize;
2001                 messages::internalError(asyncResp->res);
2002                 return;
2003             }
2004             std::vector<char> data(static_cast<size_t>(size));
2005             long long int rc = lseek(fd, 0, SEEK_SET);
2006             if (rc == -1)
2007             {
2008                 messages::internalError(asyncResp->res);
2009                 return;
2010             }
2011             rc = read(fd, data.data(), data.size());
2012             if ((rc == -1) || (rc != size))
2013             {
2014                 messages::internalError(asyncResp->res);
2015                 return;
2016             }
2017             close(fd);
2018 
2019             std::string_view strData(data.data(), data.size());
2020             std::string output = crow::utility::base64encode(strData);
2021 
2022             asyncResp->res.addHeader(boost::beast::http::field::content_type,
2023                                      "application/octet-stream");
2024             asyncResp->res.addHeader(
2025                 boost::beast::http::field::content_transfer_encoding, "Base64");
2026             asyncResp->res.body() = std::move(output);
2027             },
2028             "xyz.openbmc_project.Logging",
2029             "/xyz/openbmc_project/logging/entry/" + entryID,
2030             "xyz.openbmc_project.Logging.Entry", "GetEntry");
2031         });
2032 }
2033 
2034 constexpr const char* hostLoggerFolderPath = "/var/log/console";
2035 
2036 inline bool
2037     getHostLoggerFiles(const std::string& hostLoggerFilePath,
2038                        std::vector<std::filesystem::path>& hostLoggerFiles)
2039 {
2040     std::error_code ec;
2041     std::filesystem::directory_iterator logPath(hostLoggerFilePath, ec);
2042     if (ec)
2043     {
2044         BMCWEB_LOG_ERROR << ec.message();
2045         return false;
2046     }
2047     for (const std::filesystem::directory_entry& it : logPath)
2048     {
2049         std::string filename = it.path().filename();
2050         // Prefix of each log files is "log". Find the file and save the
2051         // path
2052         if (filename.starts_with("log"))
2053         {
2054             hostLoggerFiles.emplace_back(it.path());
2055         }
2056     }
2057     // As the log files rotate, they are appended with a ".#" that is higher for
2058     // the older logs. Since we start from oldest logs, sort the name in
2059     // descending order.
2060     std::sort(hostLoggerFiles.rbegin(), hostLoggerFiles.rend(),
2061               AlphanumLess<std::string>());
2062 
2063     return true;
2064 }
2065 
2066 inline bool getHostLoggerEntries(
2067     const std::vector<std::filesystem::path>& hostLoggerFiles, uint64_t skip,
2068     uint64_t top, std::vector<std::string>& logEntries, size_t& logCount)
2069 {
2070     GzFileReader logFile;
2071 
2072     // Go though all log files and expose host logs.
2073     for (const std::filesystem::path& it : hostLoggerFiles)
2074     {
2075         if (!logFile.gzGetLines(it.string(), skip, top, logEntries, logCount))
2076         {
2077             BMCWEB_LOG_ERROR << "fail to expose host logs";
2078             return false;
2079         }
2080     }
2081     // Get lastMessage from constructor by getter
2082     std::string lastMessage = logFile.getLastMessage();
2083     if (!lastMessage.empty())
2084     {
2085         logCount++;
2086         if (logCount > skip && logCount <= (skip + top))
2087         {
2088             logEntries.push_back(lastMessage);
2089         }
2090     }
2091     return true;
2092 }
2093 
2094 inline void fillHostLoggerEntryJson(const std::string& logEntryID,
2095                                     const std::string& msg,
2096                                     nlohmann::json::object_t& logEntryJson)
2097 {
2098     // Fill in the log entry with the gathered data.
2099     logEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
2100     logEntryJson["@odata.id"] = boost::urls::format(
2101         "/redfish/v1/Systems/system/LogServices/HostLogger/Entries/{}",
2102         logEntryID);
2103     logEntryJson["Name"] = "Host Logger Entry";
2104     logEntryJson["Id"] = logEntryID;
2105     logEntryJson["Message"] = msg;
2106     logEntryJson["EntryType"] = "Oem";
2107     logEntryJson["Severity"] = "OK";
2108     logEntryJson["OemRecordFormat"] = "Host Logger Entry";
2109 }
2110 
2111 inline void requestRoutesSystemHostLogger(App& app)
2112 {
2113     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/HostLogger/")
2114         .privileges(redfish::privileges::getLogService)
2115         .methods(boost::beast::http::verb::get)(
2116             [&app](const crow::Request& req,
2117                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2118                    const std::string& systemName) {
2119         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2120         {
2121             return;
2122         }
2123         if (systemName != "system")
2124         {
2125             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2126                                        systemName);
2127             return;
2128         }
2129         asyncResp->res.jsonValue["@odata.id"] =
2130             "/redfish/v1/Systems/system/LogServices/HostLogger";
2131         asyncResp->res.jsonValue["@odata.type"] =
2132             "#LogService.v1_1_0.LogService";
2133         asyncResp->res.jsonValue["Name"] = "Host Logger Service";
2134         asyncResp->res.jsonValue["Description"] = "Host Logger Service";
2135         asyncResp->res.jsonValue["Id"] = "HostLogger";
2136         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2137             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
2138         });
2139 }
2140 
2141 inline void requestRoutesSystemHostLoggerCollection(App& app)
2142 {
2143     BMCWEB_ROUTE(app,
2144                  "/redfish/v1/Systems/<str>/LogServices/HostLogger/Entries/")
2145         .privileges(redfish::privileges::getLogEntry)
2146         .methods(boost::beast::http::verb::get)(
2147             [&app](const crow::Request& req,
2148                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2149                    const std::string& systemName) {
2150         query_param::QueryCapabilities capabilities = {
2151             .canDelegateTop = true,
2152             .canDelegateSkip = true,
2153         };
2154         query_param::Query delegatedQuery;
2155         if (!redfish::setUpRedfishRouteWithDelegation(
2156                 app, req, asyncResp, delegatedQuery, capabilities))
2157         {
2158             return;
2159         }
2160         if (systemName != "system")
2161         {
2162             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2163                                        systemName);
2164             return;
2165         }
2166         asyncResp->res.jsonValue["@odata.id"] =
2167             "/redfish/v1/Systems/system/LogServices/HostLogger/Entries";
2168         asyncResp->res.jsonValue["@odata.type"] =
2169             "#LogEntryCollection.LogEntryCollection";
2170         asyncResp->res.jsonValue["Name"] = "HostLogger Entries";
2171         asyncResp->res.jsonValue["Description"] =
2172             "Collection of HostLogger Entries";
2173         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2174         logEntryArray = nlohmann::json::array();
2175         asyncResp->res.jsonValue["Members@odata.count"] = 0;
2176 
2177         std::vector<std::filesystem::path> hostLoggerFiles;
2178         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
2179         {
2180             BMCWEB_LOG_ERROR << "fail to get host log file path";
2181             return;
2182         }
2183         // If we weren't provided top and skip limits, use the defaults.
2184         size_t skip = delegatedQuery.skip.value_or(0);
2185         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
2186         size_t logCount = 0;
2187         // This vector only store the entries we want to expose that
2188         // control by skip and top.
2189         std::vector<std::string> logEntries;
2190         if (!getHostLoggerEntries(hostLoggerFiles, skip, top, logEntries,
2191                                   logCount))
2192         {
2193             messages::internalError(asyncResp->res);
2194             return;
2195         }
2196         // If vector is empty, that means skip value larger than total
2197         // log count
2198         if (logEntries.empty())
2199         {
2200             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
2201             return;
2202         }
2203         if (!logEntries.empty())
2204         {
2205             for (size_t i = 0; i < logEntries.size(); i++)
2206             {
2207                 nlohmann::json::object_t hostLogEntry;
2208                 fillHostLoggerEntryJson(std::to_string(skip + i), logEntries[i],
2209                                         hostLogEntry);
2210                 logEntryArray.emplace_back(std::move(hostLogEntry));
2211             }
2212 
2213             asyncResp->res.jsonValue["Members@odata.count"] = logCount;
2214             if (skip + top < logCount)
2215             {
2216                 asyncResp->res.jsonValue["Members@odata.nextLink"] =
2217                     "/redfish/v1/Systems/system/LogServices/HostLogger/Entries?$skip=" +
2218                     std::to_string(skip + top);
2219             }
2220         }
2221         });
2222 }
2223 
2224 inline void requestRoutesSystemHostLoggerLogEntry(App& app)
2225 {
2226     BMCWEB_ROUTE(
2227         app, "/redfish/v1/Systems/<str>/LogServices/HostLogger/Entries/<str>/")
2228         .privileges(redfish::privileges::getLogEntry)
2229         .methods(boost::beast::http::verb::get)(
2230             [&app](const crow::Request& req,
2231                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2232                    const std::string& systemName, const std::string& param) {
2233         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2234         {
2235             return;
2236         }
2237         if (systemName != "system")
2238         {
2239             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
2240                                        systemName);
2241             return;
2242         }
2243         const std::string& targetID = param;
2244 
2245         uint64_t idInt = 0;
2246 
2247         auto [ptr, ec] = std::from_chars(&*targetID.begin(), &*targetID.end(),
2248                                          idInt);
2249         if (ec == std::errc::invalid_argument ||
2250             ec == std::errc::result_out_of_range)
2251         {
2252             messages::resourceNotFound(asyncResp->res, "LogEntry", param);
2253             return;
2254         }
2255 
2256         std::vector<std::filesystem::path> hostLoggerFiles;
2257         if (!getHostLoggerFiles(hostLoggerFolderPath, hostLoggerFiles))
2258         {
2259             BMCWEB_LOG_ERROR << "fail to get host log file path";
2260             return;
2261         }
2262 
2263         size_t logCount = 0;
2264         size_t top = 1;
2265         std::vector<std::string> logEntries;
2266         // We can get specific entry by skip and top. For example, if we
2267         // want to get nth entry, we can set skip = n-1 and top = 1 to
2268         // get that entry
2269         if (!getHostLoggerEntries(hostLoggerFiles, idInt, top, logEntries,
2270                                   logCount))
2271         {
2272             messages::internalError(asyncResp->res);
2273             return;
2274         }
2275 
2276         if (!logEntries.empty())
2277         {
2278             nlohmann::json::object_t hostLogEntry;
2279             fillHostLoggerEntryJson(targetID, logEntries[0], hostLogEntry);
2280             asyncResp->res.jsonValue.update(hostLogEntry);
2281             return;
2282         }
2283 
2284         // Requested ID was not found
2285         messages::resourceNotFound(asyncResp->res, "LogEntry", param);
2286         });
2287 }
2288 
2289 inline void handleBMCLogServicesCollectionGet(
2290     crow::App& app, const crow::Request& req,
2291     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2292 {
2293     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2294     {
2295         return;
2296     }
2297     // Collections don't include the static data added by SubRoute
2298     // because it has a duplicate entry for members
2299     asyncResp->res.jsonValue["@odata.type"] =
2300         "#LogServiceCollection.LogServiceCollection";
2301     asyncResp->res.jsonValue["@odata.id"] =
2302         "/redfish/v1/Managers/bmc/LogServices";
2303     asyncResp->res.jsonValue["Name"] = "Open BMC Log Services Collection";
2304     asyncResp->res.jsonValue["Description"] =
2305         "Collection of LogServices for this Manager";
2306     nlohmann::json& logServiceArray = asyncResp->res.jsonValue["Members"];
2307     logServiceArray = nlohmann::json::array();
2308 
2309 #ifdef BMCWEB_ENABLE_REDFISH_BMC_JOURNAL
2310     nlohmann::json::object_t journal;
2311     journal["@odata.id"] = "/redfish/v1/Managers/bmc/LogServices/Journal";
2312     logServiceArray.emplace_back(std::move(journal));
2313 #endif
2314 
2315     asyncResp->res.jsonValue["Members@odata.count"] = logServiceArray.size();
2316 
2317 #ifdef BMCWEB_ENABLE_REDFISH_DUMP_LOG
2318     constexpr std::array<std::string_view, 1> interfaces = {
2319         "xyz.openbmc_project.Collection.DeleteAll"};
2320     dbus::utility::getSubTreePaths(
2321         "/xyz/openbmc_project/dump", 0, interfaces,
2322         [asyncResp](
2323             const boost::system::error_code& ec,
2324             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
2325         if (ec)
2326         {
2327             BMCWEB_LOG_ERROR
2328                 << "handleBMCLogServicesCollectionGet respHandler got error "
2329                 << ec;
2330             // Assume that getting an error simply means there are no dump
2331             // LogServices. Return without adding any error response.
2332             return;
2333         }
2334 
2335         nlohmann::json& logServiceArrayLocal =
2336             asyncResp->res.jsonValue["Members"];
2337 
2338         for (const std::string& path : subTreePaths)
2339         {
2340             if (path == "/xyz/openbmc_project/dump/bmc")
2341             {
2342                 nlohmann::json::object_t member;
2343                 member["@odata.id"] =
2344                     "/redfish/v1/Managers/bmc/LogServices/Dump";
2345                 logServiceArrayLocal.emplace_back(std::move(member));
2346             }
2347             else if (path == "/xyz/openbmc_project/dump/faultlog")
2348             {
2349                 nlohmann::json::object_t member;
2350                 member["@odata.id"] =
2351                     "/redfish/v1/Managers/bmc/LogServices/FaultLog";
2352                 logServiceArrayLocal.emplace_back(std::move(member));
2353             }
2354         }
2355 
2356         asyncResp->res.jsonValue["Members@odata.count"] =
2357             logServiceArrayLocal.size();
2358         });
2359 #endif
2360 }
2361 
2362 inline void requestRoutesBMCLogServiceCollection(App& app)
2363 {
2364     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/")
2365         .privileges(redfish::privileges::getLogServiceCollection)
2366         .methods(boost::beast::http::verb::get)(
2367             std::bind_front(handleBMCLogServicesCollectionGet, std::ref(app)));
2368 }
2369 
2370 inline void requestRoutesBMCJournalLogService(App& app)
2371 {
2372     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/")
2373         .privileges(redfish::privileges::getLogService)
2374         .methods(boost::beast::http::verb::get)(
2375             [&app](const crow::Request& req,
2376                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2377         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2378         {
2379             return;
2380         }
2381         asyncResp->res.jsonValue["@odata.type"] =
2382             "#LogService.v1_1_0.LogService";
2383         asyncResp->res.jsonValue["@odata.id"] =
2384             "/redfish/v1/Managers/bmc/LogServices/Journal";
2385         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Log Service";
2386         asyncResp->res.jsonValue["Description"] = "BMC Journal Log Service";
2387         asyncResp->res.jsonValue["Id"] = "Journal";
2388         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
2389 
2390         std::pair<std::string, std::string> redfishDateTimeOffset =
2391             redfish::time_utils::getDateTimeOffsetNow();
2392         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2393         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2394             redfishDateTimeOffset.second;
2395 
2396         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
2397             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2398         });
2399 }
2400 
2401 static int
2402     fillBMCJournalLogEntryJson(const std::string& bmcJournalLogEntryID,
2403                                sd_journal* journal,
2404                                nlohmann::json::object_t& bmcJournalLogEntryJson)
2405 {
2406     // Get the Log Entry contents
2407     int ret = 0;
2408 
2409     std::string message;
2410     std::string_view syslogID;
2411     ret = getJournalMetadata(journal, "SYSLOG_IDENTIFIER", syslogID);
2412     if (ret < 0)
2413     {
2414         BMCWEB_LOG_ERROR << "Failed to read SYSLOG_IDENTIFIER field: "
2415                          << strerror(-ret);
2416     }
2417     if (!syslogID.empty())
2418     {
2419         message += std::string(syslogID) + ": ";
2420     }
2421 
2422     std::string_view msg;
2423     ret = getJournalMetadata(journal, "MESSAGE", msg);
2424     if (ret < 0)
2425     {
2426         BMCWEB_LOG_ERROR << "Failed to read MESSAGE field: " << strerror(-ret);
2427         return 1;
2428     }
2429     message += std::string(msg);
2430 
2431     // Get the severity from the PRIORITY field
2432     long int severity = 8; // Default to an invalid priority
2433     ret = getJournalMetadata(journal, "PRIORITY", 10, severity);
2434     if (ret < 0)
2435     {
2436         BMCWEB_LOG_ERROR << "Failed to read PRIORITY field: " << strerror(-ret);
2437     }
2438 
2439     // Get the Created time from the timestamp
2440     std::string entryTimeStr;
2441     if (!getEntryTimestamp(journal, entryTimeStr))
2442     {
2443         return 1;
2444     }
2445 
2446     // Fill in the log entry with the gathered data
2447     bmcJournalLogEntryJson["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
2448     bmcJournalLogEntryJson["@odata.id"] = boost::urls::format(
2449         "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/{}",
2450         bmcJournalLogEntryID);
2451     bmcJournalLogEntryJson["Name"] = "BMC Journal Entry";
2452     bmcJournalLogEntryJson["Id"] = bmcJournalLogEntryID;
2453     bmcJournalLogEntryJson["Message"] = std::move(message);
2454     bmcJournalLogEntryJson["EntryType"] = "Oem";
2455     bmcJournalLogEntryJson["Severity"] = severity <= 2   ? "Critical"
2456                                          : severity <= 4 ? "Warning"
2457                                                          : "OK";
2458     bmcJournalLogEntryJson["OemRecordFormat"] = "BMC Journal Entry";
2459     bmcJournalLogEntryJson["Created"] = std::move(entryTimeStr);
2460     return 0;
2461 }
2462 
2463 inline void requestRoutesBMCJournalLogEntryCollection(App& app)
2464 {
2465     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/")
2466         .privileges(redfish::privileges::getLogEntryCollection)
2467         .methods(boost::beast::http::verb::get)(
2468             [&app](const crow::Request& req,
2469                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
2470         query_param::QueryCapabilities capabilities = {
2471             .canDelegateTop = true,
2472             .canDelegateSkip = true,
2473         };
2474         query_param::Query delegatedQuery;
2475         if (!redfish::setUpRedfishRouteWithDelegation(
2476                 app, req, asyncResp, delegatedQuery, capabilities))
2477         {
2478             return;
2479         }
2480 
2481         size_t skip = delegatedQuery.skip.value_or(0);
2482         size_t top = delegatedQuery.top.value_or(query_param::Query::maxTop);
2483 
2484         // Collections don't include the static data added by SubRoute
2485         // because it has a duplicate entry for members
2486         asyncResp->res.jsonValue["@odata.type"] =
2487             "#LogEntryCollection.LogEntryCollection";
2488         asyncResp->res.jsonValue["@odata.id"] =
2489             "/redfish/v1/Managers/bmc/LogServices/Journal/Entries";
2490         asyncResp->res.jsonValue["Name"] = "Open BMC Journal Entries";
2491         asyncResp->res.jsonValue["Description"] =
2492             "Collection of BMC Journal Entries";
2493         nlohmann::json& logEntryArray = asyncResp->res.jsonValue["Members"];
2494         logEntryArray = nlohmann::json::array();
2495 
2496         // Go through the journal and use the timestamp to create a
2497         // unique ID for each entry
2498         sd_journal* journalTmp = nullptr;
2499         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2500         if (ret < 0)
2501         {
2502             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2503             messages::internalError(asyncResp->res);
2504             return;
2505         }
2506         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2507             journalTmp, sd_journal_close);
2508         journalTmp = nullptr;
2509         uint64_t entryCount = 0;
2510         // Reset the unique ID on the first entry
2511         bool firstEntry = true;
2512         SD_JOURNAL_FOREACH(journal.get())
2513         {
2514             entryCount++;
2515             // Handle paging using skip (number of entries to skip from
2516             // the start) and top (number of entries to display)
2517             if (entryCount <= skip || entryCount > skip + top)
2518             {
2519                 continue;
2520             }
2521 
2522             std::string idStr;
2523             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2524             {
2525                 continue;
2526             }
2527             firstEntry = false;
2528 
2529             nlohmann::json::object_t bmcJournalLogEntry;
2530             if (fillBMCJournalLogEntryJson(idStr, journal.get(),
2531                                            bmcJournalLogEntry) != 0)
2532             {
2533                 messages::internalError(asyncResp->res);
2534                 return;
2535             }
2536             logEntryArray.emplace_back(std::move(bmcJournalLogEntry));
2537         }
2538         asyncResp->res.jsonValue["Members@odata.count"] = entryCount;
2539         if (skip + top < entryCount)
2540         {
2541             asyncResp->res.jsonValue["Members@odata.nextLink"] =
2542                 "/redfish/v1/Managers/bmc/LogServices/Journal/Entries?$skip=" +
2543                 std::to_string(skip + top);
2544         }
2545         });
2546 }
2547 
2548 inline void requestRoutesBMCJournalLogEntry(App& app)
2549 {
2550     BMCWEB_ROUTE(app,
2551                  "/redfish/v1/Managers/bmc/LogServices/Journal/Entries/<str>/")
2552         .privileges(redfish::privileges::getLogEntry)
2553         .methods(boost::beast::http::verb::get)(
2554             [&app](const crow::Request& req,
2555                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2556                    const std::string& entryID) {
2557         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2558         {
2559             return;
2560         }
2561         // Convert the unique ID back to a timestamp to find the entry
2562         uint64_t ts = 0;
2563         uint64_t index = 0;
2564         if (!getTimestampFromID(asyncResp, entryID, ts, index))
2565         {
2566             return;
2567         }
2568 
2569         sd_journal* journalTmp = nullptr;
2570         int ret = sd_journal_open(&journalTmp, SD_JOURNAL_LOCAL_ONLY);
2571         if (ret < 0)
2572         {
2573             BMCWEB_LOG_ERROR << "failed to open journal: " << strerror(-ret);
2574             messages::internalError(asyncResp->res);
2575             return;
2576         }
2577         std::unique_ptr<sd_journal, decltype(&sd_journal_close)> journal(
2578             journalTmp, sd_journal_close);
2579         journalTmp = nullptr;
2580         // Go to the timestamp in the log and move to the entry at the
2581         // index tracking the unique ID
2582         std::string idStr;
2583         bool firstEntry = true;
2584         ret = sd_journal_seek_realtime_usec(journal.get(), ts);
2585         if (ret < 0)
2586         {
2587             BMCWEB_LOG_ERROR << "failed to seek to an entry in journal"
2588                              << strerror(-ret);
2589             messages::internalError(asyncResp->res);
2590             return;
2591         }
2592         for (uint64_t i = 0; i <= index; i++)
2593         {
2594             sd_journal_next(journal.get());
2595             if (!getUniqueEntryID(journal.get(), idStr, firstEntry))
2596             {
2597                 messages::internalError(asyncResp->res);
2598                 return;
2599             }
2600             firstEntry = false;
2601         }
2602         // Confirm that the entry ID matches what was requested
2603         if (idStr != entryID)
2604         {
2605             messages::resourceNotFound(asyncResp->res, "LogEntry", entryID);
2606             return;
2607         }
2608 
2609         nlohmann::json::object_t bmcJournalLogEntry;
2610         if (fillBMCJournalLogEntryJson(entryID, journal.get(),
2611                                        bmcJournalLogEntry) != 0)
2612         {
2613             messages::internalError(asyncResp->res);
2614             return;
2615         }
2616         asyncResp->res.jsonValue.update(bmcJournalLogEntry);
2617         });
2618 }
2619 
2620 inline void
2621     getDumpServiceInfo(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2622                        const std::string& dumpType)
2623 {
2624     std::string dumpPath;
2625     std::string overWritePolicy;
2626     bool collectDiagnosticDataSupported = false;
2627 
2628     if (dumpType == "BMC")
2629     {
2630         dumpPath = "/redfish/v1/Managers/bmc/LogServices/Dump";
2631         overWritePolicy = "WrapsWhenFull";
2632         collectDiagnosticDataSupported = true;
2633     }
2634     else if (dumpType == "FaultLog")
2635     {
2636         dumpPath = "/redfish/v1/Managers/bmc/LogServices/FaultLog";
2637         overWritePolicy = "Unknown";
2638         collectDiagnosticDataSupported = false;
2639     }
2640     else if (dumpType == "System")
2641     {
2642         dumpPath = "/redfish/v1/Systems/system/LogServices/Dump";
2643         overWritePolicy = "WrapsWhenFull";
2644         collectDiagnosticDataSupported = true;
2645     }
2646     else
2647     {
2648         BMCWEB_LOG_ERROR << "getDumpServiceInfo() invalid dump type: "
2649                          << dumpType;
2650         messages::internalError(asyncResp->res);
2651         return;
2652     }
2653 
2654     asyncResp->res.jsonValue["@odata.id"] = dumpPath;
2655     asyncResp->res.jsonValue["@odata.type"] = "#LogService.v1_2_0.LogService";
2656     asyncResp->res.jsonValue["Name"] = "Dump LogService";
2657     asyncResp->res.jsonValue["Description"] = dumpType + " Dump LogService";
2658     asyncResp->res.jsonValue["Id"] = std::filesystem::path(dumpPath).filename();
2659     asyncResp->res.jsonValue["OverWritePolicy"] = std::move(overWritePolicy);
2660 
2661     std::pair<std::string, std::string> redfishDateTimeOffset =
2662         redfish::time_utils::getDateTimeOffsetNow();
2663     asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
2664     asyncResp->res.jsonValue["DateTimeLocalOffset"] =
2665         redfishDateTimeOffset.second;
2666 
2667     asyncResp->res.jsonValue["Entries"]["@odata.id"] = dumpPath + "/Entries";
2668 
2669     if (collectDiagnosticDataSupported)
2670     {
2671         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
2672                                 ["target"] =
2673             dumpPath + "/Actions/LogService.CollectDiagnosticData";
2674     }
2675 
2676     constexpr std::array<std::string_view, 1> interfaces = {deleteAllInterface};
2677     dbus::utility::getSubTreePaths(
2678         "/xyz/openbmc_project/dump", 0, interfaces,
2679         [asyncResp, dumpType, dumpPath](
2680             const boost::system::error_code& ec,
2681             const dbus::utility::MapperGetSubTreePathsResponse& subTreePaths) {
2682         if (ec)
2683         {
2684             BMCWEB_LOG_ERROR << "getDumpServiceInfo respHandler got error "
2685                              << ec;
2686             // Assume that getting an error simply means there are no dump
2687             // LogServices. Return without adding any error response.
2688             return;
2689         }
2690 
2691         const std::string dbusDumpPath =
2692             "/xyz/openbmc_project/dump/" +
2693             boost::algorithm::to_lower_copy(dumpType);
2694 
2695         for (const std::string& path : subTreePaths)
2696         {
2697             if (path == dbusDumpPath)
2698             {
2699                 asyncResp->res
2700                     .jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
2701                     dumpPath + "/Actions/LogService.ClearLog";
2702                 break;
2703             }
2704         }
2705         });
2706 }
2707 
2708 inline void handleLogServicesDumpServiceGet(
2709     crow::App& app, const std::string& dumpType, const crow::Request& req,
2710     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2711 {
2712     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2713     {
2714         return;
2715     }
2716     getDumpServiceInfo(asyncResp, dumpType);
2717 }
2718 
2719 inline void handleLogServicesDumpServiceComputerSystemGet(
2720     crow::App& app, const crow::Request& req,
2721     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2722     const std::string& chassisId)
2723 {
2724     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2725     {
2726         return;
2727     }
2728     if (chassisId != "system")
2729     {
2730         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2731         return;
2732     }
2733     getDumpServiceInfo(asyncResp, "System");
2734 }
2735 
2736 inline void handleLogServicesDumpEntriesCollectionGet(
2737     crow::App& app, const std::string& dumpType, const crow::Request& req,
2738     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2739 {
2740     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2741     {
2742         return;
2743     }
2744     getDumpEntryCollection(asyncResp, dumpType);
2745 }
2746 
2747 inline void handleLogServicesDumpEntriesCollectionComputerSystemGet(
2748     crow::App& app, const crow::Request& req,
2749     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2750     const std::string& chassisId)
2751 {
2752     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2753     {
2754         return;
2755     }
2756     if (chassisId != "system")
2757     {
2758         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2759         return;
2760     }
2761     getDumpEntryCollection(asyncResp, "System");
2762 }
2763 
2764 inline void handleLogServicesDumpEntryGet(
2765     crow::App& app, const std::string& dumpType, const crow::Request& req,
2766     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2767     const std::string& dumpId)
2768 {
2769     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2770     {
2771         return;
2772     }
2773     getDumpEntryById(asyncResp, dumpId, dumpType);
2774 }
2775 inline void handleLogServicesDumpEntryComputerSystemGet(
2776     crow::App& app, const crow::Request& req,
2777     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2778     const std::string& chassisId, const std::string& dumpId)
2779 {
2780     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2781     {
2782         return;
2783     }
2784     if (chassisId != "system")
2785     {
2786         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2787         return;
2788     }
2789     getDumpEntryById(asyncResp, dumpId, "System");
2790 }
2791 
2792 inline void handleLogServicesDumpEntryDelete(
2793     crow::App& app, const std::string& dumpType, const crow::Request& req,
2794     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2795     const std::string& dumpId)
2796 {
2797     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2798     {
2799         return;
2800     }
2801     deleteDumpEntry(asyncResp, dumpId, dumpType);
2802 }
2803 
2804 inline void handleLogServicesDumpEntryComputerSystemDelete(
2805     crow::App& app, const crow::Request& req,
2806     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2807     const std::string& chassisId, const std::string& dumpId)
2808 {
2809     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2810     {
2811         return;
2812     }
2813     if (chassisId != "system")
2814     {
2815         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2816         return;
2817     }
2818     deleteDumpEntry(asyncResp, dumpId, "System");
2819 }
2820 
2821 inline void handleLogServicesDumpCollectDiagnosticDataPost(
2822     crow::App& app, const std::string& dumpType, const crow::Request& req,
2823     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2824 {
2825     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2826     {
2827         return;
2828     }
2829     createDump(asyncResp, req, dumpType);
2830 }
2831 
2832 inline void handleLogServicesDumpCollectDiagnosticDataComputerSystemPost(
2833     crow::App& app, const crow::Request& req,
2834     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2835     const std::string& chassisId)
2836 {
2837     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2838     {
2839         return;
2840     }
2841     if (chassisId != "system")
2842     {
2843         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2844         return;
2845     }
2846     createDump(asyncResp, req, "System");
2847 }
2848 
2849 inline void handleLogServicesDumpClearLogPost(
2850     crow::App& app, const std::string& dumpType, const crow::Request& req,
2851     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
2852 {
2853     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2854     {
2855         return;
2856     }
2857     clearDump(asyncResp, dumpType);
2858 }
2859 
2860 inline void handleLogServicesDumpClearLogComputerSystemPost(
2861     crow::App& app, const crow::Request& req,
2862     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2863     const std::string& chassisId)
2864 {
2865     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2866     {
2867         return;
2868     }
2869     if (chassisId != "system")
2870     {
2871         messages::resourceNotFound(asyncResp->res, "ComputerSystem", chassisId);
2872         return;
2873     }
2874     clearDump(asyncResp, "System");
2875 }
2876 
2877 inline void requestRoutesBMCDumpService(App& app)
2878 {
2879     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/")
2880         .privileges(redfish::privileges::getLogService)
2881         .methods(boost::beast::http::verb::get)(std::bind_front(
2882             handleLogServicesDumpServiceGet, std::ref(app), "BMC"));
2883 }
2884 
2885 inline void requestRoutesBMCDumpEntryCollection(App& app)
2886 {
2887     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/")
2888         .privileges(redfish::privileges::getLogEntryCollection)
2889         .methods(boost::beast::http::verb::get)(std::bind_front(
2890             handleLogServicesDumpEntriesCollectionGet, std::ref(app), "BMC"));
2891 }
2892 
2893 inline void requestRoutesBMCDumpEntry(App& app)
2894 {
2895     BMCWEB_ROUTE(app,
2896                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2897         .privileges(redfish::privileges::getLogEntry)
2898         .methods(boost::beast::http::verb::get)(std::bind_front(
2899             handleLogServicesDumpEntryGet, std::ref(app), "BMC"));
2900 
2901     BMCWEB_ROUTE(app,
2902                  "/redfish/v1/Managers/bmc/LogServices/Dump/Entries/<str>/")
2903         .privileges(redfish::privileges::deleteLogEntry)
2904         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2905             handleLogServicesDumpEntryDelete, std::ref(app), "BMC"));
2906 }
2907 
2908 inline void requestRoutesBMCDumpCreate(App& app)
2909 {
2910     BMCWEB_ROUTE(
2911         app,
2912         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
2913         .privileges(redfish::privileges::postLogService)
2914         .methods(boost::beast::http::verb::post)(
2915             std::bind_front(handleLogServicesDumpCollectDiagnosticDataPost,
2916                             std::ref(app), "BMC"));
2917 }
2918 
2919 inline void requestRoutesBMCDumpClear(App& app)
2920 {
2921     BMCWEB_ROUTE(
2922         app,
2923         "/redfish/v1/Managers/bmc/LogServices/Dump/Actions/LogService.ClearLog/")
2924         .privileges(redfish::privileges::postLogService)
2925         .methods(boost::beast::http::verb::post)(std::bind_front(
2926             handleLogServicesDumpClearLogPost, std::ref(app), "BMC"));
2927 }
2928 
2929 inline void requestRoutesFaultLogDumpService(App& app)
2930 {
2931     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/")
2932         .privileges(redfish::privileges::getLogService)
2933         .methods(boost::beast::http::verb::get)(std::bind_front(
2934             handleLogServicesDumpServiceGet, std::ref(app), "FaultLog"));
2935 }
2936 
2937 inline void requestRoutesFaultLogDumpEntryCollection(App& app)
2938 {
2939     BMCWEB_ROUTE(app, "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/")
2940         .privileges(redfish::privileges::getLogEntryCollection)
2941         .methods(boost::beast::http::verb::get)(
2942             std::bind_front(handleLogServicesDumpEntriesCollectionGet,
2943                             std::ref(app), "FaultLog"));
2944 }
2945 
2946 inline void requestRoutesFaultLogDumpEntry(App& app)
2947 {
2948     BMCWEB_ROUTE(app,
2949                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2950         .privileges(redfish::privileges::getLogEntry)
2951         .methods(boost::beast::http::verb::get)(std::bind_front(
2952             handleLogServicesDumpEntryGet, std::ref(app), "FaultLog"));
2953 
2954     BMCWEB_ROUTE(app,
2955                  "/redfish/v1/Managers/bmc/LogServices/FaultLog/Entries/<str>/")
2956         .privileges(redfish::privileges::deleteLogEntry)
2957         .methods(boost::beast::http::verb::delete_)(std::bind_front(
2958             handleLogServicesDumpEntryDelete, std::ref(app), "FaultLog"));
2959 }
2960 
2961 inline void requestRoutesFaultLogDumpClear(App& app)
2962 {
2963     BMCWEB_ROUTE(
2964         app,
2965         "/redfish/v1/Managers/bmc/LogServices/FaultLog/Actions/LogService.ClearLog/")
2966         .privileges(redfish::privileges::postLogService)
2967         .methods(boost::beast::http::verb::post)(std::bind_front(
2968             handleLogServicesDumpClearLogPost, std::ref(app), "FaultLog"));
2969 }
2970 
2971 inline void requestRoutesSystemDumpService(App& app)
2972 {
2973     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Dump/")
2974         .privileges(redfish::privileges::getLogService)
2975         .methods(boost::beast::http::verb::get)(std::bind_front(
2976             handleLogServicesDumpServiceComputerSystemGet, std::ref(app)));
2977 }
2978 
2979 inline void requestRoutesSystemDumpEntryCollection(App& app)
2980 {
2981     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/")
2982         .privileges(redfish::privileges::getLogEntryCollection)
2983         .methods(boost::beast::http::verb::get)(std::bind_front(
2984             handleLogServicesDumpEntriesCollectionComputerSystemGet,
2985             std::ref(app)));
2986 }
2987 
2988 inline void requestRoutesSystemDumpEntry(App& app)
2989 {
2990     BMCWEB_ROUTE(app,
2991                  "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/<str>/")
2992         .privileges(redfish::privileges::getLogEntry)
2993         .methods(boost::beast::http::verb::get)(std::bind_front(
2994             handleLogServicesDumpEntryComputerSystemGet, std::ref(app)));
2995 
2996     BMCWEB_ROUTE(app,
2997                  "/redfish/v1/Systems/<str>/LogServices/Dump/Entries/<str>/")
2998         .privileges(redfish::privileges::deleteLogEntry)
2999         .methods(boost::beast::http::verb::delete_)(std::bind_front(
3000             handleLogServicesDumpEntryComputerSystemDelete, std::ref(app)));
3001 }
3002 
3003 inline void requestRoutesSystemDumpCreate(App& app)
3004 {
3005     BMCWEB_ROUTE(
3006         app,
3007         "/redfish/v1/Systems/<str>/LogServices/Dump/Actions/LogService.CollectDiagnosticData/")
3008         .privileges(redfish::privileges::postLogService)
3009         .methods(boost::beast::http::verb::post)(std::bind_front(
3010             handleLogServicesDumpCollectDiagnosticDataComputerSystemPost,
3011             std::ref(app)));
3012 }
3013 
3014 inline void requestRoutesSystemDumpClear(App& app)
3015 {
3016     BMCWEB_ROUTE(
3017         app,
3018         "/redfish/v1/Systems/<str>/LogServices/Dump/Actions/LogService.ClearLog/")
3019         .privileges(redfish::privileges::postLogService)
3020         .methods(boost::beast::http::verb::post)(std::bind_front(
3021             handleLogServicesDumpClearLogComputerSystemPost, std::ref(app)));
3022 }
3023 
3024 inline void requestRoutesCrashdumpService(App& app)
3025 {
3026     // Note: Deviated from redfish privilege registry for GET & HEAD
3027     // method for security reasons.
3028     /**
3029      * Functions triggers appropriate requests on DBus
3030      */
3031     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/Crashdump/")
3032         // This is incorrect, should be:
3033         //.privileges(redfish::privileges::getLogService)
3034         .privileges({{"ConfigureManager"}})
3035         .methods(boost::beast::http::verb::get)(
3036             [&app](const crow::Request& req,
3037                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3038                    const std::string& systemName) {
3039         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3040         {
3041             return;
3042         }
3043         if (systemName != "system")
3044         {
3045             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3046                                        systemName);
3047             return;
3048         }
3049 
3050         // Copy over the static data to include the entries added by
3051         // SubRoute
3052         asyncResp->res.jsonValue["@odata.id"] =
3053             "/redfish/v1/Systems/system/LogServices/Crashdump";
3054         asyncResp->res.jsonValue["@odata.type"] =
3055             "#LogService.v1_2_0.LogService";
3056         asyncResp->res.jsonValue["Name"] = "Open BMC Oem Crashdump Service";
3057         asyncResp->res.jsonValue["Description"] = "Oem Crashdump Service";
3058         asyncResp->res.jsonValue["Id"] = "Crashdump";
3059         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
3060         asyncResp->res.jsonValue["MaxNumberOfRecords"] = 3;
3061 
3062         std::pair<std::string, std::string> redfishDateTimeOffset =
3063             redfish::time_utils::getDateTimeOffsetNow();
3064         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3065         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3066             redfishDateTimeOffset.second;
3067 
3068         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
3069             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
3070         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"]["target"] =
3071             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.ClearLog";
3072         asyncResp->res.jsonValue["Actions"]["#LogService.CollectDiagnosticData"]
3073                                 ["target"] =
3074             "/redfish/v1/Systems/system/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData";
3075         });
3076 }
3077 
3078 void inline requestRoutesCrashdumpClear(App& app)
3079 {
3080     BMCWEB_ROUTE(
3081         app,
3082         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Actions/LogService.ClearLog/")
3083         // This is incorrect, should be:
3084         //.privileges(redfish::privileges::postLogService)
3085         .privileges({{"ConfigureComponents"}})
3086         .methods(boost::beast::http::verb::post)(
3087             [&app](const crow::Request& req,
3088                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3089                    const std::string& systemName) {
3090         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3091         {
3092             return;
3093         }
3094         if (systemName != "system")
3095         {
3096             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3097                                        systemName);
3098             return;
3099         }
3100         crow::connections::systemBus->async_method_call(
3101             [asyncResp](const boost::system::error_code& ec,
3102                         const std::string&) {
3103             if (ec)
3104             {
3105                 messages::internalError(asyncResp->res);
3106                 return;
3107             }
3108             messages::success(asyncResp->res);
3109             },
3110             crashdumpObject, crashdumpPath, deleteAllInterface, "DeleteAll");
3111         });
3112 }
3113 
3114 static void
3115     logCrashdumpEntry(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3116                       const std::string& logID, nlohmann::json& logEntryJson)
3117 {
3118     auto getStoredLogCallback =
3119         [asyncResp, logID,
3120          &logEntryJson](const boost::system::error_code& ec,
3121                         const dbus::utility::DBusPropertiesMap& params) {
3122         if (ec)
3123         {
3124             BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
3125             if (ec.value() ==
3126                 boost::system::linux_error::bad_request_descriptor)
3127             {
3128                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3129             }
3130             else
3131             {
3132                 messages::internalError(asyncResp->res);
3133             }
3134             return;
3135         }
3136 
3137         std::string timestamp{};
3138         std::string filename{};
3139         std::string logfile{};
3140         parseCrashdumpParameters(params, filename, timestamp, logfile);
3141 
3142         if (filename.empty() || timestamp.empty())
3143         {
3144             messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3145             return;
3146         }
3147 
3148         std::string crashdumpURI =
3149             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/" +
3150             logID + "/" + filename;
3151         nlohmann::json::object_t logEntry;
3152         logEntry["@odata.type"] = "#LogEntry.v1_9_0.LogEntry";
3153         logEntry["@odata.id"] = boost::urls::format(
3154             "/redfish/v1/Systems/system/LogServices/Crashdump/Entries/{}",
3155             logID);
3156         logEntry["Name"] = "CPU Crashdump";
3157         logEntry["Id"] = logID;
3158         logEntry["EntryType"] = "Oem";
3159         logEntry["AdditionalDataURI"] = std::move(crashdumpURI);
3160         logEntry["DiagnosticDataType"] = "OEM";
3161         logEntry["OEMDiagnosticDataType"] = "PECICrashdump";
3162         logEntry["Created"] = std::move(timestamp);
3163 
3164         // If logEntryJson references an array of LogEntry resources
3165         // ('Members' list), then push this as a new entry, otherwise set it
3166         // directly
3167         if (logEntryJson.is_array())
3168         {
3169             logEntryJson.push_back(logEntry);
3170             asyncResp->res.jsonValue["Members@odata.count"] =
3171                 logEntryJson.size();
3172         }
3173         else
3174         {
3175             logEntryJson.update(logEntry);
3176         }
3177     };
3178     sdbusplus::asio::getAllProperties(
3179         *crow::connections::systemBus, crashdumpObject,
3180         crashdumpPath + std::string("/") + logID, crashdumpInterface,
3181         std::move(getStoredLogCallback));
3182 }
3183 
3184 inline void requestRoutesCrashdumpEntryCollection(App& app)
3185 {
3186     // Note: Deviated from redfish privilege registry for GET & HEAD
3187     // method for security reasons.
3188     /**
3189      * Functions triggers appropriate requests on DBus
3190      */
3191     BMCWEB_ROUTE(app,
3192                  "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/")
3193         // This is incorrect, should be.
3194         //.privileges(redfish::privileges::postLogEntryCollection)
3195         .privileges({{"ConfigureComponents"}})
3196         .methods(boost::beast::http::verb::get)(
3197             [&app](const crow::Request& req,
3198                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3199                    const std::string& systemName) {
3200         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3201         {
3202             return;
3203         }
3204         if (systemName != "system")
3205         {
3206             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3207                                        systemName);
3208             return;
3209         }
3210 
3211         constexpr std::array<std::string_view, 1> interfaces = {
3212             crashdumpInterface};
3213         dbus::utility::getSubTreePaths(
3214             "/", 0, interfaces,
3215             [asyncResp](const boost::system::error_code& ec,
3216                         const std::vector<std::string>& resp) {
3217             if (ec)
3218             {
3219                 if (ec.value() !=
3220                     boost::system::errc::no_such_file_or_directory)
3221                 {
3222                     BMCWEB_LOG_DEBUG << "failed to get entries ec: "
3223                                      << ec.message();
3224                     messages::internalError(asyncResp->res);
3225                     return;
3226                 }
3227             }
3228             asyncResp->res.jsonValue["@odata.type"] =
3229                 "#LogEntryCollection.LogEntryCollection";
3230             asyncResp->res.jsonValue["@odata.id"] =
3231                 "/redfish/v1/Systems/system/LogServices/Crashdump/Entries";
3232             asyncResp->res.jsonValue["Name"] = "Open BMC Crashdump Entries";
3233             asyncResp->res.jsonValue["Description"] =
3234                 "Collection of Crashdump Entries";
3235             asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
3236             asyncResp->res.jsonValue["Members@odata.count"] = 0;
3237 
3238             for (const std::string& path : resp)
3239             {
3240                 const sdbusplus::message::object_path objPath(path);
3241                 // Get the log ID
3242                 std::string logID = objPath.filename();
3243                 if (logID.empty())
3244                 {
3245                     continue;
3246                 }
3247                 // Add the log entry to the array
3248                 logCrashdumpEntry(asyncResp, logID,
3249                                   asyncResp->res.jsonValue["Members"]);
3250             }
3251             });
3252         });
3253 }
3254 
3255 inline void requestRoutesCrashdumpEntry(App& app)
3256 {
3257     // Note: Deviated from redfish privilege registry for GET & HEAD
3258     // method for security reasons.
3259 
3260     BMCWEB_ROUTE(
3261         app, "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/<str>/")
3262         // this is incorrect, should be
3263         // .privileges(redfish::privileges::getLogEntry)
3264         .privileges({{"ConfigureComponents"}})
3265         .methods(boost::beast::http::verb::get)(
3266             [&app](const crow::Request& req,
3267                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3268                    const std::string& systemName, const std::string& param) {
3269         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3270         {
3271             return;
3272         }
3273         if (systemName != "system")
3274         {
3275             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3276                                        systemName);
3277             return;
3278         }
3279         const std::string& logID = param;
3280         logCrashdumpEntry(asyncResp, logID, asyncResp->res.jsonValue);
3281         });
3282 }
3283 
3284 inline void requestRoutesCrashdumpFile(App& app)
3285 {
3286     // Note: Deviated from redfish privilege registry for GET & HEAD
3287     // method for security reasons.
3288     BMCWEB_ROUTE(
3289         app,
3290         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Entries/<str>/<str>/")
3291         .privileges(redfish::privileges::getLogEntry)
3292         .methods(boost::beast::http::verb::get)(
3293             [](const crow::Request& req,
3294                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3295                const std::string& systemName, const std::string& logID,
3296                const std::string& fileName) {
3297         // Do not call getRedfishRoute here since the crashdump file is not a
3298         // Redfish resource.
3299 
3300         if (systemName != "system")
3301         {
3302             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3303                                        systemName);
3304             return;
3305         }
3306 
3307         auto getStoredLogCallback =
3308             [asyncResp, logID, fileName, url(boost::urls::url(req.url()))](
3309                 const boost::system::error_code& ec,
3310                 const std::vector<
3311                     std::pair<std::string, dbus::utility::DbusVariantType>>&
3312                     resp) {
3313             if (ec)
3314             {
3315                 BMCWEB_LOG_DEBUG << "failed to get log ec: " << ec.message();
3316                 messages::internalError(asyncResp->res);
3317                 return;
3318             }
3319 
3320             std::string dbusFilename{};
3321             std::string dbusTimestamp{};
3322             std::string dbusFilepath{};
3323 
3324             parseCrashdumpParameters(resp, dbusFilename, dbusTimestamp,
3325                                      dbusFilepath);
3326 
3327             if (dbusFilename.empty() || dbusTimestamp.empty() ||
3328                 dbusFilepath.empty())
3329             {
3330                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3331                 return;
3332             }
3333 
3334             // Verify the file name parameter is correct
3335             if (fileName != dbusFilename)
3336             {
3337                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3338                 return;
3339             }
3340 
3341             if (!std::filesystem::exists(dbusFilepath))
3342             {
3343                 messages::resourceNotFound(asyncResp->res, "LogEntry", logID);
3344                 return;
3345             }
3346             std::ifstream ifs(dbusFilepath, std::ios::in | std::ios::binary);
3347             asyncResp->res.body() =
3348                 std::string(std::istreambuf_iterator<char>{ifs}, {});
3349 
3350             // Configure this to be a file download when accessed
3351             // from a browser
3352             asyncResp->res.addHeader(
3353                 boost::beast::http::field::content_disposition, "attachment");
3354         };
3355         sdbusplus::asio::getAllProperties(
3356             *crow::connections::systemBus, crashdumpObject,
3357             crashdumpPath + std::string("/") + logID, crashdumpInterface,
3358             std::move(getStoredLogCallback));
3359         });
3360 }
3361 
3362 enum class OEMDiagnosticType
3363 {
3364     onDemand,
3365     telemetry,
3366     invalid,
3367 };
3368 
3369 inline OEMDiagnosticType getOEMDiagnosticType(std::string_view oemDiagStr)
3370 {
3371     if (oemDiagStr == "OnDemand")
3372     {
3373         return OEMDiagnosticType::onDemand;
3374     }
3375     if (oemDiagStr == "Telemetry")
3376     {
3377         return OEMDiagnosticType::telemetry;
3378     }
3379 
3380     return OEMDiagnosticType::invalid;
3381 }
3382 
3383 inline void requestRoutesCrashdumpCollect(App& app)
3384 {
3385     // Note: Deviated from redfish privilege registry for GET & HEAD
3386     // method for security reasons.
3387     BMCWEB_ROUTE(
3388         app,
3389         "/redfish/v1/Systems/<str>/LogServices/Crashdump/Actions/LogService.CollectDiagnosticData/")
3390         // The below is incorrect;  Should be ConfigureManager
3391         //.privileges(redfish::privileges::postLogService)
3392         .privileges({{"ConfigureComponents"}})
3393         .methods(boost::beast::http::verb::post)(
3394             [&app](const crow::Request& req,
3395                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3396                    const std::string& systemName) {
3397         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3398         {
3399             return;
3400         }
3401 
3402         if (systemName != "system")
3403         {
3404             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3405                                        systemName);
3406             return;
3407         }
3408 
3409         std::string diagnosticDataType;
3410         std::string oemDiagnosticDataType;
3411         if (!redfish::json_util::readJsonAction(
3412                 req, asyncResp->res, "DiagnosticDataType", diagnosticDataType,
3413                 "OEMDiagnosticDataType", oemDiagnosticDataType))
3414         {
3415             return;
3416         }
3417 
3418         if (diagnosticDataType != "OEM")
3419         {
3420             BMCWEB_LOG_ERROR
3421                 << "Only OEM DiagnosticDataType supported for Crashdump";
3422             messages::actionParameterValueFormatError(
3423                 asyncResp->res, diagnosticDataType, "DiagnosticDataType",
3424                 "CollectDiagnosticData");
3425             return;
3426         }
3427 
3428         OEMDiagnosticType oemDiagType =
3429             getOEMDiagnosticType(oemDiagnosticDataType);
3430 
3431         std::string iface;
3432         std::string method;
3433         std::string taskMatchStr;
3434         if (oemDiagType == OEMDiagnosticType::onDemand)
3435         {
3436             iface = crashdumpOnDemandInterface;
3437             method = "GenerateOnDemandLog";
3438             taskMatchStr = "type='signal',"
3439                            "interface='org.freedesktop.DBus.Properties',"
3440                            "member='PropertiesChanged',"
3441                            "arg0namespace='com.intel.crashdump'";
3442         }
3443         else if (oemDiagType == OEMDiagnosticType::telemetry)
3444         {
3445             iface = crashdumpTelemetryInterface;
3446             method = "GenerateTelemetryLog";
3447             taskMatchStr = "type='signal',"
3448                            "interface='org.freedesktop.DBus.Properties',"
3449                            "member='PropertiesChanged',"
3450                            "arg0namespace='com.intel.crashdump'";
3451         }
3452         else
3453         {
3454             BMCWEB_LOG_ERROR << "Unsupported OEMDiagnosticDataType: "
3455                              << oemDiagnosticDataType;
3456             messages::actionParameterValueFormatError(
3457                 asyncResp->res, oemDiagnosticDataType, "OEMDiagnosticDataType",
3458                 "CollectDiagnosticData");
3459             return;
3460         }
3461 
3462         auto collectCrashdumpCallback =
3463             [asyncResp, payload(task::Payload(req)),
3464              taskMatchStr](const boost::system::error_code& ec,
3465                            const std::string&) mutable {
3466             if (ec)
3467             {
3468                 if (ec.value() == boost::system::errc::operation_not_supported)
3469                 {
3470                     messages::resourceInStandby(asyncResp->res);
3471                 }
3472                 else if (ec.value() ==
3473                          boost::system::errc::device_or_resource_busy)
3474                 {
3475                     messages::serviceTemporarilyUnavailable(asyncResp->res,
3476                                                             "60");
3477                 }
3478                 else
3479                 {
3480                     messages::internalError(asyncResp->res);
3481                 }
3482                 return;
3483             }
3484             std::shared_ptr<task::TaskData> task = task::TaskData::createTask(
3485                 [](const boost::system::error_code& err, sdbusplus::message_t&,
3486                    const std::shared_ptr<task::TaskData>& taskData) {
3487                 if (!err)
3488                 {
3489                     taskData->messages.emplace_back(messages::taskCompletedOK(
3490                         std::to_string(taskData->index)));
3491                     taskData->state = "Completed";
3492                 }
3493                 return task::completed;
3494                 },
3495                 taskMatchStr);
3496 
3497             task->startTimer(std::chrono::minutes(5));
3498             task->populateResp(asyncResp->res);
3499             task->payload.emplace(std::move(payload));
3500         };
3501 
3502         crow::connections::systemBus->async_method_call(
3503             std::move(collectCrashdumpCallback), crashdumpObject, crashdumpPath,
3504             iface, method);
3505         });
3506 }
3507 
3508 /**
3509  * DBusLogServiceActionsClear class supports POST method for ClearLog action.
3510  */
3511 inline void requestRoutesDBusLogServiceActionsClear(App& app)
3512 {
3513     /**
3514      * Function handles POST method request.
3515      * The Clear Log actions does not require any parameter.The action deletes
3516      * all entries found in the Entries collection for this Log Service.
3517      */
3518 
3519     BMCWEB_ROUTE(
3520         app,
3521         "/redfish/v1/Systems/<str>/LogServices/EventLog/Actions/LogService.ClearLog/")
3522         .privileges(redfish::privileges::postLogService)
3523         .methods(boost::beast::http::verb::post)(
3524             [&app](const crow::Request& req,
3525                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3526                    const std::string& systemName) {
3527         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3528         {
3529             return;
3530         }
3531         if (systemName != "system")
3532         {
3533             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3534                                        systemName);
3535             return;
3536         }
3537         BMCWEB_LOG_DEBUG << "Do delete all entries.";
3538 
3539         // Process response from Logging service.
3540         auto respHandler = [asyncResp](const boost::system::error_code& ec) {
3541             BMCWEB_LOG_DEBUG << "doClearLog resp_handler callback: Done";
3542             if (ec)
3543             {
3544                 // TODO Handle for specific error code
3545                 BMCWEB_LOG_ERROR << "doClearLog resp_handler got error " << ec;
3546                 asyncResp->res.result(
3547                     boost::beast::http::status::internal_server_error);
3548                 return;
3549             }
3550 
3551             asyncResp->res.result(boost::beast::http::status::no_content);
3552         };
3553 
3554         // Make call to Logging service to request Clear Log
3555         crow::connections::systemBus->async_method_call(
3556             respHandler, "xyz.openbmc_project.Logging",
3557             "/xyz/openbmc_project/logging",
3558             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3559         });
3560 }
3561 
3562 /****************************************************
3563  * Redfish PostCode interfaces
3564  * using DBUS interface: getPostCodesTS
3565  ******************************************************/
3566 inline void requestRoutesPostCodesLogService(App& app)
3567 {
3568     BMCWEB_ROUTE(app, "/redfish/v1/Systems/<str>/LogServices/PostCodes/")
3569         .privileges(redfish::privileges::getLogService)
3570         .methods(boost::beast::http::verb::get)(
3571             [&app](const crow::Request& req,
3572                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3573                    const std::string& systemName) {
3574         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3575         {
3576             return;
3577         }
3578         if (systemName != "system")
3579         {
3580             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3581                                        systemName);
3582             return;
3583         }
3584         asyncResp->res.jsonValue["@odata.id"] =
3585             "/redfish/v1/Systems/system/LogServices/PostCodes";
3586         asyncResp->res.jsonValue["@odata.type"] =
3587             "#LogService.v1_1_0.LogService";
3588         asyncResp->res.jsonValue["Name"] = "POST Code Log Service";
3589         asyncResp->res.jsonValue["Description"] = "POST Code Log Service";
3590         asyncResp->res.jsonValue["Id"] = "PostCodes";
3591         asyncResp->res.jsonValue["OverWritePolicy"] = "WrapsWhenFull";
3592         asyncResp->res.jsonValue["Entries"]["@odata.id"] =
3593             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries";
3594 
3595         std::pair<std::string, std::string> redfishDateTimeOffset =
3596             redfish::time_utils::getDateTimeOffsetNow();
3597         asyncResp->res.jsonValue["DateTime"] = redfishDateTimeOffset.first;
3598         asyncResp->res.jsonValue["DateTimeLocalOffset"] =
3599             redfishDateTimeOffset.second;
3600 
3601         asyncResp->res.jsonValue["Actions"]["#LogService.ClearLog"] = {
3602             {"target",
3603              "/redfish/v1/Systems/system/LogServices/PostCodes/Actions/LogService.ClearLog"}};
3604         });
3605 }
3606 
3607 inline void requestRoutesPostCodesClear(App& app)
3608 {
3609     BMCWEB_ROUTE(
3610         app,
3611         "/redfish/v1/Systems/<str>/LogServices/PostCodes/Actions/LogService.ClearLog/")
3612         // The following privilege is incorrect;  It should be ConfigureManager
3613         //.privileges(redfish::privileges::postLogService)
3614         .privileges({{"ConfigureComponents"}})
3615         .methods(boost::beast::http::verb::post)(
3616             [&app](const crow::Request& req,
3617                    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3618                    const std::string& systemName) {
3619         if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3620         {
3621             return;
3622         }
3623         if (systemName != "system")
3624         {
3625             messages::resourceNotFound(asyncResp->res, "ComputerSystem",
3626                                        systemName);
3627             return;
3628         }
3629         BMCWEB_LOG_DEBUG << "Do delete all postcodes entries.";
3630 
3631         // Make call to post-code service to request clear all
3632         crow::connections::systemBus->async_method_call(
3633             [asyncResp](const boost::system::error_code& ec) {
3634             if (ec)
3635             {
3636                 // TODO Handle for specific error code
3637                 BMCWEB_LOG_ERROR << "doClearPostCodes resp_handler got error "
3638                                  << ec;
3639                 asyncResp->res.result(
3640                     boost::beast::http::status::internal_server_error);
3641                 messages::internalError(asyncResp->res);
3642                 return;
3643             }
3644             },
3645             "xyz.openbmc_project.State.Boot.PostCode0",
3646             "/xyz/openbmc_project/State/Boot/PostCode0",
3647             "xyz.openbmc_project.Collection.DeleteAll", "DeleteAll");
3648         });
3649 }
3650 
3651 /**
3652  * @brief Parse post code ID and get the current value and index value
3653  *        eg: postCodeID=B1-2, currentValue=1, index=2
3654  *
3655  * @param[in]  postCodeID     Post Code ID
3656  * @param[out] currentValue   Current value
3657  * @param[out] index          Index value
3658  *
3659  * @return bool true if the parsing is successful, false the parsing fails
3660  */
3661 inline static bool parsePostCode(const std::string& postCodeID,
3662                                  uint64_t& currentValue, uint16_t& index)
3663 {
3664     std::vector<std::string> split;
3665     bmcweb::split(split, postCodeID, '-');
3666     if (split.size() != 2 || split[0].length() < 2 || split[0].front() != 'B')
3667     {
3668         return false;
3669     }
3670 
3671     auto start = std::next(split[0].begin());
3672     auto end = split[0].end();
3673     auto [ptrIndex, ecIndex] = std::from_chars(&*start, &*end, index);
3674 
3675     if (ptrIndex != &*end || ecIndex != std::errc())
3676     {
3677         return false;
3678     }
3679 
3680     start = split[1].begin();
3681     end = split[1].end();
3682 
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"] = boost::urls::format(
3790             "/redfish/v1/Systems/system/LogServices/PostCodes/Entries/{}",
3791             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.emplace_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 = std::max(static_cast<uint64_t>(skip),
3899                                                  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