001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2023 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http;
020
021import java.net.URLDecoder;
022import java.nio.Buffer;
023import java.nio.ByteBuffer;
024import java.nio.CharBuffer;
025import java.nio.charset.Charset;
026import java.nio.charset.CharsetDecoder;
027import java.nio.charset.StandardCharsets;
028import java.util.ArrayList;
029import java.util.Collections;
030import java.util.List;
031import java.util.Map;
032import java.util.concurrent.ConcurrentHashMap;
033import java.util.function.BiConsumer;
034import org.jgrapes.io.events.Input;
035import org.jgrapes.io.util.InputConsumer;
036import org.jgrapes.io.util.ManagedBuffer;
037
038/**
039 * Decodes www-form-urlencoded data.
040 */
041public class WwwFormUrldecoder implements InputConsumer {
042    private boolean isEof;
043    private CharsetDecoder decoder;
044    private Charset charset = StandardCharsets.UTF_8;
045    private Charset formCharset = StandardCharsets.UTF_8;
046    private CharBuffer pending;
047    private CharBuffer rest;
048    private final Map<String, List<String>> result = new ConcurrentHashMap<>();
049    private BiConsumer<String, String> consumer = (k, v) -> {
050        result.computeIfAbsent(k,
051            key -> Collections.synchronizedList(new ArrayList<>())).add(v);
052    };
053
054    /**
055     * Sets the charset to be used if {@link #feed(ManagedBuffer)}
056     * is invoked with `ManagedBuffer<ByteBuffer>`. Defaults to UTF-8. 
057     * Must be set before the first invocation of {@link #feed(ManagedBuffer)}.
058     * 
059     * This is provided for edge cases. As "urlencoded" data may only
060     * contain ASCII characters, it does not make sense to specify
061     * a charset for media type `x-www-form-urlencoded`
062     *
063     * @param charset the charset
064     * @return the managed buffer reader
065     */
066    public WwwFormUrldecoder charset(Charset charset) {
067        if (decoder != null) {
068            throw new IllegalStateException("Charset cannot be changed.");
069        }
070        this.charset = charset;
071        return this;
072    }
073
074    /**
075     * The charset to be used with {@link URLDecoder#decode(String, Charset)}.
076     * Defaults to UTF-8.
077     *
078     * @param charset the charset
079     * @return the www form urldecoder
080     */
081    public WwwFormUrldecoder formCharset(Charset charset) {
082        formCharset = charset;
083        return this;
084    }
085
086    /**
087     * Configures a consumer for key/value pairs. The consumer is invoked
088     * when a pair has been decoded. If a consumer is configured,
089     * {@link #result()} must not be used (always returns an empty map).
090     *
091     * @param consumer the consumer
092     * @return the decoder
093     */
094    public WwwFormUrldecoder consumer(BiConsumer<String, String> consumer) {
095        this.consumer = consumer;
096        return this;
097    }
098
099    /**
100     * Feed data to the collector. 
101     * 
102     * Calling this method with `null` as argument closes the feed.
103     *
104     * @param buffer the buffer
105     */
106    @Override
107    public <W extends Buffer> void feed(ManagedBuffer<W> buffer) {
108        if (buffer == null) {
109            isEof = true;
110        } else {
111            copyToPending(buffer.backingBuffer());
112        }
113        processPending();
114    }
115
116    /**
117     * Calls {@link #feed(ManagedBuffer)} with the provided event's
118     * buffer. If {@link Input#isEndOfRecord()} returns `true`,
119     * no further input data is processed.
120     * 
121     * Calling this method with `null` indicates the end of the feed.
122     *
123     * @param <W> the generic type
124     * @param event the event
125     */
126    @Override
127    public <W extends Buffer> void feed(Input<W> event) {
128        if (event == null) {
129            feed((ManagedBuffer<W>) null);
130        } else {
131            feed(event.buffer());
132            if (event.isEndOfRecord()) {
133                isEof = true;
134            }
135        }
136    }
137
138    private <W extends Buffer> void copyToPending(W buffer) {
139        try {
140            buffer.mark();
141            if (pending == null) {
142                pending = CharBuffer.allocate(buffer.capacity());
143            }
144            if (buffer instanceof CharBuffer charBuf) {
145                if (pending.remaining() < charBuf.remaining()) {
146                    resizePending(charBuf);
147                }
148                pending.put(charBuf);
149                return;
150            }
151            if (decoder == null) {
152                decoder = charset.newDecoder();
153            }
154            while (true) {
155                var result
156                    = decoder.decode((ByteBuffer) buffer, pending, isEof);
157                if (!result.isOverflow()) {
158                    break;
159                }
160                // Need larger buffer
161                resizePending(buffer);
162            }
163        } finally {
164            buffer.reset();
165        }
166    }
167
168    private void resizePending(Buffer toAppend) {
169        var old = pending;
170        pending = CharBuffer.allocate(old.capacity() + toAppend.capacity());
171        old.flip();
172        pending.put(old);
173    }
174
175    @SuppressWarnings({ "PMD.AvoidReassigningLoopVariables",
176        "PMD.AvoidInstantiatingObjectsInLoops",
177        "PMD.AvoidLiteralsInIfCondition",
178        "PMD.AvoidBranchingStatementAsLastInLoop", "PMD.NcssCount" })
179    private void processPending() {
180        pending.flip();
181        if (!pending.hasRemaining()) {
182            pending.clear();
183            return;
184        }
185        int end = pending.limit();
186        while (pending.hasRemaining()) {
187            int start = pending.position();
188            for (int pos = start; pos < end;) {
189                if (pending.get(pos) != '&') {
190                    pos += 1;
191                    continue;
192                }
193                splitPair(new String(pending.array(), start, pos - start));
194                pos += 1;
195                pending.position(pos);
196                break;
197            }
198            if (pending.position() == start) {
199                // No '&' found
200                break;
201            }
202        }
203        if (!pending.hasRemaining()) {
204            pending.clear();
205            return;
206        }
207        if (isEof) {
208            // Remaining is last entry
209            splitPair(new String(pending.array(), pending.position(),
210                pending.remaining()).trim());
211            return;
212        }
213        if (pending.position() == 0) {
214            // Nothing consumed, continue to write into pending
215            var limit = pending.limit();
216            pending.clear();
217            pending.position(limit);
218            return;
219        }
220        // Transfer remaining to beginning of pending
221        if (rest == null || rest.capacity() < pending.remaining()) {
222            rest = CharBuffer.allocate(pending.capacity());
223        }
224        rest.put(pending);
225        rest.flip();
226        pending.clear();
227        pending.put(rest);
228        rest.clear();
229    }
230
231    private void splitPair(String pair) {
232        int sep = pair.indexOf('=');
233        String key = URLDecoder.decode(pair.substring(0, sep), formCharset);
234        String value = URLDecoder.decode(pair.substring(sep + 1), formCharset);
235        consumer.accept(key, value);
236    }
237
238    /**
239     * Checks if more input may become available.
240     *
241     * @return true, if successful
242     */
243    public boolean eof() {
244        return isEof;
245    }
246
247    /**
248     * Gets the result.
249     *
250     * @return the line
251     */
252    public Map<String, List<String>> result() {
253        return result;
254    }
255}