View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http.cookie;
17  
18  import static io.netty.handler.codec.http.cookie.CookieUtil.add;
19  import static io.netty.handler.codec.http.cookie.CookieUtil.addQuoted;
20  import static io.netty.handler.codec.http.cookie.CookieUtil.stringBuilder;
21  import static io.netty.handler.codec.http.cookie.CookieUtil.stripTrailingSeparator;
22  import static io.netty.handler.codec.http.cookie.CookieUtil.stripTrailingSeparatorOrNull;
23  import static io.netty.util.internal.ObjectUtil.checkNotNull;
24  import io.netty.handler.codec.http.HttpRequest;
25  import io.netty.util.internal.InternalThreadLocalMap;
26  
27  import java.util.Arrays;
28  import java.util.Collection;
29  import java.util.Comparator;
30  import java.util.Iterator;
31  import java.util.List;
32  
33  /**
34   * A <a href="https://tools.ietf.org/html/rfc6265">RFC6265</a> compliant cookie encoder to be used client side, so
35   * only name=value pairs are sent.
36   *
37   * Note that multiple cookies are supposed to be sent at once in a single "Cookie" header.
38   *
39   * <pre>
40   * // Example
41   * {@link HttpRequest} req = ...;
42   * res.setHeader("Cookie", {@link ClientCookieEncoder}.encode("JSESSIONID", "1234"));
43   * </pre>
44   *
45   * @see ClientCookieDecoder
46   */
47  public final class ClientCookieEncoder extends CookieEncoder {
48  
49      /**
50       * Strict encoder that validates that name and value chars are in the valid scope and (for methods that accept
51       * multiple cookies) sorts cookies into order of decreasing path length, as specified in RFC6265.
52       */
53      public static final ClientCookieEncoder STRICT = new ClientCookieEncoder(true);
54  
55      /**
56       * Lax instance that doesn't validate name and value, and (for methods that accept multiple cookies) keeps
57       * cookies in the order in which they were given.
58       */
59      public static final ClientCookieEncoder LAX = new ClientCookieEncoder(false);
60  
61      private ClientCookieEncoder(boolean strict) {
62          super(strict);
63      }
64  
65      /**
66       * Encodes the specified cookie into a Cookie header value.
67       *
68       * @param name
69       *            the cookie name
70       * @param value
71       *            the cookie value
72       * @return a Rfc6265 style Cookie header value
73       */
74      public String encode(String name, String value) {
75          return encode(new DefaultCookie(name, value));
76      }
77  
78      /**
79       * Encodes the specified cookie into a Cookie header value.
80       *
81       * @param cookie the specified cookie
82       * @return a Rfc6265 style Cookie header value
83       */
84      public String encode(Cookie cookie) {
85          StringBuilder buf = stringBuilder();
86          encode(buf, checkNotNull(cookie, "cookie"));
87          return stripTrailingSeparator(buf);
88      }
89  
90      /**
91       * Sort cookies into decreasing order of path length, breaking ties by sorting into increasing chronological
92       * order of creation time, as recommended by RFC 6265.
93       */
94      // package-private for testing only.
95      static final Comparator<Cookie> COOKIE_COMPARATOR = new Comparator<Cookie>() {
96          @Override
97          public int compare(Cookie c1, Cookie c2) {
98              String path1 = c1.path();
99              String path2 = c2.path();
100             // Cookies with unspecified path default to the path of the request. We don't
101             // know the request path here, but we assume that the length of an unspecified
102             // path is longer than any specified path (i.e. pathless cookies come first),
103             // because setting cookies with a path longer than the request path is of
104             // limited use.
105             int len1 = path1 == null ? Integer.MAX_VALUE : path1.length();
106             int len2 = path2 == null ? Integer.MAX_VALUE : path2.length();
107 
108             // Rely on Arrays.sort's stability to retain creation order in cases where
109             // cookies have same path length.
110             return len2 - len1;
111         }
112     };
113 
114     /**
115      * Encodes the specified cookies into a single Cookie header value.
116      *
117      * @param cookies
118      *            some cookies
119      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
120      */
121     public String encode(Cookie... cookies) {
122         if (checkNotNull(cookies, "cookies").length == 0) {
123             return null;
124         }
125 
126         StringBuilder buf = stringBuilder();
127         if (strict) {
128             if (cookies.length == 1) {
129                 encode(buf, cookies[0]);
130             } else {
131                 Cookie[] cookiesSorted = Arrays.copyOf(cookies, cookies.length);
132                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
133                 for (Cookie c : cookiesSorted) {
134                     encode(buf, c);
135                 }
136             }
137         } else {
138             for (Cookie c : cookies) {
139                 encode(buf, c);
140             }
141         }
142         return stripTrailingSeparatorOrNull(buf);
143     }
144 
145     /**
146      * Encodes the specified cookies into a single Cookie header value.
147      *
148      * @param cookies
149      *            some cookies
150      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
151      */
152     public String encode(Collection<? extends Cookie> cookies) {
153         if (checkNotNull(cookies, "cookies").isEmpty()) {
154             return null;
155         }
156 
157         StringBuilder buf = stringBuilder();
158         if (strict) {
159             if (cookies.size() == 1) {
160                 encode(buf, cookies.iterator().next());
161             } else {
162                 Cookie[] cookiesSorted = cookies.toArray(new Cookie[0]);
163                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
164                 for (Cookie c : cookiesSorted) {
165                     encode(buf, c);
166                 }
167             }
168         } else {
169             for (Cookie c : cookies) {
170                 encode(buf, c);
171             }
172         }
173         return stripTrailingSeparatorOrNull(buf);
174     }
175 
176     /**
177      * Encodes the specified cookies into a single Cookie header value.
178      *
179      * @param cookies some cookies
180      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
181      */
182     public String encode(Iterable<? extends Cookie> cookies) {
183         Iterator<? extends Cookie> cookiesIt = checkNotNull(cookies, "cookies").iterator();
184         if (!cookiesIt.hasNext()) {
185             return null;
186         }
187 
188         StringBuilder buf = stringBuilder();
189         if (strict) {
190             Cookie firstCookie = cookiesIt.next();
191             if (!cookiesIt.hasNext()) {
192                 encode(buf, firstCookie);
193             } else {
194                 List<Cookie> cookiesList = InternalThreadLocalMap.get().arrayList();
195                 cookiesList.add(firstCookie);
196                 while (cookiesIt.hasNext()) {
197                     cookiesList.add(cookiesIt.next());
198                 }
199                 Cookie[] cookiesSorted = cookiesList.toArray(new Cookie[0]);
200                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
201                 for (Cookie c : cookiesSorted) {
202                     encode(buf, c);
203                 }
204             }
205         } else {
206             while (cookiesIt.hasNext()) {
207                 encode(buf, cookiesIt.next());
208             }
209         }
210         return stripTrailingSeparatorOrNull(buf);
211     }
212 
213     private void encode(StringBuilder buf, Cookie c) {
214         final String name = c.name();
215         final String value = c.value() != null ? c.value() : "";
216 
217         validateCookie(name, value);
218 
219         if (c.wrap()) {
220             addQuoted(buf, name, value);
221         } else {
222             add(buf, name, value);
223         }
224     }
225 }