• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium Authors
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 NET_SOCKET_SOCKET_TAG_H_
6 #define NET_SOCKET_SOCKET_TAG_H_
7 
8 #include "build/build_config.h"
9 #include "net/base/net_export.h"
10 #include "net/socket/socket_descriptor.h"
11 
12 #if BUILDFLAG(IS_ANDROID)
13 #include <stdint.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 #endif
17 
18 namespace net {
19 
20 // SocketTag represents a tag that can be applied to a socket. Currently only
21 // implemented for Android, it facilitates assigning a Android TrafficStats tag
22 // and UID to a socket so that future network data usage by the socket is
23 // attributed to the tag and UID that the socket is tagged with.
24 //
25 // This class is small (<=64-bits) and contains only POD to facilitate default
26 // copy and assignment operators so that it can easily be passed by value.
27 class NET_EXPORT SocketTag {
28  public:
29 #if BUILDFLAG(IS_ANDROID)
30   // Default constructor doesn't set any tags.
SocketTag()31   SocketTag() : SocketTag(UNSET_UID, UNSET_TAG) {}
32   // Create a SocketTag with given UID |uid| and |traffic_stats_tag|.
SocketTag(uid_t uid,int32_t traffic_stats_tag)33   SocketTag(uid_t uid, int32_t traffic_stats_tag)
34       : uid_(uid), traffic_stats_tag_(traffic_stats_tag) {}
35 #else
36   SocketTag() = default;
37 #endif  // BUILDFLAG(IS_ANDROID)
38   ~SocketTag() = default;
39 
40   bool operator<(const SocketTag& other) const;
41   bool operator==(const SocketTag& other) const;
42   bool operator!=(const SocketTag& other) const { return !(*this == other); }
43 
44   // Apply this tag to |socket|.
45   void Apply(SocketDescriptor socket) const;
46 
47 #if BUILDFLAG(IS_ANDROID)
48   // Values to indicate no UID or tag should be set. These values match those in
49   // Android:
50   // http://androidxref.com/4.4_r1/xref/frameworks/base/core/java/android/net/TrafficStats.java#147
51   // http://androidxref.com/4.4_r1/xref/frameworks/base/core/java/android/net/TrafficStats.java#169
52   static const uid_t UNSET_UID = -1;
53   static const int32_t UNSET_TAG = -1;
54 
55  private:
56   // UID to tag with.
57   uid_t uid_;
58   // TrafficStats tag to tag with.
59   int32_t traffic_stats_tag_;
60 #endif  // BUILDFLAG(IS_ANDROID)
61   // Copying and assignment are allowed.
62 };
63 
64 }  // namespace net
65 
66 #endif  // NET_SOCKET_SOCKET_TAG_H_
67