1package com.android.server.wifi.anqp;
2
3import com.android.server.wifi.SIMAccessor;
4import com.android.server.wifi.hotspot2.AuthMatch;
5import com.android.server.wifi.hotspot2.Utils;
6import com.android.server.wifi.hotspot2.pps.Credential;
7import com.android.server.wifi.hotspot2.pps.HomeSP;
8
9import java.net.ProtocolException;
10import java.nio.ByteBuffer;
11import java.util.ArrayList;
12import java.util.Collections;
13import java.util.List;
14
15import static com.android.server.wifi.anqp.Constants.BYTES_IN_SHORT;
16import static com.android.server.wifi.anqp.Constants.SHORT_MASK;
17
18/**
19 * The NAI Realm ANQP Element, IEEE802.11-2012 section 8.4.4.10
20 */
21public class NAIRealmElement extends ANQPElement {
22    private final List<NAIRealmData> mRealmData;
23
24    public NAIRealmElement(Constants.ANQPElementType infoID, ByteBuffer payload)
25            throws ProtocolException {
26        super(infoID);
27
28        if (!payload.hasRemaining()) {
29            mRealmData = Collections.emptyList();
30            return;
31        }
32
33        if (payload.remaining() < BYTES_IN_SHORT) {
34            throw new ProtocolException("Runt NAI Realm: " + payload.remaining());
35        }
36
37        int count = payload.getShort() & SHORT_MASK;
38        mRealmData = new ArrayList<>(count);
39        while (count > 0) {
40            mRealmData.add(new NAIRealmData(payload));
41            count--;
42        }
43    }
44
45    public List<NAIRealmData> getRealmData() {
46        return Collections.unmodifiableList(mRealmData);
47    }
48
49    public int match(Credential credential) {
50        if (mRealmData.isEmpty())
51            return AuthMatch.Indeterminate;
52
53        List<String> credLabels = Utils.splitDomain(credential.getRealm());
54        int best = AuthMatch.None;
55        for (NAIRealmData realmData : mRealmData) {
56            int match = realmData.match(credLabels, credential);
57            if (match > best) {
58                best = match;
59                if (best == AuthMatch.Exact) {
60                    return best;
61                }
62            }
63        }
64        return best;
65    }
66
67    @Override
68    public String toString() {
69        StringBuilder sb = new StringBuilder();
70        sb.append("NAI Realm:\n");
71        for (NAIRealmData data : mRealmData) {
72            sb.append(data);
73        }
74        return sb.toString();
75    }
76}
77