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    *   http://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.util.internal.ObjectUtil.checkNotNull;
23  
24  import io.netty.handler.codec.DateFormatter;
25  import io.netty.handler.codec.http.HttpConstants;
26  import io.netty.handler.codec.http.HttpResponse;
27  
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.Collections;
31  import java.util.Date;
32  import java.util.HashMap;
33  import java.util.Iterator;
34  import java.util.List;
35  import java.util.Map;
36  
37  /**
38   * A <a href="http://tools.ietf.org/html/rfc6265">RFC6265</a> compliant cookie encoder to be used server side,
39   * so some fields are sent (Version is typically ignored).
40   *
41   * As Netty's Cookie merges Expires and MaxAge into one single field, only Max-Age field is sent.
42   *
43   * Note that multiple cookies must be sent as separate "Set-Cookie" headers.
44   *
45   * <pre>
46   * // Example
47   * {@link HttpResponse} res = ...;
48   * res.setHeader("Set-Cookie", {@link ServerCookieEncoder}.encode("JSESSIONID", "1234"));
49   * </pre>
50   *
51   * @see ServerCookieDecoder
52   */
53  public final class ServerCookieEncoder extends CookieEncoder {
54  
55      /**
56       * Strict encoder that validates that name and value chars are in the valid scope
57       * defined in RFC6265, and (for methods that accept multiple cookies) that only
58       * one cookie is encoded with any given name. (If multiple cookies have the same
59       * name, the last one is the one that is encoded.)
60       */
61      public static final ServerCookieEncoder STRICT = new ServerCookieEncoder(true);
62  
63      /**
64       * Lax instance that doesn't validate name and value, and that allows multiple
65       * cookies with the same name.
66       */
67      public static final ServerCookieEncoder LAX = new ServerCookieEncoder(false);
68  
69      private ServerCookieEncoder(boolean strict) {
70          super(strict);
71      }
72  
73      /**
74       * Encodes the specified cookie name-value pair into a Set-Cookie header value.
75       *
76       * @param name the cookie name
77       * @param value the cookie value
78       * @return a single Set-Cookie header value
79       */
80      public String encode(String name, String value) {
81          return encode(new DefaultCookie(name, value));
82      }
83  
84      /**
85       * Encodes the specified cookie into a Set-Cookie header value.
86       *
87       * @param cookie the cookie
88       * @return a single Set-Cookie header value
89       */
90      public String encode(Cookie cookie) {
91          final String name = checkNotNull(cookie, "cookie").name();
92          final String value = cookie.value() != null ? cookie.value() : "";
93  
94          validateCookie(name, value);
95  
96          StringBuilder buf = stringBuilder();
97  
98          if (cookie.wrap()) {
99              addQuoted(buf, name, value);
100         } else {
101             add(buf, name, value);
102         }
103 
104         if (cookie.maxAge() != Long.MIN_VALUE) {
105             add(buf, CookieHeaderNames.MAX_AGE, cookie.maxAge());
106             Date expires = new Date(cookie.maxAge() * 1000 + System.currentTimeMillis());
107             buf.append(CookieHeaderNames.EXPIRES);
108             buf.append((char) HttpConstants.EQUALS);
109             DateFormatter.append(expires, buf);
110             buf.append((char) HttpConstants.SEMICOLON);
111             buf.append((char) HttpConstants.SP);
112         }
113 
114         if (cookie.path() != null) {
115             add(buf, CookieHeaderNames.PATH, cookie.path());
116         }
117 
118         if (cookie.domain() != null) {
119             add(buf, CookieHeaderNames.DOMAIN, cookie.domain());
120         }
121         if (cookie.isSecure()) {
122             add(buf, CookieHeaderNames.SECURE);
123         }
124         if (cookie.isHttpOnly()) {
125             add(buf, CookieHeaderNames.HTTPONLY);
126         }
127 
128         return stripTrailingSeparator(buf);
129     }
130 
131     /** Deduplicate a list of encoded cookies by keeping only the last instance with a given name.
132      *
133      * @param encoded The list of encoded cookies.
134      * @param nameToLastIndex A map from cookie name to index of last cookie instance.
135      * @return The encoded list with all but the last instance of a named cookie.
136      */
137     private static List<String> dedup(List<String> encoded, Map<String, Integer> nameToLastIndex) {
138         boolean[] isLastInstance = new boolean[encoded.size()];
139         for (int idx : nameToLastIndex.values()) {
140             isLastInstance[idx] = true;
141         }
142         List<String> dedupd = new ArrayList<String>(nameToLastIndex.size());
143         for (int i = 0, n = encoded.size(); i < n; i++) {
144             if (isLastInstance[i]) {
145                 dedupd.add(encoded.get(i));
146             }
147         }
148         return dedupd;
149     }
150 
151     /**
152      * Batch encodes cookies into Set-Cookie header values.
153      *
154      * @param cookies a bunch of cookies
155      * @return the corresponding bunch of Set-Cookie headers
156      */
157     public List<String> encode(Cookie... cookies) {
158         if (checkNotNull(cookies, "cookies").length == 0) {
159             return Collections.emptyList();
160         }
161 
162         List<String> encoded = new ArrayList<String>(cookies.length);
163         Map<String, Integer> nameToIndex = strict && cookies.length > 1 ? new HashMap<String, Integer>() : null;
164         boolean hasDupdName = false;
165         for (int i = 0; i < cookies.length; i++) {
166             Cookie c = cookies[i];
167             encoded.add(encode(c));
168             if (nameToIndex != null) {
169                 hasDupdName |= nameToIndex.put(c.name(), i) != null;
170             }
171         }
172         return hasDupdName ? dedup(encoded, nameToIndex) : encoded;
173     }
174 
175     /**
176      * Batch encodes cookies into Set-Cookie header values.
177      *
178      * @param cookies a bunch of cookies
179      * @return the corresponding bunch of Set-Cookie headers
180      */
181     public List<String> encode(Collection<? extends Cookie> cookies) {
182         if (checkNotNull(cookies, "cookies").isEmpty()) {
183             return Collections.emptyList();
184         }
185 
186         List<String> encoded = new ArrayList<String>(cookies.size());
187         Map<String, Integer> nameToIndex = strict && cookies.size() > 1 ? new HashMap<String, Integer>() : null;
188         int i = 0;
189         boolean hasDupdName = false;
190         for (Cookie c : cookies) {
191             encoded.add(encode(c));
192             if (nameToIndex != null) {
193                 hasDupdName |= nameToIndex.put(c.name(), i++) != null;
194             }
195         }
196         return hasDupdName ? dedup(encoded, nameToIndex) : encoded;
197     }
198 
199     /**
200      * Batch encodes cookies into Set-Cookie header values.
201      *
202      * @param cookies a bunch of cookies
203      * @return the corresponding bunch of Set-Cookie headers
204      */
205     public List<String> encode(Iterable<? extends Cookie> cookies) {
206         Iterator<? extends Cookie> cookiesIt = checkNotNull(cookies, "cookies").iterator();
207         if (!cookiesIt.hasNext()) {
208             return Collections.emptyList();
209         }
210 
211         List<String> encoded = new ArrayList<String>();
212         Cookie firstCookie = cookiesIt.next();
213         Map<String, Integer> nameToIndex = strict && cookiesIt.hasNext() ? new HashMap<String, Integer>() : null;
214         int i = 0;
215         encoded.add(encode(firstCookie));
216         boolean hasDupdName = nameToIndex != null && nameToIndex.put(firstCookie.name(), i++) != null;
217         while (cookiesIt.hasNext()) {
218             Cookie c = cookiesIt.next();
219             encoded.add(encode(c));
220             if (nameToIndex != null) {
221                 hasDupdName |= nameToIndex.put(c.name(), i++) != null;
222             }
223         }
224         return hasDupdName ? dedup(encoded, nameToIndex) : encoded;
225     }
226 }