1 // Copyright (c) 2020 The Chromium Embedded Framework Authors. All rights 2 // reserved. Use of this source code is governed by a BSD-style license that 3 // can be found in the LICENSE file. 4 5 #ifndef CEF_LIBCEF_BROWSER_DEVTOOLS_DEVTOOLS_UTIL_H_ 6 #define CEF_LIBCEF_BROWSER_DEVTOOLS_DEVTOOLS_UTIL_H_ 7 #pragma once 8 9 #include "base/strings/string_piece.h" 10 11 namespace devtools_util { 12 13 // Fast parser for DevTools JSON protocol messages. This implementation makes 14 // certain assumptions about the JSON object structure (value order and 15 // formatting) to avoid stateful parsing of messages that may be large 16 // (sometimes > 1MB in size). The message must be a JSON dictionary that starts 17 // with a "method" or "id" value which is non-empty and of the expected data 18 // type. Messages that have a "method" value (event message) may optionally have 19 // a "params" dictionary. Messages that have an "id" value (result message) must 20 // have a "result" or "error" dictionary. The dictionary contents are not 21 // validated and may be empty ("{}"). 22 // 23 // Example event message: 24 // {"method":"Target.targetDestroyed","params":{"targetId":"1234..."}} 25 // 26 // Example result messages: 27 // {"id":3,"result":{}} 28 // {"id":4,"result":{"debuggerId":"-2193881606781505058.81393575456727957"}} 29 // {"id":5,"error":{"code":-32000,"message":"Not supported"}} 30 struct ProtocolParser { 31 ProtocolParser() = default; 32 33 // Checks for a non-empty JSON dictionary. 34 static bool IsValidMessage(const base::StringPiece& message); 35 36 // Returns false if already initialized. 37 bool Initialize(const base::StringPiece& message); 38 IsInitializedProtocolParser39 bool IsInitialized() const { return status_ != UNINITIALIZED; } IsEventProtocolParser40 bool IsEvent() const { return status_ == EVENT; } IsResultProtocolParser41 bool IsResult() const { return status_ == RESULT; } IsFailureProtocolParser42 bool IsFailure() const { return status_ == FAILURE; } 43 ResetProtocolParser44 void Reset() { status_ = UNINITIALIZED; } 45 46 // For event messages: 47 // "method" string: 48 base::StringPiece method_; 49 50 // For result messages: 51 // "id" int: 52 int message_id_ = 0; 53 // true if "result" value, false if "error" value: 54 bool success_ = false; 55 56 // For both: 57 // "params", "result" or "error" dictionary: 58 base::StringPiece params_; 59 60 private: 61 enum Status { 62 UNINITIALIZED, 63 EVENT, // Event message. 64 RESULT, // Result message. 65 FAILURE, // Parsing failure. 66 }; 67 Status status_ = UNINITIALIZED; 68 }; 69 70 } // namespace devtools_util 71 72 #endif // CEF_LIBCEF_BROWSER_DEVTOOLS_DEVTOOLS_UTIL_H_