Skip to main content
summaryrefslogtreecommitdiffstats
blob: a3b92114c77a1fddb4a6f15d9d2d498a21d43ca2 (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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
/*
 * Copyright (c) 2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.userstorage.tests.util;

import org.eclipse.userstorage.internal.util.IOUtil;
import org.eclipse.userstorage.internal.util.JSONUtil;
import org.eclipse.userstorage.internal.util.StringUtil;
import org.eclipse.userstorage.spi.Credentials;
import org.eclipse.userstorage.tests.StorageTests;

import org.eclipse.core.runtime.Path;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author Eike Stepper
 */
public final class USSServer
{
  public static final String BLOB_EXTENSION = ".blob";

  public static final String ETAG_EXTENSION = ".etag";

  private static final boolean DEBUG = Boolean.getBoolean("org.eclipse.userstorage.tests.server.debug");

  private final USSHandler handler = new USSHandler();

  private final Set<String> applicationTokens = new HashSet<String>();

  private final Map<String, User> users = new HashMap<String, User>();

  private final Map<String, Session> sessions = new HashMap<String, Session>();

  private final File folder;

  private final int startPort;

  private int port;

  private Server server;

  public USSServer(int startPort, File folder)
  {
    this.startPort = startPort;
    this.folder = folder;
  }

  public int getPort()
  {
    return port;
  }

  public File getFolder()
  {
    return folder;
  }

  public Set<String> getApplicationTokens()
  {
    return applicationTokens;
  }

  public Map<String, User> getUsers()
  {
    return users;
  }

  public User addUser(Credentials credentials)
  {
    return addUser(credentials.getUsername(), credentials.getPassword());
  }

  public User addUser(String username, String password)
  {
    User user = new User(username, password);
    users.put(user.getUsername(), user);
    return user;
  }

  public File getUserFile(User user, String applicationToken, String key, String extension)
  {
    return new File(getApplicationFolder(user, applicationToken), key + StringUtil.safe(extension));
  }

  public File getApplicationFolder(User user, String applicationToken)
  {
    return new File(new File(folder, user.getUsername()), applicationToken);
  }

  public Map<String, Session> getSessions()
  {
    return sessions;
  }

  public int start() throws Exception
  {
    Exception exception = new Exception("No free port");

    for (port = startPort; port < 65535; port++)
    {
      server = new Server(port);
      server.setHandler(handler);

      try
      {
        server.start();
        return port;
      }
      catch (Exception ex)
      {
        exception = ex;

        try
        {
          server.stop();
        }
        catch (Exception ignore)
        {
          //$FALL-THROUGH$
        }
        finally
        {
          server = null;
        }
      }
    }

    throw exception;
  }

  public void stop() throws Exception
  {
    if (server != null)
    {
      server.stop();
      server = null;
    }
  }

  public void join() throws InterruptedException
  {
    if (server != null)
    {
      server.join();
    }
  }

  protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException
  {
    Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), null);

    String username = (String)requestObject.get("username");
    String password = (String)requestObject.get("password");

    User user = users.get(username);
    if (user == null || password == null || !password.equals(user.getPassword()))
    {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    Session session = addSession(user);
    Cookie cookie = new Cookie("SESSION", session.getID());
    cookie.setPath("/");
    response.addCookie(cookie);

    Map<String, Object> responseObject = new LinkedHashMap<String, Object>();
    responseObject.put("sessid", session.getID());
    responseObject.put("token", session.getCSRFToken());
    InputStream body = JSONUtil.build(responseObject);

    try
    {
      ServletOutputStream out = response.getOutputStream();
      IOUtil.copy(body, out);
      out.flush();
    }
    finally
    {
      IOUtil.closeSilent(body);
    }
  }

  protected void retrieveProperties(HttpServletRequest request, HttpServletResponse response, File applicationFolder) throws IOException
  {
    if (!applicationFolder.isDirectory())
    {
      response.sendError(422);
      return;
    }

    String applicationToken = applicationFolder.getName();

    int pageSize = getIntParameter(request, "pageSize", 20);
    if (pageSize < 1 || pageSize > 100)
    {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page size");
      return;
    }

    int page = getIntParameter(request, "page", 20);
    if (page < 1)
    {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page");
      return;
    }

    boolean empty = true;

    StringBuilder builder = new StringBuilder();
    builder.append('[');

    File[] files = applicationFolder.listFiles();
    if (files != null)
    {
      int first = (page - 1) * pageSize + 1;
      System.out.println("##### " + first);
      int i = 0;

      for (File file : files)
      {
        String name = file.getName();
        if (name.endsWith(ETAG_EXTENSION))
        {
          if (++i >= first)
          {
            String key = name.substring(0, name.length() - ETAG_EXTENSION.length());
            System.out.println("##### " + key);
            String etag = IOUtil.readUTF(file);

            if (empty)
            {
              empty = false;
            }
            else
            {
              builder.append(",");
            }

            builder.append("{\"application_token\":\"");
            builder.append(applicationToken);
            builder.append("\",\"key\":\"");
            builder.append(key);
            builder.append("\",\"etag\":\"");
            builder.append(etag);
            builder.append("\"}");

            if (--pageSize == 0)
            {
              break;
            }
          }
        }
      }
    }

    if (empty)
    {
      response.sendError(422);
      return;
    }

    builder.append(']');
    System.out.println(builder);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    InputStream body = IOUtil.streamUTF(builder.toString());

    try
    {
      ServletOutputStream out = response.getOutputStream();
      IOUtil.copy(body, out);
      out.flush();
    }
    finally
    {
      IOUtil.closeSilent(body);
    }
  }

  protected void retrieveBlob(HttpServletRequest request, HttpServletResponse response, File blobFile, File etagFile, boolean exists) throws IOException
  {
    if (!exists)
    {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    String etag = IOUtil.readUTF(etagFile);
    String ifNoneMatch = getETag(request, "If-None-Match");
    if (ifNoneMatch != null && ifNoneMatch.equals(etag))
    {
      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");
    response.setHeader("ETag", "\"" + etag + "\"");

    InputStream body = JSONUtil.build(Collections.singletonMap("value", new FileInputStream(blobFile)));

    try
    {
      ServletOutputStream out = response.getOutputStream();
      IOUtil.copy(body, out);
      out.flush();
    }
    finally
    {
      IOUtil.closeSilent(body);
    }
  }

  protected void updateBlob(HttpServletRequest request, HttpServletResponse response, File blobFile, File etagFile, boolean exists) throws IOException
  {
    if (exists)
    {
      String etag = IOUtil.readUTF(etagFile);
      String ifMatch = getETag(request, "If-Match");
      if (ifMatch != null && !ifMatch.equals(etag))
      {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
      }
    }

    String etag = UUID.randomUUID().toString();

    IOUtil.mkdirs(blobFile.getParentFile());
    FileOutputStream out = new FileOutputStream(blobFile);
    InputStream body = null;

    try
    {
      Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), "value");
      body = (InputStream)requestObject.get("value");

      IOUtil.copy(body, out);
    }
    finally
    {
      IOUtil.closeSilent(body);
      IOUtil.close(out);
    }

    IOUtil.writeUTF(etagFile, etag);

    response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
    response.setHeader("ETag", "\"" + etag + "\"");
  }

  protected void deleteBlob(HttpServletRequest request, HttpServletResponse response, File blobFile, File etagFile, boolean exists) throws IOException
  {
    if (exists)
    {
      String etag = IOUtil.readUTF(etagFile);
      String ifMatch = getETag(request, "If-Match");
      if (ifMatch != null && !ifMatch.equals(etag))
      {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
      }
    }
    else
    {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    IOUtil.delete(blobFile);
    IOUtil.delete(etagFile);

    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
  }

  private Session getSession(HttpServletRequest request)
  {
    String csrfToken = request.getHeader("X-CSRF-Token");
    if (csrfToken != null)
    {
      Cookie[] cookies = request.getCookies();
      if (cookies != null)
      {
        for (Cookie cookie : cookies)
        {
          if ("SESSION".equals(cookie.getName()))
          {
            String sessionID = cookie.getValue();
            Session session = sessions.get(sessionID);

            if (session != null && session.getCSRFToken().equals(csrfToken))
            {
              return session;
            }

            break;
          }
        }
      }
    }

    return null;
  }

  private Session addSession(User user)
  {
    Session session = new Session(user);
    sessions.put(session.getID(), session);
    return session;
  }

  private static String getETag(HttpServletRequest request, String headerName)
  {
    String eTag = request.getHeader(headerName);
    if (eTag != null)
    {
      // Remove the quotes.
      eTag = eTag.substring(1, eTag.length() - 1);
    }

    return eTag;
  }

  @SuppressWarnings("restriction")
  private static String getReasonPhrase(int status)
  {
    try
    {
      return org.apache.http.impl.EnglishReasonPhraseCatalog.INSTANCE.getReason(status, null);
    }
    catch (Throwable ex)
    {
      return "";
    }
  }

  private static int getIntParameter(HttpServletRequest request, String name, int defaultValue)
  {
    String parameter = request.getParameter(name);
    if (parameter != null)
    {
      try
      {
        return Integer.parseInt(parameter);
      }
      catch (NumberFormatException ex)
      {
        //$FALL-THROUGH$
      }
    }

    return defaultValue;
  }

  /**
   * @author Eike Stepper
   */
  private class USSHandler extends AbstractHandler
  {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
      try
      {
        baseRequest.setHandled(true);

        String userAgent = request.getHeader("User-Agent");
        if (!org.eclipse.userstorage.internal.Session.USER_AGENT_ID.equals(userAgent))
        {
          response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid User-Agent");
          return;
        }

        String method = request.getMethod();
        String path = request.getPathInfo();

        if (DEBUG)
        {
          StringBuilder builder = new StringBuilder();
          builder.append(method);
          builder.append(" ");
          builder.append(path);
          builder.append('\n');

          Enumeration<String> headerNames = request.getHeaderNames();
          while (headerNames.hasMoreElements())
          {
            String headerName = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(headerName);
            while (headers.hasMoreElements())
            {
              String header = headers.nextElement();
              builder.append("   ");
              builder.append(headerName);
              builder.append(": ");
              builder.append(header);
              builder.append('\n');
            }
          }

          System.out.print(builder);
          System.out.flush();
        }

        if (path != null && method != null)
        {
          handle(method, path, request, response);

          if (DEBUG)
          {
            int status = response.getStatus();
            String reasonPhrase = getReasonPhrase(status);

            StringBuilder builder = new StringBuilder();
            builder.append(request.getProtocol());
            builder.append(" ");
            builder.append(status);
            if (!StringUtil.isEmpty(reasonPhrase))
            {
              builder.append(" ");
              builder.append(reasonPhrase);
            }

            builder.append('\n');

            for (String headerName : response.getHeaderNames())
            {
              for (String header : response.getHeaders(headerName))
              {
                builder.append("   ");
                builder.append(headerName);
                builder.append(": ");
                builder.append(header);
                builder.append('\n');
              }
            }

            System.out.println(builder);
          }
        }
      }
      catch (IOException ex)
      {
        ex.printStackTrace();
        throw ex;
      }
      catch (RuntimeException ex)
      {
        ex.printStackTrace();
        throw ex;
      }
    }

    private void handle(String method, String path, HttpServletRequest request, HttpServletResponse response) throws IOException
    {
      if (path.equals("/api/user/login") && HttpMethod.POST.is(method))
      {
        login(request, response);
        return;
      }

      Session session = getSession(request);
      if (session == null)
      {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
      }

      if (path.startsWith("/api/blob"))
      {
        User user = session.getUser();
        Path segments = new Path(path);

        String applicationToken = segments.segment(2);
        if (!applicationTokens.contains(applicationToken))
        {
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }

        if (segments.segmentCount() < 4)
        {
          if (HttpMethod.GET.is(method))
          {
            File applicationFolder = getApplicationFolder(user, applicationToken);
            retrieveProperties(request, response, applicationFolder);
            return;
          }

          response.sendError(HttpServletResponse.SC_FORBIDDEN);
          return;
        }

        String key = segments.segment(3);
        File blobFile = getUserFile(user, applicationToken, key, BLOB_EXTENSION);
        File etagFile = getUserFile(user, applicationToken, key, ETAG_EXTENSION);
        boolean exists = etagFile.exists();

        if (HttpMethod.GET.is(method))
        {
          retrieveBlob(request, response, blobFile, etagFile, exists);
          return;
        }

        if (HttpMethod.PUT.is(method))
        {
          updateBlob(request, response, blobFile, etagFile, exists);
          return;
        }

        if (HttpMethod.DELETE.is(method))
        {
          deleteBlob(request, response, blobFile, etagFile, exists);
          return;
        }

        return;
      }

      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }

  /**
  * @author Eike Stepper
  */
  public static final class User
  {
    private final String username;

    private final byte[] password;

    public User(String username, String password)
    {
      this.username = username;
      this.password = StringUtil.encrypt(password);
    }

    public String getUsername()
    {
      return username;
    }

    public String getPassword()
    {
      return StringUtil.decrypt(password);
    }

    @Override
    public String toString()
    {
      return username;
    }

    @Override
    public int hashCode()
    {
      return username.hashCode();
    }

    @Override
    public boolean equals(Object obj)
    {
      if (this == obj)
      {
        return true;
      }

      if (obj == null)
      {
        return false;
      }

      if (getClass() != obj.getClass())
      {
        return false;
      }

      User other = (User)obj;
      if (username == null)
      {
        if (other.username != null)
        {
          return false;
        }
      }
      else if (!username.equals(other.username))
      {
        return false;
      }

      return true;
    }
  }

  /**
  * @author Eike Stepper
  */
  public static final class Session
  {
    private final String id;

    private final String csrfToken;

    private final User user;

    public Session(User user)
    {
      id = UUID.randomUUID().toString();
      csrfToken = UUID.randomUUID().toString();
      this.user = user;
    }

    public String getID()
    {
      return id;
    }

    public String getCSRFToken()
    {
      return csrfToken;
    }

    public User getUser()
    {
      return user;
    }

    @Override
    public int hashCode()
    {
      return id.hashCode();
    }

    @Override
    public boolean equals(Object obj)
    {
      if (this == obj)
      {
        return true;
      }

      if (obj == null)
      {
        return false;
      }

      if (getClass() != obj.getClass())
      {
        return false;
      }

      Session other = (Session)obj;
      if (id == null)
      {
        if (other.id != null)
        {
          return false;
        }
      }
      else if (!id.equals(other.id))
      {
        return false;
      }

      return true;
    }

    @Override
    public String toString()
    {
      return id + " -> " + user;
    }
  }

  /**
   * @author Eike Stepper
   */
  public static class NOOPLogger implements Logger
  {
    @Override
    public String getName()
    {
      return "noop";
    }

    @Override
    public void warn(String msg, Object... args)
    {
    }

    @Override
    public void warn(Throwable thrown)
    {
    }

    @Override
    public void warn(String msg, Throwable thrown)
    {
    }

    @Override
    public void info(String msg, Object... args)
    {
    }

    @Override
    public void info(Throwable thrown)
    {
    }

    @Override
    public void info(String msg, Throwable thrown)
    {
    }

    @Override
    public boolean isDebugEnabled()
    {
      return false;
    }

    @Override
    public void setDebugEnabled(boolean enabled)
    {
    }

    @Override
    public void debug(String msg, Object... args)
    {
    }

    @Override
    public void debug(Throwable thrown)
    {
    }

    @Override
    public void debug(String msg, Throwable thrown)
    {
    }

    @Override
    public void debug(String msg, long value)
    {
    }

    @Override
    public Logger getLogger(String name)
    {
      return this;
    }

    @Override
    public void ignore(Throwable ignored)
    {
    }
  }

  public static void main(String[] args) throws Exception
  {
    Log.setLog(new NOOPLogger());

    USSServer server = new USSServer(8080, new File(System.getProperty("java.io.tmpdir"), "uss-server"));
    server.addUser(FixedCredentialsProvider.DEFAULT_CREDENTIALS);

    Set<String> applicationTokens = server.getApplicationTokens();
    applicationTokens.add(StorageTests.APPLICATION_TOKEN);
    applicationTokens.add("cNhDr0INs8T109P8h6E1r_GvU3I"); // Oomph

    System.out.println(server.getFolder());
    System.out.println("Listening on port " + server.start());
    server.join();
  }
}

Back to the top