-
Notifications
You must be signed in to change notification settings - Fork 40.2k
/
Connection.java
164 lines (141 loc) · 5.21 KB
/
Connection.java
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
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.livereload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
/**
* A {@link LiveReloadServer} connection.
*
* @author Phillip Webb
* @author Francis Lavoie
*/
class Connection {
private static final Log logger = LogFactory.getLog(Connection.class);
private static final Pattern WEBSOCKET_KEY_PATTERN = Pattern.compile("^sec-websocket-key:(.*)$",
Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
public static final String WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private final Socket socket;
private final ConnectionInputStream inputStream;
private final ConnectionOutputStream outputStream;
private final String header;
private volatile boolean webSocket;
private volatile boolean running = true;
/**
* Create a new {@link Connection} instance.
* @param socket the source socket
* @param inputStream the socket input stream
* @param outputStream the socket output stream
* @throws IOException in case of I/O errors
*/
Connection(Socket socket, InputStream inputStream, OutputStream outputStream) throws IOException {
this.socket = socket;
this.inputStream = new ConnectionInputStream(inputStream);
this.outputStream = new ConnectionOutputStream(outputStream);
String header = this.inputStream.readHeader();
logger.debug(LogMessage.format("Established livereload connection [%s]", header));
this.header = header;
}
/**
* Run the connection.
* @throws Exception in case of errors
*/
void run() throws Exception {
String lowerCaseHeader = this.header.toLowerCase();
if (lowerCaseHeader.contains("upgrade: websocket") && lowerCaseHeader.contains("sec-websocket-version: 13")) {
runWebSocket();
}
if (lowerCaseHeader.contains("get /livereload.js")) {
this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"), "text/javascript");
}
}
private void runWebSocket() throws Exception {
String accept = getWebsocketAcceptResponse();
this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade",
"Sec-WebSocket-Accept: " + accept);
new Frame("{\"command\":\"hello\",\"protocols\":[\"http://livereload.com/protocols/official-7\"],"
+ "\"serverName\":\"spring-boot\"}").write(this.outputStream);
Thread.sleep(100);
this.webSocket = true;
while (this.running) {
readWebSocketFrame();
}
}
private void readWebSocketFrame() throws IOException {
try {
Frame frame = Frame.read(this.inputStream);
if (frame.getType() == Frame.Type.PING) {
writeWebSocketFrame(new Frame(Frame.Type.PONG));
}
else if (frame.getType() == Frame.Type.CLOSE) {
throw new ConnectionClosedException();
}
else if (frame.getType() == Frame.Type.TEXT) {
logger.debug(LogMessage.format("Received LiveReload text frame %s", frame));
}
else {
throw new IOException("Unexpected Frame Type " + frame.getType());
}
}
catch (SocketTimeoutException ex) {
writeWebSocketFrame(new Frame(Frame.Type.PING));
Frame frame = Frame.read(this.inputStream);
if (frame.getType() != Frame.Type.PONG) {
throw new IllegalStateException("No Pong");
}
}
}
/**
* Trigger livereload for the client using this connection.
* @throws IOException in case of I/O errors
*/
void triggerReload() throws IOException {
if (this.webSocket) {
logger.debug("Triggering LiveReload");
writeWebSocketFrame(new Frame("{\"command\":\"reload\",\"path\":\"/\"}"));
}
}
private void writeWebSocketFrame(Frame frame) throws IOException {
frame.write(this.outputStream);
}
private String getWebsocketAcceptResponse() throws NoSuchAlgorithmException {
Matcher matcher = WEBSOCKET_KEY_PATTERN.matcher(this.header);
Assert.state(matcher.find(), "No Sec-WebSocket-Key");
String response = matcher.group(1).trim() + WEBSOCKET_GUID;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
messageDigest.update(response.getBytes(), 0, response.length());
return Base64Utils.encodeToString(messageDigest.digest());
}
/**
* Close the connection.
* @throws IOException in case of I/O errors
*/
void close() throws IOException {
this.running = false;
this.socket.close();
}
}