001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.attachment;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.net.SocketException;
026import java.nio.charset.StandardCharsets;
027import java.security.Permission;
028import java.security.Principal;
029import java.util.ArrayList;
030import java.util.List;
031import java.util.Properties;
032import java.util.Set;
033
034import org.apache.commons.fileupload2.core.DiskFileItemFactory;
035import org.apache.commons.fileupload2.core.FileItem;
036import org.apache.commons.fileupload2.core.FileItemFactory;
037import org.apache.commons.fileupload2.core.FileUploadException;
038import org.apache.commons.fileupload2.core.ProgressListener;
039import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;
040import org.apache.logging.log4j.LogManager;
041import org.apache.logging.log4j.Logger;
042import org.apache.wiki.api.core.Attachment;
043import org.apache.wiki.api.core.Context;
044import org.apache.wiki.api.core.ContextEnum;
045import org.apache.wiki.api.core.Engine;
046import org.apache.wiki.api.core.Page;
047import org.apache.wiki.api.core.Session;
048import org.apache.wiki.api.exceptions.ProviderException;
049import org.apache.wiki.api.exceptions.RedirectException;
050import org.apache.wiki.api.exceptions.WikiException;
051import org.apache.wiki.api.providers.WikiProvider;
052import org.apache.wiki.api.spi.Wiki;
053import org.apache.wiki.auth.AuthorizationManager;
054import org.apache.wiki.auth.permissions.PermissionFactory;
055import org.apache.wiki.http.filter.CsrfProtectionFilter;
056import org.apache.wiki.i18n.InternationalizationManager;
057import org.apache.wiki.preferences.Preferences;
058import org.apache.wiki.ui.progress.ProgressItem;
059import org.apache.wiki.ui.progress.ProgressManager;
060import org.apache.wiki.util.HttpUtil;
061import org.apache.wiki.util.TextUtil;
062
063import jakarta.servlet.ServletConfig;
064import jakarta.servlet.ServletContext;
065import jakarta.servlet.ServletException;
066import jakarta.servlet.ServletInputStream;
067import jakarta.servlet.http.HttpServlet;
068import jakarta.servlet.http.HttpServletRequest;
069import jakarta.servlet.http.HttpServletResponse;
070import org.apache.commons.fileupload2.core.FileUploadByteCountLimitException;
071import java.util.ResourceBundle;
072import org.apache.wiki.tags.MaxUploadTag;
073
074
075/**
076 *  This is the chief JSPWiki attachment management servlet.  It is used for
077 *  both uploading new content and downloading old content.  It can handle
078 *  most common cases, e.g. check for modifications and return 304's as necessary.
079 *  <p>
080 *  Authentication is done using JSPWiki's normal AAA framework.
081 *  <p>
082 *  This servlet is also capable of managing dynamically created attachments.
083 *
084 *
085 *  @since 1.9.45.
086 */
087public class AttachmentServlet extends HttpServlet {
088
089    private static final long serialVersionUID = 3257282552187531320L;
090    private static final int BUFFER_SIZE = 8192;
091
092    private Engine m_engine;
093    private static final Logger LOG = LogManager.getLogger( AttachmentServlet.class );
094    private static final String HDR_VERSION = "version";
095
096    /** Allowlist of passive content types which may be served inline; everything else forces a download. */
097    private static final Set< String > INLINE_SAFE_TYPES = Set.of(
098            "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp",
099            "image/avif", "image/tiff", "image/x-icon", "image/vnd.microsoft.icon",
100            "text/plain" );
101
102    /** The maximum size that an attachment can be. */
103    private int m_maxSize = Integer.MAX_VALUE;
104
105    /** List of attachment types which are allowed */
106    private String[] m_allowedPatterns;
107    private String[] m_forbiddenPatterns;
108
109    //
110    // Not static as DateFormat objects are not thread safe.
111    // Used to handle the RFC date format = Sat, 13 Apr 2002 13:23:01 GMT
112    //
113    //private final DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
114
115    /**
116     *  Initializes the servlet from Engine properties.
117     * @param config
118     * @throws jakarta.servlet.ServletException
119     */
120    @Override
121    public void init( final ServletConfig config ) throws ServletException {
122        m_engine = Wiki.engine().find( config );
123        final Properties props = m_engine.getWikiProperties();
124        final String tmpDir = m_engine.getWorkDir() + File.separator + "attach-tmp";
125        final String allowed = TextUtil.getStringProperty( props, AttachmentManager.PROP_ALLOWEDEXTENSIONS, null );
126        m_maxSize = TextUtil.getIntegerProperty( props, AttachmentManager.PROP_MAXSIZE, Integer.MAX_VALUE );
127
128        if( allowed != null && !allowed.isEmpty() ) {
129            m_allowedPatterns = allowed.toLowerCase().split( "\\s" );
130        } else {
131            m_allowedPatterns = new String[ 0 ];
132        }
133
134        final String forbidden = TextUtil.getStringProperty( props, AttachmentManager.PROP_FORBIDDENEXTENSIONS,null );
135        if( forbidden != null && !forbidden.isEmpty() ) {
136            m_forbiddenPatterns = forbidden.toLowerCase().split("\\s");
137        } else {
138            m_forbiddenPatterns = new String[0];
139        }
140
141        final File f = new File( tmpDir );
142        if( !f.exists() ) {
143            f.mkdirs();
144        } else if( !f.isDirectory() ) {
145            LOG.fatal( "A file already exists where the temporary dir is supposed to be: {}. Please remove it.", tmpDir );
146        }
147
148        LOG.debug( "UploadServlet initialized. Using {} for temporary storage.", tmpDir );
149    }
150
151    private boolean isTypeAllowed( String name )
152    {
153        if( name == null || name.isEmpty() ) return false;
154
155        name = name.toLowerCase();
156
157        for( final String m_forbiddenPattern : m_forbiddenPatterns ) {
158            if( name.endsWith( m_forbiddenPattern ) && !m_forbiddenPattern.isEmpty() )
159                return false;
160        }
161
162        for( final String m_allowedPattern : m_allowedPatterns ) {
163            if( name.endsWith( m_allowedPattern ) && !m_allowedPattern.isEmpty() )
164                return true;
165        }
166
167        return m_allowedPatterns.length == 0;
168    }
169
170    /**
171     *  Implements the OPTIONS method.
172     *
173     *  @param req The servlet request
174     *  @param res The servlet response
175     */
176
177    @Override
178    protected void doOptions( final HttpServletRequest req, final HttpServletResponse res ) {
179        res.setHeader( "Allow", "GET, PUT, POST, OPTIONS, PROPFIND, PROPPATCH, MOVE, COPY, DELETE");
180        res.setStatus( HttpServletResponse.SC_OK );
181    }
182
183    /**
184     *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
185     *  of the attachment, 'version' specifying the version indicator.
186     *
187     */
188    // FIXME: Messages would need to be localized somehow.
189    @Override
190    public void doGet( final HttpServletRequest  req, final HttpServletResponse res ) throws IOException {
191        final Context context = Wiki.context().create( m_engine, req, ContextEnum.PAGE_ATTACH.getRequestContext() );
192        final AttachmentManager mgr = m_engine.getManager( AttachmentManager.class );
193        final AuthorizationManager authmgr = m_engine.getManager( AuthorizationManager.class );
194        final String version = req.getParameter( HDR_VERSION );
195        final String nextPage = req.getParameter( "nextpage" );
196        final String page = context.getPage().getName();
197        int ver = WikiProvider.LATEST_VERSION;
198
199        if( page == null ) {
200            LOG.info( "Invalid attachment name." );
201            res.sendError( HttpServletResponse.SC_BAD_REQUEST );
202            return;
203        }
204
205        try( final OutputStream out = res.getOutputStream() ) {
206            LOG.debug("Attempting to download att "+page+", version "+version);
207            if( version != null ) {
208                ver = Integer.parseInt( version );
209            }
210
211            final Attachment att = mgr.getAttachmentInfo( page, ver );
212            if( att != null ) {
213                //
214                //  Check if the user has permission for this attachment
215                //
216
217                final Permission permission = PermissionFactory.getPagePermission( att, "view" );
218                if( !authmgr.checkPermission( context.getWikiSession(), permission ) ) {
219                    LOG.debug("User does not have permission for this");
220                    res.sendError( HttpServletResponse.SC_FORBIDDEN );
221                    return;
222                }
223
224                //
225                //  Check if the client already has a version of this attachment.
226                //
227                if( HttpUtil.checkFor304( req, att.getName(), att.getLastModified() ) ) {
228                    LOG.debug( "Client has latest version already, sending 304..." );
229                    res.sendError( HttpServletResponse.SC_NOT_MODIFIED );
230                    return;
231                }
232
233                final String mimetype = getMimeType( context, att.getFileName() );
234                res.setContentType( mimetype );
235
236                final String contentDisposition = getContentDisposition( att, mimetype );
237                res.addHeader( "Content-Disposition", contentDisposition );
238                res.addDateHeader("Last-Modified",att.getLastModified().getTime());
239
240                if( !att.isCacheable() ) {
241                    res.addHeader( "Pragma", "no-cache" );
242                    res.addHeader( "Cache-control", "no-cache" );
243                }
244
245                // If a size is provided by the provider, report it.
246                if( att.getSize() >= 0 ) {
247                    // LOG.info("size:"+att.getSize());
248                    res.setContentLength( (int)att.getSize() );
249                }
250
251                try( final InputStream  in = mgr.getAttachmentStream( context, att ) ) {
252                    int read;
253                    final byte[] buffer = new byte[ BUFFER_SIZE ];
254
255                    while( ( read = in.read( buffer ) ) > -1 ) {
256                        out.write( buffer, 0, read );
257                    }
258                }
259                LOG.debug( "Attachment {} sent to {} on {}", att.getFileName(), req.getRemoteUser(), HttpUtil.getRemoteAddress(req) );
260                if( nextPage != null ) {
261                    res.sendRedirect(
262                        validateNextPage(
263                            TextUtil.urlEncodeUTF8(nextPage),
264                            m_engine.getURL( ContextEnum.WIKI_ERROR.getRequestContext(), "", null )
265                        )
266                    );
267                }
268
269            } else {
270                final String msg = "Attachment '" + page + "', version " + ver + " does not exist.";
271                LOG.info( msg );
272                res.sendError( HttpServletResponse.SC_NOT_FOUND, msg );
273            }
274        } catch( final ProviderException pe ) {
275            LOG.warn("Provider failed while reading", pe);
276            //
277            //  This might fail, if the response is already committed.  So in that
278            //  case we just log it.
279            //
280            final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, req.getLocale() );
281            sendError( res, rb.getString("operation.failed") );
282        } catch( final NumberFormatException nfe ) {
283            LOG.warn( "Invalid version number: " + version );
284            res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid version number" );
285        } catch( final SocketException se ) {
286            //
287            //  These are very common in download situations due to aggressive
288            //  clients.  No need to try and send an error.
289            //
290            LOG.debug( "I/O exception during download", se );
291        } catch( final IOException ioe ) {
292            //
293            //  Client dropped the connection or something else happened.
294            //  We don't know where the error came from, so we'll at least
295            //  try to send an error and catch it quietly if it doesn't quite work.
296            //
297            LOG.debug( "I/O exception during download", ioe );
298            final ResourceBundle rb = ResourceBundle.getBundle( InternationalizationManager.CORE_BUNDLE, req.getLocale() );
299            sendError( res, rb.getString("operation.failed") );
300        }
301    }
302
303    String getContentDisposition( final Attachment att, final String mimetype ) {
304        // Default-deny: only passive content types which cannot execute script on the wiki's origin
305        // are served inline, so that user agents can try to automatically open them.  Everything
306        // else - including anything the container resolves to an actively rendering type such as
307        // text/html, application/xhtml+xml or image/svg+xml - is forced to download.
308        String contentDisposition = "attachment; filename=\"";
309        if( isInlineRenderSafe( mimetype ) && !m_engine.getManager( AttachmentManager.class ).forceDownload( att.getFileName() ) ) {
310            contentDisposition = "inline; filename=\"";
311        }
312        contentDisposition += encodeFileName( att.getFileName() );
313        return contentDisposition;
314    }
315
316    /**
317     * Builds the part of a {@code Content-Disposition} header that follows the quote of the {@code filename}
318     * parameter, as in RFC 6266.  A name made of printable ASCII characters other than the quote and the backslash
319     * is written as it is.  Any other name gets an ASCII fallback in {@code filename} and the real name, as UTF-8
320     * percent encoded bytes, in {@code filename*} (RFC 8187), since a header value has no defined encoding for
321     * the other characters.
322     *
323     * @param fileName The name of the attachment.
324     * @return The rest of the header value: the file name, the closing quote and the terminating semicolon.
325     * @since 3.0.1
326     */
327    static String encodeFileName( final String fileName ) {
328        boolean plain = true;
329        final StringBuilder fallback = new StringBuilder( fileName.length() );
330        for( int i = 0; i < fileName.length(); i++ ) {
331            final char c = fileName.charAt( i );
332            if( c < 0x20 || c > 0x7e || c == '"' || c == '\\' ) {
333                plain = false;
334                fallback.append( '_' );
335            } else {
336                fallback.append( c );
337            }
338        }
339        if( plain ) {
340            return fileName + "\";";
341        }
342
343        final StringBuilder encoded = new StringBuilder( fileName.length() * 3 );
344        for( final byte b : fileName.getBytes( StandardCharsets.UTF_8 ) ) {
345            final int v = b & 0xff;
346            if( isAttrChar( v ) ) {
347                encoded.append( ( char )v );
348            } else {
349                encoded.append( '%' ).append( Character.toUpperCase( Character.forDigit( v >> 4, 16 ) ) )
350                       .append( Character.toUpperCase( Character.forDigit( v & 0xf, 16 ) ) );
351            }
352        }
353        return fallback + "\"; filename*=UTF-8''" + encoded + ";";
354    }
355
356    /** Tells whether a byte is an {@code attr-char} of RFC 8187, which may appear in {@code filename*} unencoded. */
357    private static boolean isAttrChar( final int v ) {
358        return v >= 'a' && v <= 'z' || v >= 'A' && v <= 'Z' || v >= '0' && v <= '9' || "!#$&+-.^_`|~".indexOf( v ) >= 0;
359    }
360
361    /**
362     * Checks whether the given content type is safe to render inline on the wiki origin, i.e. it is a
363     * passive media type which cannot carry script.  Actively rendering types (text/html,
364     * application/xhtml+xml, image/svg+xml, XML, PDF, ...) are deliberately not on the allowlist.
365     *
366     * @param mimetype The resolved content type of the attachment.
367     * @return {@code true} if the attachment may be served with {@code Content-Disposition: inline}.
368     */
369    static boolean isInlineRenderSafe( final String mimetype ) {
370        if( mimetype == null ) {
371            return false;
372        }
373        final String type = mimetype.toLowerCase();
374        return INLINE_SAFE_TYPES.contains( type ) || type.startsWith( "audio/" ) || type.startsWith( "video/" );
375    }
376
377    void sendError( final HttpServletResponse res, final String message ) throws IOException {
378        try {
379            res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message );
380        } catch( final IllegalStateException e ) {
381            LOG.debug(e.getMessage(), e);
382        }
383    }
384
385    /**
386     *  Returns the mime type for this particular file.  Case does not matter.
387     *
388     * @param ctx WikiContext; required to access the ServletContext of the request.
389     * @param fileName The name to check for.
390     * @return A valid mime type, or application/binary, if not recognized
391     */
392    private static String getMimeType( final Context ctx, final String fileName ) {
393        String mimetype = null;
394
395        final HttpServletRequest req = ctx.getHttpRequest();
396        if( req != null ) {
397            final ServletContext s = req.getSession().getServletContext();
398
399            if( s != null ) {
400                mimetype = s.getMimeType( fileName.toLowerCase() );
401            }
402        }
403
404        if( mimetype == null ) {
405            mimetype = "application/binary";
406        }
407
408        return mimetype;
409    }
410
411
412    /**
413     * Grabs mime/multipart data and stores it into the temporary area.
414     * Uses other parameters to determine which name to store as.
415     *
416     * <p>The input to this servlet is generated by an HTML FORM with
417     * two parts. The first, named 'page', is the WikiName identifier
418     * for the parent file. The second, named 'content', is the binary
419     * content of the file.
420     *
421     */
422    @Override
423    public void doPost( final HttpServletRequest req, final HttpServletResponse res ) throws IOException {
424        try {
425            final String nextPage = upload( req );
426            req.getSession().removeAttribute("msg");
427            res.sendRedirect( nextPage );
428        } catch( final RedirectException e ) {
429            final Session session = Wiki.session().find( m_engine, req );
430            session.addMessage( e.getMessage() );
431            //drain the request body
432            try (ServletInputStream inputStream = req.getInputStream();) {
433                int data;
434                while ((data = inputStream.read()) != -1) {
435                    //we are just reading the stream to the end
436                }
437            } catch (Exception err) {
438                //ignore it
439                LOG.debug(e.getMessage(), e);
440            }
441            
442            
443            req.getSession().setAttribute("msg", e.getMessage());
444            res.sendRedirect( e.getRedirect() );
445        }
446    }
447
448    /**
449     *  Validates the next page to be on the same server as this webapp.
450     *  Fixes [JSPWIKI-46].
451     */
452    private String validateNextPage( String nextPage, final String errorPage ) {
453        if( !isSameOrigin( nextPage, m_engine.getBaseURL() ) ) {
454            LOG.warn("Detected phishing attempt by redirecting to an unsecure location: "+nextPage);
455            nextPage = errorPage;
456         }
457 
458
459        return nextPage;
460    }
461    
462    
463    /**
464     *  Checks that a redirect target stays on this wiki. Rejects scheme-relative ({@code //host}) and
465     *  backslash forms, which browsers resolve to a foreign origin even though they contain no {@code ://},
466     *  and requires any URL with an explicit scheme to stay within the wiki's base URL on a path-segment
467     *  boundary (so {@code http://host/wiki.evil.example} cannot spoof a base URL of {@code http://host/wiki}).
468     *
469     *  @param nextPage redirect target to validate
470     *  @param baseURL the wiki's configured base URL
471     *  @return true if the target is safe to redirect to
472     */
473    static boolean isSameOrigin( final String nextPage, final String baseURL ) {
474        // Browsers ignore ASCII control characters and whitespace when parsing URLs, so strip them before validating.
475        final String url = nextPage.replaceAll( "[\\x00-\\x20]", "" );
476        if( url.startsWith( "//" ) || url.startsWith( "/\\" ) || url.startsWith( "\\" ) ) {
477            return false;
478        }
479        final int colon = url.indexOf( ':' );
480        if( colon != -1 && url.substring( 0, colon ).matches( "[a-zA-Z][a-zA-Z0-9+.-]*" ) ) {
481            // absolute URL with an explicit scheme: only allow it inside our own base URL
482            final String base = baseURL.endsWith( "/" ) ? baseURL : baseURL + "/";
483            return url.startsWith( base ) || url.equals( base.substring( 0, base.length() - 1 ) );
484        }
485        return true; // relative URL, resolves on this server
486    }
487
488    /**
489     *  Uploads a specific mime multipart input set, intercepts exceptions.
490     * 
491     *  If the total request size is too big, the user will be redirected to the Error.jsp page
492     *
493     *  @param req The servlet request
494     *  @return The page to which we should go next.
495     *  @throws RedirectException If there's an error and a redirection is needed
496     *  @throws IOException If upload fails
497     */
498    protected String upload( final HttpServletRequest req ) throws RedirectException, IOException {
499        final String msg;
500        final String attName = "(unknown)";
501        final String errorPage = m_engine.getURL( ContextEnum.WIKI_ERROR.getRequestContext(), "", null ); // If something bad happened, Upload should be able to take care of most stuff
502        String nextPage = errorPage;
503        final String progressId = req.getParameter( "progressid" );
504        String csrfToken = req.getParameter( CsrfProtectionFilter.ANTICSRF_PARAM );
505
506        // Check that we have a file upload request
507        if( !JakartaServletFileUpload.isMultipartContent(req) ) {
508            throw new RedirectException( "Not a file upload", nextPage );
509        }
510
511        try {
512            final FileItemFactory factory = DiskFileItemFactory.builder().get();
513
514            // Create the context _before_ Multipart operations, otherwise strict servlet containers may fail when setting encoding.
515            final Context context = Wiki.context().create( m_engine, req, ContextEnum.PAGE_ATTACH.getRequestContext() );
516            final UploadListener pl = new UploadListener();
517
518            m_engine.getManager( ProgressManager.class ).startProgress( pl, progressId );
519            
520            if (req.getContentLengthLong() > m_maxSize) {
521                //we don't want total upload size to be larger than the max
522                //this is to prevent resource exhaustion
523                //TODO i18n this error message
524                throw new RedirectException("Request too big " + 
525                        MaxUploadTag.humanReadableByteCountBin(req.getContentLengthLong()) + " vs " + 
526                        MaxUploadTag.humanReadableByteCountBin(m_maxSize), errorPage +"?Error=true");
527            }
528            final JakartaServletFileUpload upload = new JakartaServletFileUpload( factory );
529            upload.setHeaderCharset(StandardCharsets.UTF_8);
530            upload.setProgressListener( pl );
531            final List<FileItem> items;
532            try {
533                items = upload.parseRequest(req);
534            } catch (FileUploadByteCountLimitException ex) {
535                throw new RedirectException( "Request too big " + ex.getMessage(), nextPage );
536            }
537            String   wikipage   = null;
538            String   changeNote = null;
539            //FileItem actualFile = null;
540            final List<FileItem> fileItems = new ArrayList<>();
541
542            for( final FileItem item : items ) {
543                if( item.isFormField() ) {
544                    switch( item.getFieldName() ) {
545                    case "page":
546                        // FIXME: Kludge alert.  We must end up with the parent page name, if this is an upload of a new revision
547                        wikipage = item.getString( StandardCharsets.UTF_8);
548                        final int x = wikipage.indexOf( "/" );
549                        if( x != -1 ) {
550                            wikipage = wikipage.substring( 0, x );
551                        }
552                        break;
553                    case "changenote":
554                        changeNote = item.getString( StandardCharsets.UTF_8 );
555                        if( changeNote != null ) {
556                            changeNote = TextUtil.replaceEntities( changeNote );
557                        }
558                        break;
559                    case "nextpage":
560                        nextPage = validateNextPage( item.getString( StandardCharsets.UTF_8 ), errorPage );
561                        break;
562                    case CsrfProtectionFilter.ANTICSRF_PARAM:
563                        csrfToken = item.getString( StandardCharsets.UTF_8 );
564                        break;
565                    }
566                } else {
567                    fileItems.add( item );
568                }
569            }
570
571            // The CsrfProtectionFilter delegates multipart requests to this servlet, since it cannot read the
572            // token from a multipart body without consuming it. Enforce the token here - taken from the multipart
573            // form field written by <wiki:CsrfProtection/> (or, for older clients, the query string) - before
574            // acting on anything else in the request, including the "Broken file upload" redirect below.
575            final Session session = Wiki.session().find( m_engine, req );
576            if( csrfToken == null || !csrfToken.equals( session.antiCsrfToken() ) ) {
577                LOG.error( "Incorrect {} received for {}", CsrfProtectionFilter.ANTICSRF_PARAM, req.getPathInfo() );
578                throw new RedirectException( "Missing or invalid CSRF token", errorPage );
579            }
580
581            if(fileItems.isEmpty()) {
582                throw new RedirectException( "Broken file upload", nextPage );
583
584            } else {
585                for( final FileItem actualFile : fileItems ) {
586                    if( !context.hasAdminPermissions() ) {
587                        if (actualFile.getSize()> m_maxSize) {
588                            //TODO i18n this error message
589                            throw new RedirectException("Attachment too big " + actualFile.getName() + " " + 
590                                     MaxUploadTag.humanReadableByteCountBin(actualFile.getSize()) + " vs " + 
591                                     MaxUploadTag.humanReadableByteCountBin(m_maxSize), nextPage);
592                        }
593                    }
594                    
595                    final String filename = actualFile.getName();
596                    final long   fileSize = actualFile.getSize();
597                    try( final InputStream in  = actualFile.getInputStream() ) {
598                        executeUpload( context, in, filename, nextPage, wikipage, changeNote, fileSize );
599                    }
600                }
601            }
602
603        } catch( final ProviderException e ) {
604            msg = "Upload failed because the provider failed: "+e.getMessage();
605            LOG.warn( msg + " (attachment: " + attName + ")", e );
606
607            throw new IOException( msg );
608        } catch( final FileUploadException e ) {
609            // Show the submit page again, but with a bit more intimidating output.
610            msg = "Upload failure: " + e.getMessage();
611            LOG.warn( msg + " (attachment: " + attName + ")", e );
612
613            throw new IOException( msg, e );
614        } catch( final IOException e ) {
615            // Show the submit page again, but with a bit more intimidating output.
616            msg = "Upload failure: " + e.getMessage();
617            LOG.warn( msg + " (attachment: " + attName + ")", e );
618
619            throw e;
620        } finally {
621            m_engine.getManager( ProgressManager.class ).stopProgress( progressId );
622            // FIXME: In case of exceptions should absolutely remove the uploaded file.
623        }
624
625        return nextPage;
626    }
627
628    /**
629     *
630     * @param context the wiki context
631     * @param data the input stream data
632     * @param filename the name of the file to upload
633     * @param errorPage the place to which you want to get a redirection
634     * @param parentPage the page to which the file should be attached
635     * @param changenote The change note
636     * @param contentLength The content length
637     * @return <code>true</code> if upload results in the creation of a new page;
638     * <code>false</code> otherwise
639     * @throws RedirectException If the content needs to be redirected
640     * @throws IOException       If there is a problem in the upload.
641     * @throws ProviderException If there is a problem in the backend.
642     */
643    protected boolean executeUpload( final Context context, final InputStream data,
644                                     String filename, final String errorPage,
645                                     final String parentPage, final String changenote,
646                                     final long contentLength )
647            throws RedirectException, IOException, ProviderException {
648        boolean created = false;
649
650        try {
651            filename = AttachmentManager.validateFileName( filename );
652        } catch( final WikiException e ) {
653            // this is a kludge, the exception that is caught here contains the i18n key
654            // here we have the context available, so we can internationalize it properly :
655            throw new RedirectException (Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE )
656                    .getString( e.getMessage() ), errorPage );
657        }
658
659        //
660        //  FIXME: This has the unfortunate side effect that it will receive the
661        //  contents.  But we can't figure out the page to redirect to
662        //  before we receive the file, due to the stupid constructor of MultipartRequest.
663        //
664
665        if( !context.hasAdminPermissions() ) {
666            if( contentLength > m_maxSize ) {
667                // FIXME: Does not delete the received files.
668                throw new RedirectException( "File exceeds maximum size ("+m_maxSize+" bytes)", errorPage );
669            }
670
671            if( !isTypeAllowed(filename) ) {
672                throw new RedirectException( "Files of this type may not be uploaded to this wiki", errorPage );
673            }
674        }
675
676        final Principal user    = context.getCurrentUser();
677        final AttachmentManager mgr = m_engine.getManager( AttachmentManager.class );
678
679        LOG.debug("file="+filename);
680
681        if( data == null ) {
682            LOG.error("File could not be opened.");
683            throw new RedirectException("File could not be opened.", errorPage);
684        }
685
686        //  Check whether we already have this kind of page. If the "page" parameter already defines an attachment
687        //  name for an update, then we just use that file. Otherwise, we create a new attachment, and use the
688        //  filename given.  Incidentally, this will also mean that if the user uploads a file with the exact
689        //  same name than some other previous attachment, then that attachment gains a new version.
690        Attachment att = mgr.getAttachmentInfo( context.getPage().getName() );
691        if( att == null ) {
692            att = new org.apache.wiki.attachment.Attachment( m_engine, parentPage, filename );
693            created = true;
694        }
695        att.setSize( contentLength );
696
697        //  Check if we're allowed to do this?
698        final Permission permission = PermissionFactory.getPagePermission( att, "upload" );
699        if( m_engine.getManager( AuthorizationManager.class ).checkPermission( context.getWikiSession(), permission ) ) {
700            if( user != null ) {
701                att.setAuthor( user.getName() );
702            }
703
704            if( changenote != null && !changenote.isEmpty() ) {
705                att.setAttribute( Page.CHANGENOTE, changenote );
706            }
707
708            try {
709                m_engine.getManager( AttachmentManager.class ).storeAttachment( att, data );
710            } catch( final ProviderException pe ) {
711                // this is a kludge, the exception that is caught here contains the i18n key
712                // here we have the context available, so we can internationalize it properly :
713                throw new ProviderException( Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE ).getString( pe.getMessage() ) );
714            }
715
716            LOG.info( "User " + user + " uploaded attachment to " + parentPage + " called "+filename+", size " + att.getSize() );
717        } else {
718            throw new RedirectException( "No permission to upload a file", errorPage );
719        }
720
721        return created;
722    }
723
724    /**
725     *  Provides tracking for upload progress.
726     *
727     */
728    private static class UploadListener extends ProgressItem implements ProgressListener {
729        public long m_currentBytes;
730        public long m_totalBytes;
731
732        @Override
733        public void update( final long recvdBytes, final long totalBytes, final int item) {
734            m_currentBytes = recvdBytes;
735            m_totalBytes   = totalBytes;
736        }
737
738        @Override
739        public int getProgress() {
740            return ( int )( ( ( float )m_currentBytes / m_totalBytes ) * 100 + 0.5 );
741        }
742    }
743
744}
745
746