aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/identity/Identity.java
blob: 901bd4c6cd282de16c3b83ad4426d2a70ab9c416 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*
 This file is part of GNUnet.
  Copyright (C) 2012, 2013 Christian Grothoff (and other contributing authors)

  GNUnet is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3, or (at your
  option) any later version.

  GNUnet is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GNUnet; see the file COPYING.  If not, write to the
  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
 */

package org.gnunet.identity;


import com.google.common.collect.Lists;
import org.gnunet.identity.messages.*;
import org.gnunet.mq.Envelope;
import org.gnunet.requests.Request;
import org.gnunet.requests.RequestIdentifier;
import org.gnunet.requests.SequentialRequestContainer;
import org.gnunet.util.*;
import org.gnunet.util.crypto.EcdsaPrivateKey;
import org.gnunet.util.crypto.EcdsaPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Make requests to the identity service.
 */
public class Identity {
    private static final Logger logger = LoggerFactory
            .getLogger(Identity.class);
    private Configuration configuration;
    private SequentialRequestContainer<IdentityRequest> requests;
    private Client client;
    private IdentityListCallback identityListCallback;
    private List<Ego> knownEgos = Lists.newLinkedList();

    private static Ego anonymousEgo;

    /**
     * Look up the given ego name.
     *
     * @param configuration configuration to use for connecting to
     *                      the identity service
     * @param egoName ego name to look up
     * @param identityCallback handler for lookup result
     * @return a handle to cancel the lookup
     */
    public static Cancelable lookup(Configuration configuration,
                                    final String egoName, final IdentityCallback identityCallback) {
        final Identity myIdentity = new Identity();
        final CancellationToken cancellationToken = new CancellationToken();
        myIdentity.connect(configuration, new IdentityListCallback() {
            boolean done = false;
            @Override
            public void onEgoAdd(Ego ego) {
                if (done) {
                    throw new AssertionError();
                }
                if (ego.name.equals(egoName)) {
                    done = true;
                    cancellationToken.cancel();
                    identityCallback.onEgo(ego);
                }
            }

            @Override
            public void onEgoDelete(Ego ego) {
                if (done) {
                    throw new AssertionError();
                }
                logger.error("unsolicited ego delete on lookup");
                done = true;
                cancellationToken.cancel();
                identityCallback.onError("identity service misbehaved");
            }

            @Override
            public void onEgoRename(String oldName, Ego ego) {
                if (done) {
                    throw new AssertionError();
                }
                logger.error("unsolicited ego rename on lookup");
                done = true;
                cancellationToken.cancel();
                identityCallback.onError("identity service misbehaved");
            }

            @Override
            public void onListEnd() {
                if (done) {
                    throw new AssertionError();
                }
                done = true;
                cancellationToken.cancel();
                identityCallback.onError("identity not found");

            }
        });
        cancellationToken.add(new Cancelable() {
            @Override
            public void cancel() {
                myIdentity.disconnect();
            }
        });
        return cancellationToken;
    }

    /**
     * An ego.
     */
    public static class Ego {
        private String name;
        private EcdsaPrivateKey privateKey;

        /**
         * Create an ego with the given name and private key.
         *
         * @param egoName the ego name
         * @param privateKey the ego's private key
         */
        public Ego(String egoName, EcdsaPrivateKey privateKey) {
            this.name = egoName;
            this.privateKey = privateKey;
        }

        /**
         * Get the ego's private key.
         *
         * @return the ego's private key
         */
        public EcdsaPrivateKey getPrivateKey() {
            return privateKey;
        }

        /**
         * Compute the ego's public key from its private key.
         *
         * @return the ego's public key
         */
        public EcdsaPublicKey getPublicKey() {
            return privateKey.getPublicKey();
        }

        /**
         * Get the ego's name.
         *
         * @return the ego's name
         */
        public String getName() {
            return name;
        }
    }

    public abstract class IdentityRequest extends Request {

        public void onError(String errorMessage) {
            throw new AssertionError("unexpected error message: " + errorMessage);
        }

        public void onResult() {
            throw new AssertionError("unexpected result");
        }
    }

    public class GetDefaultRequest extends IdentityRequest {
        IdentityCallback identityCallback;
        String serviceName;
        GetDefaultRequest(String serviceName, IdentityCallback identityCallback) {
            this.identityCallback = identityCallback;
            this.serviceName = serviceName;
        }
        @Override
        public Envelope assembleRequest() {
            GetDefaultMessage m = new GetDefaultMessage();
            m.nameLength = serviceName.length() + 1;
            m.serviceName = serviceName;
            return new Envelope(m);
        }

        @Override
        public void onError(String errorMessage) {
            identityCallback.onError(errorMessage);
        }
    }

    public class SetDefaultRequest extends IdentityRequest {
        IdentityContinuation cont;
        String serviceName;
        Ego ego;
        SetDefaultRequest(String serviceName, Ego ego) {
            this.serviceName = serviceName;
            this.ego = ego;
        }
        @Override
        public Envelope assembleRequest() {
            SetDefaultMessage m = new SetDefaultMessage();
            m.nameLength = serviceName.length() + 1;
            m.serviceName = serviceName;
            m.privateKey = ego.privateKey;
            return new Envelope(m);
        }
        @Override
        public void onError(String errorMessage) {
            cont.onError(errorMessage);
        }
        @Override
        public void onResult() {
            cont.onDone();
        }
    }

    public class RenameRequest extends IdentityRequest {
        IdentityContinuation cont;
        String oldName;
        String newName;
        RenameRequest(String newName, String oldName) {
            this.oldName = oldName;
            this.newName = newName;
        }
        @Override
        public Envelope assembleRequest() {
            RenameMessage m = new RenameMessage();
            m.newName = newName;
            m.newNameLength = newName.length() + 1;
            m.oldName = oldName;
            m.oldNameLength = oldName.length() + 1;
            return new Envelope(m);
        }
        @Override
        public void onError(String errorMessage) {
            cont.onError(errorMessage);
        }
        @Override
        public void onResult() {
            cont.onDone();
        }
    }

    public class DeleteRequest extends IdentityRequest {
        IdentityContinuation cont;
        String name;
        DeleteRequest(String name) {
            this.name = name;
        }
        @Override
        public Envelope assembleRequest() {
            DeleteMessage m = new DeleteMessage();
            m.name = name;
            m.nameLength = name.length() + 1;
            return new Envelope(m);
        }
        @Override
        public void onError(String errorMessage) {
            cont.onError(errorMessage);
        }
        @Override
        public void onResult() {
            cont.onDone();
        }
    }

    public class CreateRequest extends IdentityRequest {
        final EcdsaPrivateKey privateKey;
        IdentityContinuation cont;
        String name;
        CreateRequest(String name, EcdsaPrivateKey privateKey, IdentityContinuation cont) {
            this.cont = cont;
            this.privateKey = privateKey;
            this.name = name;
        }
        @Override
        public Envelope assembleRequest() {
            CreateRequestMessage m = new CreateRequestMessage();
            m.name = name;
            m.nameLength = name.length() + 1;
            m.privateKey = privateKey;
            return new Envelope(m);
        }
        @Override
        public void onError(String errorMessage) {
            cont.onError(errorMessage);
        }

        @Override
        public void onResult() {
            cont.onDone();
        }
    }

    /**
     * Get the anonymous ego.  The anonymous ego has a publicly
     * known private key.
     *
     * @return the anonymous ego
     */
    public static Ego getAnonymousEgo() {
        if (anonymousEgo == null) {
            anonymousEgo = new Ego(null, EcdsaPrivateKey.getAnonymous());
        }
        return anonymousEgo;
    }


    /**
     * Create a handle that can connect to the identity service.
     * Nothing will happen until calling connect.
     */
    public Identity() {
        // do nothing
    }

    /**
     * Connect to the identity service.
     *
     * @param configuration configuration to use
     * @param identityListCallback callback that receives initially the list of all egos,
     *                             and subsequently changes to egos
     */
    public void connect(Configuration configuration, IdentityListCallback identityListCallback) {
        this.configuration = configuration;
        this.client = new Client("identity", configuration);
        this.client.installReceiver(new IdentityReceiver());
        requests = new SequentialRequestContainer<IdentityRequest>(this.client);
        this.identityListCallback = identityListCallback;
        StartMessage m = new StartMessage();
        client.send(m);
    }

    /**
     * Get the default ego for a service
     *
     * @param serviceName name of the service
     * @param identityCallback callback that receives the default ego
     * @return a handle to cancel the operation
     */
    public Cancelable get(String serviceName, IdentityCallback identityCallback) {
        return requests.addRequest(new GetDefaultRequest(serviceName, identityCallback));
    }

    /**
     * Set the default ego for a service.
     *
     * @param serviceName service
     * @param ego ego
     * @return object for cancellation
     */
    public Cancelable set(String serviceName, Ego ego) {
        return requests.addRequest(new SetDefaultRequest(serviceName, ego));
    }

    /**
     * Disconnect from the identity service.
     */
    public void disconnect() {
        client.disconnect();
        client = null;
    }

    /**
     * Create a new ego with the given name.
     *
     * @param name ego name
     * @param cont continuation
     * @return object for cancellation
     */
    public Cancelable create(String name, IdentityContinuation cont) {
        EcdsaPrivateKey privateKey = EcdsaPrivateKey.createRandom();
        return requests.addRequest(new CreateRequest(name, privateKey, cont));
    }

    /**
     * Rename an ego.
     *
     * @param oldName old name of the ego
     * @param newName new name of the ego
     * @return object for cancellation
     */
    public Cancelable rename(String oldName, String newName) {
        return requests.addRequest(new RenameRequest(newName, oldName));
    }

    /**
     * Delete an ego.
     *
     * @param name name of the ego to delete
     * @return object for cancellation
     */
    public Cancelable delete(String name) {
        return requests.addRequest(new DeleteRequest(name));
    }

    private Ego getEgoForKey(EcdsaPrivateKey privateKey) {
        for (Ego ex : knownEgos) {
            if (ex.privateKey.equals(privateKey)) {
                return ex;
            }
        }
        return null;
    }

    public class IdentityReceiver extends RunaboutMessageReceiver {
        @Override
        public void handleError() {
            logger.warn("identity service disconnected");
            // FIXME: should have exp. backoff
            client.reconnect();
        }

        public void visit(ResultCodeMessage m) {
            RequestIdentifier<IdentityRequest> rId = requests.getRequestIdentifier();
            IdentityRequest r = rId.getRequest();
            if (null == r) {
                logger.warn("unsolicited result code message");
                return;
            }
            if (m.errorMessage != null) {
                r.onError(m.errorMessage);
            } else {
                r.onResult();
            }
            rId.retire();
        }

        public void visit(SetDefaultMessage m) {
            RequestIdentifier<IdentityRequest> rId = requests.getRequestIdentifier();
            IdentityRequest r = rId.getRequest();
            if (!(r instanceof GetDefaultRequest)) {
                logger.error("unexpected 'default ego' response");
                return;
            }
            GetDefaultRequest gdr = (GetDefaultRequest) r;
            Ego ego = getEgoForKey(m.privateKey);
            if (null != ego)
                gdr.identityCallback.onEgo(ego);
            rId.retire();
        }

        public void visit(final UpdateListMessage m) {
            if (m.endOfList != 0) {
                if (null != identityListCallback)
                    identityListCallback.onListEnd();
                return;
            }
            if (m.nameLength == 0) {
                Ego e = getEgoForKey(m.privateKey);
                if (null != e) {
                    knownEgos.remove(e);
                }
                if (null != identityListCallback)
                    identityListCallback.onEgoDelete(e);
            } else {
                Ego existingEgo = getEgoForKey(m.privateKey);
                if (existingEgo == null) {
                    Ego ego = new Ego(m.egoName, m.privateKey);
                    knownEgos.add(ego);
                    if (null != identityListCallback)
                        identityListCallback.onEgoAdd(ego);
                } else {
                    // rename
                    String oldName = existingEgo.name;
                    existingEgo.name = m.egoName;
                    if (null != identityListCallback)
                        identityListCallback.onEgoRename(oldName, existingEgo);
                }
            }
        }
    }
}