View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2024 Christian Kohlschütter
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.newsclub.net.unix;
19  
20  import java.io.IOException;
21  import java.io.Serializable;
22  import java.net.Socket;
23  import java.rmi.server.RemoteServer;
24  import java.util.Arrays;
25  import java.util.UUID;
26  
27  /**
28   * AF_UNIX socket credentials.
29   *
30   * @see AFUNIXSocket#getPeerCredentials()
31   */
32  public final class AFUNIXSocketCredentials implements Serializable {
33    private static final long serialVersionUID = 1L;
34  
35    /**
36     * Special instance, indicating that there is no remote peer, but the referenced object is from
37     * the same process.
38     */
39    public static final AFUNIXSocketCredentials SAME_PROCESS = new AFUNIXSocketCredentials();
40  
41    /**
42     * The PID, or -1 for "not set".
43     */
44    private long pid = -1; // NOPMD -- Set in native code
45  
46    /**
47     * The UID, or -1 for "not set".
48     */
49    private long uid = -1; // NOPMD -- Set in native code
50  
51    /**
52     * All GID values (or null for "not set"); the first being the primary one.
53     */
54    private long[] gids = null;
55  
56    /**
57     * The UUID, or null for "not set".
58     */
59    private UUID uuid = null;
60  
61    AFUNIXSocketCredentials() {
62    }
63  
64    /**
65     * Returns the "pid" (process ID), or {@code -1} if it could not be retrieved.
66     *
67     * @return The pid, or -1.
68     */
69    public long getPid() {
70      return pid;
71    }
72  
73    /**
74     * Returns the "uid" (user ID), or {@code -1} if it could not be retrieved.
75     *
76     * @return The uid, or -1.
77     */
78    public long getUid() {
79      return uid;
80    }
81  
82    /**
83     * Returns the primary "gid" (group ID), or {@code -1} if it could not be retrieved.
84     *
85     * @return The gid, or -1.
86     */
87    public long getGid() {
88      return gids == null ? -1 : gids.length == 0 ? -1 : gids[0];
89    }
90  
91    /**
92     * Returns all "gid" values (group IDs), or {@code null} if they could not be retrieved.
93     *
94     * Note that this list may be incomplete (only the primary gid may be returned), but it is
95     * guaranteed that the first one in the list is the primary gid as returned by {@link #getGid()}.
96     *
97     * @return The gids, or null.
98     */
99    public long[] getGids() {
100     return gids == null ? null : gids.clone();
101   }
102 
103   /**
104    * Returns the process' unique identifier, or {@code null} if no such identifier could be
105    * retrieved. Note that all processes run by the same Java runtime may share the same UUID.
106    *
107    * @return The UUID, or null.
108    */
109   public UUID getUUID() {
110     return uuid;
111   }
112 
113   void setUUID(String uuidStr) {
114     this.uuid = UUID.fromString(uuidStr);
115   }
116 
117   void setGids(long[] gids) {
118     this.gids = gids.clone();
119   }
120 
121   /**
122    * Checks if neither of the possible peer credentials are set.
123    *
124    * @return {@code true} if no credentials set.
125    */
126   public boolean isEmpty() {
127     return pid == -1 && uid == -1 && (gids == null || gids.length == 0) && uuid == null;
128   }
129 
130   @Override
131   public String toString() {
132     StringBuilder sb = new StringBuilder();
133     sb.append(super.toString());
134     sb.append('[');
135     if (this == SAME_PROCESS) { // NOPMD: CompareObjectsWithEquals
136       sb.append("(same process)]");
137       return sb.toString();
138     }
139     if (pid != -1) {
140       sb.append("pid=");
141       sb.append(pid);
142       sb.append(';');
143     }
144     if (uid != -1) {
145       sb.append("uid=");
146       sb.append(uid);
147       sb.append(';');
148     }
149     if (gids != null) {
150       sb.append("gids=");
151       sb.append(Arrays.toString(gids));
152       sb.append(';');
153     }
154     if (uuid != null) {
155       sb.append("uuid=");
156       sb.append(uuid);
157       sb.append(';');
158     }
159     if (sb.charAt(sb.length() - 1) == ';') {
160       sb.setLength(sb.length() - 1);
161     }
162     sb.append(']');
163     return sb.toString();
164   }
165 
166   @Override
167   public int hashCode() {
168     final int prime = 31;
169     int result = 1;
170     result = prime * result + Arrays.hashCode(gids);
171     result = prime * result + (int) (pid ^ (pid >>> 32));
172     result = prime * result + (int) (uid ^ (uid >>> 32));
173     result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
174     return result;
175   }
176 
177   @Override
178   @SuppressWarnings("all")
179   public boolean equals(Object obj) {
180     if (this == obj)
181       return true;
182     if (obj == null)
183       return false;
184     if (getClass() != obj.getClass())
185       return false;
186     AFUNIXSocketCredentials other = (AFUNIXSocketCredentials) obj;
187     if (!Arrays.equals(gids, other.gids))
188       return false;
189     if (pid != other.pid)
190       return false;
191     if (uid != other.uid)
192       return false;
193     if (uuid == null) {
194       if (other.uuid != null)
195         return false;
196     } else if (!uuid.equals(other.uuid))
197       return false;
198     return true;
199   }
200 
201   /**
202    * Returns the {@link AFUNIXSocketCredentials} for the currently active remote session, or
203    * {@code null} if it was not possible to retrieve these credentials.
204    *
205    * NOTE: For now, only RMI remote sessions are supported (RemoteServer sessions during a remote
206    * method invocation).
207    *
208    * If you want to retrieve the peer credentials for an RMI server, see junixsocket-rmi's
209    * RemotePeerInfo.
210    *
211    * @return The credentials, or {@code null} if unable to retrieve.
212    */
213   public static AFUNIXSocketCredentials remotePeerCredentials() {
214     try {
215       RemoteServer.getClientHost();
216     } catch (Exception e) {
217       return null;
218     }
219 
220     Socket sock = NativeUnixSocket.currentRMISocket();
221     if (!(sock instanceof AFUNIXSocket)) {
222       return null;
223     }
224     AFUNIXSocket socket = (AFUNIXSocket) sock;
225 
226     try {
227       return socket.getPeerCredentials();
228     } catch (IOException e) {
229       return null;
230     }
231   }
232 }