1 package com.ericsson.research.transport.ws.spi;
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 import java.io.IOException;
37 import java.io.OutputStream;
38
39 import com.ericsson.research.transport.ws.WSException;
40
41 public class WSHixie75Handshake extends WSAbstractHandshake implements WSConstants {
42
43 protected static final String SERVER_PREAMBLE = HTTP11 + " 101 Web Socket Protocol Handshake";
44 protected static final String COMMON_PART = CRLF+UPGRADE_HEADER+COLON_SPACE+WEBSOCKET_VALUE+CRLF+CONNECTION_HEADER+COLON_SPACE+UPGRADE_VALUE+CRLF;
45
46 public WSHixie75Handshake(WSAbstractProtocol protocol) {
47 super(protocol);
48 }
49
50 public void sendHandshake(OutputStream os) throws IOException {
51 StringBuffer h = new StringBuffer();
52 if(protocol.client) {
53 h.append(GET);
54 h.append(" ");
55 h.append(protocol.resource);
56 h.append(" ");
57 h.append(HTTP11);
58 h.append(COMMON_PART);
59 h.append(HOST_HEADER);
60 h.append(COLON_SPACE);
61 h.append(protocol.host);
62 if ((protocol.securityContext==null && protocol.port!=80) || (protocol.securityContext!=null && protocol.port!=443)) {
63 h.append(":");
64 h.append(protocol.port);
65 }
66 h.append(CRLF);
67 h.append(ORIGIN_HEADER);
68 h.append(COLON_SPACE);
69 h.append(protocol.origin);
70 h.append(CRLFCRLF);
71 } else {
72 h.append(SERVER_PREAMBLE);
73 h.append(COMMON_PART);
74 h.append(WEBSOCKET_ORIGIN_HEADER);
75 h.append(COLON_SPACE);
76 h.append(protocol.origin);
77 h.append(CRLF);
78 h.append(WEBSOCKET_LOCATION_HEADER);
79 h.append(COLON_SPACE);
80 h.append(protocol.location);
81 h.append(CRLFCRLF);
82 }
83 synchronized(os) {
84 os.write(h.toString().getBytes(ISO_8859_1));
85 os.flush();
86 }
87 }
88
89 public void headersRead() throws WSException {
90 if(protocol.client) {
91 if(!protocol.origin.equals(getHeader(WEBSOCKET_ORIGIN_HEADER)))
92 throw new WSException("Failed to match origin ("+protocol.origin+" != "+getHeader(WEBSOCKET_ORIGIN_HEADER)+")");
93 StringBuffer location = new StringBuffer();
94 if(protocol.securityContext!=null)
95 location.append(WSS_SCHEMA);
96 else
97 location.append(WS_SCHEMA);
98 location.append(protocol.host);
99 if((protocol.securityContext==null && protocol.port != 80) || (protocol.securityContext!=null && protocol.port != 443)) {
100 location.append(":");
101 location.append(protocol.port);
102 }
103 location.append(protocol.resource);
104 if (!location.toString().equals(getHeader(WEBSOCKET_LOCATION_HEADER)))
105 throw new WSException("Failed to match location ("+location+" != "+getHeader(WEBSOCKET_LOCATION_HEADER)+")");
106 } else {
107 protocol.origin = getHeader(ORIGIN_HEADER);
108 StringBuffer loc = new StringBuffer();
109 if(protocol.securityContext!=null)
110 loc.append(WSS_SCHEMA);
111 else
112 loc.append(WS_SCHEMA);
113 loc.append(getHeader(HOST_HEADER));
114 loc.append(protocol.resource);
115 protocol.location = loc.toString();
116 }
117 }
118
119 }