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