1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef COMPONENTS_CAST_CHANNEL_LOGGER_H_
6 #define COMPONENTS_CAST_CHANNEL_LOGGER_H_
7 
8 #include <stddef.h>
9 
10 #include <map>
11 #include <memory>
12 #include <string>
13 
14 #include "base/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/threading/thread_checker.h"
17 #include "components/cast_channel/cast_channel_enum.h"
18 
19 namespace cast_channel {
20 
21 struct AuthResult;
22 
23 // Holds the most recent error encountered by a CastSocket.
24 struct LastError {
25  public:
26   LastError();
27   ~LastError();
28 
29   // The most recent event that occurred at the time of the error.
30   ChannelEvent channel_event;
31 
32   // The most recent ChallengeReplyError logged for the socket.
33   // NOTE(mfoltz): AuthResult::ErrorType is zero-indexed and ChallengeReplyError
34   // is one-indexed, so we can't use AuthResult::ErrorType here.
35   ChallengeReplyError challenge_reply_error;
36 
37   // The most recent net_return_value logged for the socket.
38   int net_return_value;
39 };
40 
41 // Called with events that occur on a Cast Channel and remembers any that
42 // warrant reporting to the caller in LastError.
43 class Logger : public base::RefCountedThreadSafe<Logger> {
44  public:
45   Logger();
46 
47   // For events that involves socket / crypto operations that returns a value.
48   void LogSocketEventWithRv(int channel_id, ChannelEvent channel_event, int rv);
49 
50   // For AUTH_CHALLENGE_REPLY event.
51   void LogSocketChallengeReplyEvent(int channel_id,
52                                     const AuthResult& auth_result);
53 
54   // Returns the last errors logged for |channel_id|.
55   LastError GetLastError(int channel_id) const;
56 
57   // Removes a LastError entry for |channel_id| if one exists.
58   void ClearLastError(int channel_id);
59 
60  private:
61   friend class base::RefCountedThreadSafe<Logger>;
62   ~Logger();
63 
64   // Propagate any error values in |rv| or |challenge_reply_error| to the
65   // LastError for |channel_id|.
66   void MaybeSetLastError(int channel_id,
67                          ChannelEvent channel_event,
68                          int rv,
69                          ChallengeReplyError challenge_reply_error);
70 
71   // Maps channel_id to the LastError for the channel.
72   std::map<int, LastError> last_errors_;
73 
74   THREAD_CHECKER(thread_checker_);
75 
76   DISALLOW_COPY_AND_ASSIGN(Logger);
77 };
78 }  // namespace cast_channel
79 
80 #endif  // COMPONENTS_CAST_CHANNEL_LOGGER_H_
81