@@ -116,9 +116,9 @@ private Collection<Cookie> getCookies(HttpRequest request) {
116
116
private void addCookie (HttpResponse response , Cookie cook ) {
117
117
StringBuilder cookie = new StringBuilder ();
118
118
119
- // TODO: escape string as necessary
120
- String name = cook .getName ( );
121
- cookie .append (name ).append ("=" ).append (cook . getValue () ).append ("; " );
119
+ String name = escapeCookieValue ( cook . getName ());
120
+ String value = escapeCookieValue ( cook .getValue () );
121
+ cookie .append (name ).append ("=" ).append (value ).append ("; " );
122
122
123
123
append (cookie , cook .getDomain (), str -> "Domain=" + str );
124
124
append (cookie , cook .getPath (), str -> "Path=" + str );
@@ -191,4 +191,45 @@ private Cookie parse(String cookieString) {
191
191
192
192
return builder .build ();
193
193
}
194
+
195
+ private String escapeCookieValue (String value ) {
196
+ if (value == null || value .isEmpty ()) {
197
+ return "" ;
198
+ }
199
+
200
+ StringBuilder cookieValue = new StringBuilder ();
201
+
202
+ for (char c : value .toCharArray ()) {
203
+ switch (c ) {
204
+ case '\\' :
205
+ cookieValue .append ("\\ \\ " );
206
+ break ;
207
+ case '"' :
208
+ cookieValue .append ("\\ \" " );
209
+ break ;
210
+ case ';' :
211
+ cookieValue .append ("\\ ;" );
212
+ break ;
213
+ case ',' :
214
+ cookieValue .append ("\\ ," );
215
+ break ;
216
+ case '\r' :
217
+ case '\n' :
218
+ // Skip carriage return and newline characters
219
+ break ;
220
+ case '<' :
221
+ cookieValue .append ("<" );
222
+ break ;
223
+ case '>' :
224
+ cookieValue .append (">" );
225
+ break ;
226
+ case '&' :
227
+ cookieValue .append ("&" );
228
+ break ;
229
+ default :
230
+ cookieValue .append (c ); // Append safe characters as they are
231
+ }
232
+ }
233
+ return cookieValue .toString ();
234
+ }
194
235
}
0 commit comments