Exemple #1
0
        /// <exception cref="System.IO.IOException"/>
        private void ValidateRequest(ServletContext context, Configuration conf, HttpServletRequest
                                     request, HttpServletResponse response, FSImage nnImage, string theirStorageInfoString
                                     )
        {
            if (UserGroupInformation.IsSecurityEnabled() && !IsValidRequestor(context, request
                                                                              .GetUserPrincipal().GetName(), conf))
            {
                string errorMsg = "Only Namenode, Secondary Namenode, and administrators may access "
                                  + "this servlet";
                response.SendError(HttpServletResponse.ScForbidden, errorMsg);
                Log.Warn("Received non-NN/SNN/administrator request for image or edits from " + request
                         .GetUserPrincipal().GetName() + " at " + request.GetRemoteHost());
                throw new IOException(errorMsg);
            }
            string myStorageInfoString = nnImage.GetStorage().ToColonSeparatedString();

            if (theirStorageInfoString != null && !myStorageInfoString.Equals(theirStorageInfoString
                                                                              ))
            {
                string errorMsg = "This namenode has storage info " + myStorageInfoString + " but the secondary expected "
                                  + theirStorageInfoString;
                response.SendError(HttpServletResponse.ScForbidden, errorMsg);
                Log.Warn("Received an invalid request file transfer request " + "from a secondary with storage info "
                         + theirStorageInfoString);
                throw new IOException(errorMsg);
            }
        }
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            FileInputStream editFileIn = null;

            try
            {
                ServletContext context = GetServletContext();
                Configuration  conf    = (Configuration)GetServletContext().GetAttribute(JspHelper.CurrentConf
                                                                                         );
                string journalId = request.GetParameter(JournalIdParam);
                QuorumJournalManager.CheckJournalId(journalId);
                JNStorage storage = JournalNodeHttpServer.GetJournalFromContext(context, journalId
                                                                                ).GetStorage();
                // Check security
                if (!CheckRequestorOrSendError(conf, request, response))
                {
                    return;
                }
                // Check that the namespace info is correct
                if (!CheckStorageInfoOrSendError(storage, request, response))
                {
                    return;
                }
                long segmentTxId       = ServletUtil.ParseLongParam(request, SegmentTxidParam);
                FileJournalManager fjm = storage.GetJournalManager();
                FilePath           editFile;
                lock (fjm)
                {
                    // Synchronize on the FJM so that the file doesn't get finalized
                    // out from underneath us while we're in the process of opening
                    // it up.
                    FileJournalManager.EditLogFile elf = fjm.GetLogFile(segmentTxId);
                    if (elf == null)
                    {
                        response.SendError(HttpServletResponse.ScNotFound, "No edit log found starting at txid "
                                           + segmentTxId);
                        return;
                    }
                    editFile = elf.GetFile();
                    ImageServlet.SetVerificationHeadersForGet(response, editFile);
                    ImageServlet.SetFileNameHeaders(response, editFile);
                    editFileIn = new FileInputStream(editFile);
                }
                DataTransferThrottler throttler = ImageServlet.GetThrottler(conf);
                // send edits
                TransferFsImage.CopyFileToStream(response.GetOutputStream(), editFile, editFileIn
                                                 , throttler);
            }
            catch (Exception t)
            {
                string errMsg = "getedit failed. " + StringUtils.StringifyException(t);
                response.SendError(HttpServletResponse.ScInternalServerError, errMsg);
                throw new IOException(errMsg);
            }
            finally
            {
                IOUtils.CloseStream(editFileIn);
            }
        }
Exemple #3
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest req, HttpServletResponse res)
            {
                string queryString = req.GetQueryString();

                switch (counter)
                {
                case 0:
                {
                    VerifyQuery(queryString, "SUCCEEDED");
                    break;
                }

                case 2:
                {
                    VerifyQuery(queryString, "KILLED");
                    break;
                }

                case 4:
                {
                    VerifyQuery(queryString, "FAILED");
                    break;
                }
                }
                if (counter % 2 == 0)
                {
                    res.SendError(HttpServletResponse.ScBadRequest, "forcing error");
                }
                else
                {
                    res.SetStatus(HttpServletResponse.ScOk);
                }
                counter++;
            }
Exemple #4
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoPut(HttpServletRequest request, HttpServletResponse response
                               )
 {
     try
     {
         ServletContext context = GetServletContext();
         FSImage        nnImage = NameNodeHttpServer.GetFsImageFromContext(context);
         Configuration  conf    = (Configuration)GetServletContext().GetAttribute(JspHelper.CurrentConf
                                                                                  );
         ImageServlet.PutImageParams parsedParams = new ImageServlet.PutImageParams(request
                                                                                    , response, conf);
         NameNodeMetrics metrics = NameNode.GetNameNodeMetrics();
         ValidateRequest(context, conf, request, response, nnImage, parsedParams.GetStorageInfoString
                             ());
         UserGroupInformation.GetCurrentUser().DoAs(new _PrivilegedExceptionAction_458(parsedParams
                                                                                       , nnImage, response, request, conf, metrics));
     }
     catch (Exception t)
     {
         // Metrics non-null only when used inside name node
         // Now that we have a new checkpoint, we might be able to
         // remove some old ones.
         string errMsg = "PutImage failed. " + StringUtils.StringifyException(t);
         response.SendError(HttpServletResponse.ScGone, errMsg);
         throw new IOException(errMsg);
     }
 }
        /// <exception cref="System.IO.IOException"/>
        private bool CheckStorageInfoOrSendError(JNStorage storage, HttpServletRequest request
                                                 , HttpServletResponse response)
        {
            int    myNsId                 = storage.GetNamespaceID();
            string myClusterId            = storage.GetClusterID();
            string theirStorageInfoString = StringEscapeUtils.EscapeHtml(request.GetParameter
                                                                             (StorageinfoParam));

            if (theirStorageInfoString != null)
            {
                int theirNsId = StorageInfo.GetNsIdFromColonSeparatedString(theirStorageInfoString
                                                                            );
                string theirClusterId = StorageInfo.GetClusterIdFromColonSeparatedString(theirStorageInfoString
                                                                                         );
                if (myNsId != theirNsId || !myClusterId.Equals(theirClusterId))
                {
                    string msg = "This node has namespaceId '" + myNsId + " and clusterId '" + myClusterId
                                 + "' but the requesting node expected '" + theirNsId + "' and '" + theirClusterId
                                 + "'";
                    response.SendError(HttpServletResponse.ScForbidden, msg);
                    Log.Warn("Received an invalid request file transfer request from " + request.GetRemoteAddr
                                 () + ": " + msg);
                    return(false);
                }
            }
            return(true);
        }
Exemple #6
0
        /// <summary>
        /// Enforces the content-type to be application/octet-stream for
        /// POST and PUT requests.
        /// </summary>
        /// <param name="request">servlet request.</param>
        /// <param name="response">servlet response.</param>
        /// <param name="chain">filter chain.</param>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurrs.</exception>
        /// <exception cref="Javax.Servlet.ServletException">thrown if a servet error occurrs.
        ///     </exception>
        public virtual void DoFilter(ServletRequest request, ServletResponse response, FilterChain
                                     chain)
        {
            bool contentTypeOK          = true;
            HttpServletRequest  httpReq = (HttpServletRequest)request;
            HttpServletResponse httpRes = (HttpServletResponse)response;
            string method = httpReq.GetMethod();

            if (method.Equals("PUT") || method.Equals("POST"))
            {
                string op = httpReq.GetParameter(HttpFSFileSystem.OpParam);
                if (op != null && UploadOperations.Contains(StringUtils.ToUpperCase(op)))
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase("true", httpReq.GetParameter(HttpFSParametersProvider.DataParam
                                                                                      .Name)))
                    {
                        string contentType = httpReq.GetContentType();
                        contentTypeOK = Sharpen.Runtime.EqualsIgnoreCase(HttpFSFileSystem.UploadContentType
                                                                         , contentType);
                    }
                }
            }
            if (contentTypeOK)
            {
                chain.DoFilter(httpReq, httpRes);
            }
            else
            {
                httpRes.SendError(HttpServletResponse.ScBadRequest, "Data upload requests must have content-type set to '"
                                  + HttpFSFileSystem.UploadContentType + "'");
            }
        }
Exemple #7
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            UserGroupInformation ugi;
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);

            try
            {
                ugi = GetUGI(req, conf);
            }
            catch (IOException ioe)
            {
                Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr
                             (), ioe);
                resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user"
                               );
                return;
            }
            NameNode nn          = NameNodeHttpServer.GetNameNodeFromContext(context);
            string   tokenString = req.GetParameter(Token);

            if (tokenString == null)
            {
                resp.SendError(HttpServletResponse.ScMultipleChoices, "Token to renew not specified"
                               );
            }
            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>();
            token.DecodeFromUrlString(tokenString);
            try
            {
                long        result = ugi.DoAs(new _PrivilegedExceptionAction_73(nn, token));
                PrintWriter os     = new PrintWriter(new OutputStreamWriter(resp.GetOutputStream(), Charsets
                                                                            .Utf8));
                os.WriteLine(result);
                os.Close();
            }
            catch (Exception e)
            {
                // transfer exception over the http
                string exceptionClass = e.GetType().FullName;
                string exceptionMsg   = e.GetLocalizedMessage();
                string strException   = exceptionClass + ";" + exceptionMsg;
                Log.Info("Exception while renewing token. Re-throwing. s=" + strException, e);
                resp.SendError(HttpServletResponse.ScInternalServerError, strException);
            }
        }
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            UserGroupInformation ugi;
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);

            try
            {
                ugi = GetUGI(req, conf);
            }
            catch (IOException ioe)
            {
                Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr
                             (), ioe);
                resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user"
                               );
                return;
            }
            Log.Info("Sending token: {" + ugi.GetUserName() + "," + req.GetRemoteAddr() + "}"
                     );
            NameNode         nn           = NameNodeHttpServer.GetNameNodeFromContext(context);
            string           renewer      = req.GetParameter(Renewer);
            string           renewerFinal = (renewer == null) ? req.GetUserPrincipal().GetName() : renewer;
            DataOutputStream dos          = null;

            try
            {
                dos = new DataOutputStream(resp.GetOutputStream());
                DataOutputStream dosFinal = dos;
                // for doAs block
                ugi.DoAs(new _PrivilegedExceptionAction_69(nn, ugi, renewerFinal, dosFinal));
            }
            catch (Exception e)
            {
                Log.Info("Exception while sending token. Re-throwing ", e);
                resp.SendError(HttpServletResponse.ScInternalServerError);
            }
            finally
            {
                if (dos != null)
                {
                    dos.Close();
                }
            }
        }
        /// <summary>Service a GET request as described below.</summary>
        /// <remarks>
        /// Service a GET request as described below.
        /// Request:
        /// <c>GET http://&lt;nn&gt;:&lt;port&gt;/data[/&lt;path&gt;] HTTP/1.1</c>
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            Configuration        conf = NameNodeHttpServer.GetConfFromContext(GetServletContext());
            UserGroupInformation ugi  = GetUGI(request, conf);

            try
            {
                ugi.DoAs(new _PrivilegedExceptionAction_116(this, request, response, ugi));
            }
            catch (IOException e)
            {
                response.SendError(400, e.Message);
            }
            catch (Exception e)
            {
                response.SendError(400, e.Message);
            }
        }
 /// <exception cref="System.IO.IOException"/>
 private bool CheckRequestorOrSendError(Configuration conf, HttpServletRequest request
                                        , HttpServletResponse response)
 {
     if (UserGroupInformation.IsSecurityEnabled() && !IsValidRequestor(request, conf))
     {
         response.SendError(HttpServletResponse.ScForbidden, "Only Namenode and another JournalNode may access this servlet"
                            );
         Log.Warn("Received non-NN/JN request for edits from " + request.GetRemoteHost());
         return(false);
     }
     return(true);
 }
Exemple #11
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            UserGroupInformation ugi;
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);

            try
            {
                ugi = GetUGI(req, conf);
            }
            catch (IOException ioe)
            {
                Log.Info("Request for token received with no authentication from " + req.GetRemoteAddr
                             (), ioe);
                resp.SendError(HttpServletResponse.ScForbidden, "Unable to identify or authenticate user"
                               );
                return;
            }
            NameNode nn          = NameNodeHttpServer.GetNameNodeFromContext(context);
            string   tokenString = req.GetParameter(Token);

            if (tokenString == null)
            {
                resp.SendError(HttpServletResponse.ScMultipleChoices, "Token to renew not specified"
                               );
            }
            Org.Apache.Hadoop.Security.Token.Token <DelegationTokenIdentifier> token = new Org.Apache.Hadoop.Security.Token.Token
                                                                                       <DelegationTokenIdentifier>();
            token.DecodeFromUrlString(tokenString);
            try
            {
                ugi.DoAs(new _PrivilegedExceptionAction_70(nn, token));
            }
            catch (Exception e)
            {
                Log.Info("Exception while cancelling token. Re-throwing. ", e);
                resp.SendError(HttpServletResponse.ScInternalServerError, e.Message);
            }
        }
Exemple #12
0
            /// <exception cref="Javax.Servlet.ServletException"/>
            /// <exception cref="System.IO.IOException"/>
            protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                          )
            {
                ServletContext       context  = GetServletContext();
                Configuration        conf     = NameNodeHttpServer.GetConfFromContext(context);
                UserGroupInformation ugi      = GetUGI(request, conf);
                NameNode             namenode = NameNodeHttpServer.GetNameNodeFromContext(context);
                DatanodeID           datanode = NamenodeJspHelper.GetRandomDatanode(namenode);

                try
                {
                    response.SendRedirect(CreateRedirectURL(ugi, datanode, request, namenode).ToString
                                              ());
                }
                catch (IOException e)
                {
                    response.SendError(400, e.Message);
                }
            }
Exemple #13
0
        /// <summary>Handle fsck request</summary>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            IDictionary <string, string[]> pmap = request.GetParameterMap();
            PrintWriter @out          = response.GetWriter();
            IPAddress   remoteAddress = Sharpen.Extensions.GetAddressByName(request.GetRemoteAddr
                                                                                ());
            ServletContext       context = GetServletContext();
            Configuration        conf    = NameNodeHttpServer.GetConfFromContext(context);
            UserGroupInformation ugi     = GetUGI(request, conf);

            try
            {
                ugi.DoAs(new _PrivilegedExceptionAction_58(context, conf, pmap, @out, remoteAddress
                                                           ));
            }
            catch (Exception e)
            {
                response.SendError(400, e.Message);
            }
        }
        /// <summary>Service a GET request as described below.</summary>
        /// <remarks>
        /// Service a GET request as described below.
        /// Request:
        /// <c>GET http://&lt;nn&gt;:&lt;port&gt;/listPaths[/&lt;path&gt;][&lt;?option&gt;[&option]*] HTTP/1.1
        ///     </c>
        /// Where <i>option</i> (default) in:
        /// recursive (&quot;no&quot;)
        /// filter (&quot;.*&quot;)
        /// exclude (&quot;\..*\.crc&quot;)
        /// Response: A flat list of files/directories in the following format:
        /// <c>
        /// &lt;listing path="..." recursive="(yes|no)" filter="..."
        /// time="yyyy-MM-dd hh:mm:ss UTC" version="..."&gt;
        /// &lt;directory path="..." modified="yyyy-MM-dd hh:mm:ss"/&gt;
        /// &lt;file path="..." modified="yyyy-MM-dd'T'hh:mm:ssZ" accesstime="yyyy-MM-dd'T'hh:mm:ssZ"
        /// blocksize="..."
        /// replication="..." size="..."/&gt;
        /// &lt;/listing&gt;
        /// </c>
        /// </remarks>
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            PrintWriter  @out = response.GetWriter();
            XMLOutputter doc  = new XMLOutputter(@out, "UTF-8");
            IDictionary <string, string> root = BuildRoot(request, doc);
            string path     = root["path"];
            string filePath = ServletUtil.GetDecodedPath(request, "/listPaths");

            try
            {
                bool            recur   = "yes".Equals(root["recursive"]);
                Sharpen.Pattern filter  = Sharpen.Pattern.Compile(root["filter"]);
                Sharpen.Pattern exclude = Sharpen.Pattern.Compile(root["exclude"]);
                Configuration   conf    = (Configuration)GetServletContext().GetAttribute(JspHelper.CurrentConf
                                                                                          );
                GetUGI(request, conf).DoAs(new _PrivilegedExceptionAction_149(this, doc, root, filePath
                                                                              , path, exclude, filter, recur));
            }
            catch (IOException ioe)
            {
                WriteXml(ioe, path, doc);
            }
            catch (Exception e)
            {
                Log.Warn("ListPathServlet encountered InterruptedException", e);
                response.SendError(400, e.Message);
            }
            finally
            {
                if (doc != null)
                {
                    doc.EndDocument();
                }
                if (@out != null)
                {
                    @out.Close();
                }
            }
        }
Exemple #15
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoPost(HttpServletRequest req, HttpServletResponse resp)
        {
            Log.Info("POST");
            resp.SetContentType("text/html");
            PrintWriter    @out     = resp.GetWriter();
            Reconfigurable reconf   = GetReconfigurable(req);
            string         nodeName = reconf.GetType().GetCanonicalName();

            PrintHeader(@out, nodeName);
            try
            {
                ApplyChanges(@out, reconf, req);
            }
            catch (ReconfigurationException e)
            {
                resp.SendError(HttpServletResponse.ScInternalServerError, StringUtils.StringifyException
                                   (e));
                return;
            }
            @out.WriteLine("<p><a href=\"" + req.GetServletPath() + "\">back</a></p>");
            PrintFooter(@out);
        }
Exemple #16
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            if (!HttpServer2.IsInstrumentationAccessAllowed(GetServletContext(), request, response
                                                            ))
            {
                return;
            }
            string format = request.GetParameter(FormatParam);

            if (null == format)
            {
                format = FormatXml;
            }
            if (FormatXml.Equals(format))
            {
                response.SetContentType("text/xml; charset=utf-8");
            }
            else
            {
                if (FormatJson.Equals(format))
                {
                    response.SetContentType("application/json; charset=utf-8");
                }
            }
            TextWriter @out = response.GetWriter();

            try
            {
                WriteResponse(GetConfFromContext(), @out, format);
            }
            catch (ConfServlet.BadFormatException bfe)
            {
                response.SendError(HttpServletResponse.ScBadRequest, bfe.Message);
            }
            @out.Close();
        }
Exemple #17
0
 /// <exception cref="Javax.Servlet.ServletException"/>
 /// <exception cref="System.IO.IOException"/>
 protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                               )
 {
     try
     {
         ServletContext context = GetServletContext();
         FSImage        nnImage = NameNodeHttpServer.GetFsImageFromContext(context);
         ImageServlet.GetImageParams parsedParams = new ImageServlet.GetImageParams(request
                                                                                    , response);
         Configuration   conf    = (Configuration)context.GetAttribute(JspHelper.CurrentConf);
         NameNodeMetrics metrics = NameNode.GetNameNodeMetrics();
         ValidateRequest(context, conf, request, response, nnImage, parsedParams.GetStorageInfoString
                             ());
         UserGroupInformation.GetCurrentUser().DoAs(new _PrivilegedExceptionAction_98(parsedParams
                                                                                      , nnImage, metrics, response, conf));
     }
     catch (Exception t)
     {
         // Metrics non-null only when used inside name node
         // Metrics non-null only when used inside name node
         // Potential race where the file was deleted while we were in the
         // process of setting headers!
         // It's possible the file could be deleted after this point, but
         // we've already opened the 'fis' stream.
         // It's also possible length could change, but this would be
         // detected by the client side as an inaccurate length header.
         // send file
         string errMsg = "GetImage failed. " + StringUtils.StringifyException(t);
         response.SendError(HttpServletResponse.ScGone, errMsg);
         throw new IOException(errMsg);
     }
     finally
     {
         response.GetOutputStream().Close();
     }
 }
Exemple #18
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     "/>
        public override bool ManagementOperation(AuthenticationToken token, HttpServletRequest
                                                 request, HttpServletResponse response)
        {
            bool   requestContinues = true;
            string op = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                  .OpParam);

            op = (op != null) ? StringUtils.ToUpperCase(op) : null;
            if (DelegationTokenOps.Contains(op) && !request.GetMethod().Equals("OPTIONS"))
            {
                DelegationTokenAuthenticator.DelegationTokenOperation dtOp = DelegationTokenAuthenticator.DelegationTokenOperation
                                                                             .ValueOf(op);
                if (dtOp.GetHttpMethod().Equals(request.GetMethod()))
                {
                    bool doManagement;
                    if (dtOp.RequiresKerberosCredentials() && token == null)
                    {
                        token = Authenticate(request, response);
                        if (token == null)
                        {
                            requestContinues = false;
                            doManagement     = false;
                        }
                        else
                        {
                            doManagement = true;
                        }
                    }
                    else
                    {
                        doManagement = true;
                    }
                    if (doManagement)
                    {
                        UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.CreateRemoteUser
                                                              (token.GetUserName()) : null;
                        // Create the proxy user if doAsUser exists
                        string doAsUser = DelegationTokenAuthenticationFilter.GetDoAs(request);
                        if (requestUgi != null && doAsUser != null)
                        {
                            requestUgi = UserGroupInformation.CreateProxyUser(doAsUser, requestUgi);
                            try
                            {
                                ProxyUsers.Authorize(requestUgi, request.GetRemoteHost());
                            }
                            catch (AuthorizationException ex)
                            {
                                HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden
                                                                                  , ex);
                                return(false);
                            }
                        }
                        IDictionary map = null;
                        switch (dtOp)
                        {
                        case DelegationTokenAuthenticator.DelegationTokenOperation.Getdelegationtoken:
                        {
                            if (requestUgi == null)
                            {
                                throw new InvalidOperationException("request UGI cannot be NULL");
                            }
                            string renewer = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                       .RenewerParam);
                            try
                            {
                                Org.Apache.Hadoop.Security.Token.Token <object> dToken = tokenManager.CreateToken(
                                    requestUgi, renewer);
                                map = DelegationTokenToJSON(dToken);
                            }
                            catch (IOException ex)
                            {
                                throw new AuthenticationException(ex.ToString(), ex);
                            }
                            break;
                        }

                        case DelegationTokenAuthenticator.DelegationTokenOperation.Renewdelegationtoken:
                        {
                            if (requestUgi == null)
                            {
                                throw new InvalidOperationException("request UGI cannot be NULL");
                            }
                            string tokenToRenew = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                            .TokenParam);
                            if (tokenToRenew == null)
                            {
                                response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]"
                                                                                                          , dtOp, KerberosDelegationTokenAuthenticator.TokenParam));
                                requestContinues = false;
                            }
                            else
                            {
                                Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new
                                                                                                                Org.Apache.Hadoop.Security.Token.Token();
                                try
                                {
                                    dt.DecodeFromUrlString(tokenToRenew);
                                    long expirationTime = tokenManager.RenewToken(dt, requestUgi.GetShortUserName());
                                    map         = new Hashtable();
                                    map["long"] = expirationTime;
                                }
                                catch (IOException ex)
                                {
                                    throw new AuthenticationException(ex.ToString(), ex);
                                }
                            }
                            break;
                        }

                        case DelegationTokenAuthenticator.DelegationTokenOperation.Canceldelegationtoken:
                        {
                            string tokenToCancel = ServletUtils.GetParameter(request, KerberosDelegationTokenAuthenticator
                                                                             .TokenParam);
                            if (tokenToCancel == null)
                            {
                                response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Operation [{0}] requires the parameter [{1}]"
                                                                                                          , dtOp, KerberosDelegationTokenAuthenticator.TokenParam));
                                requestContinues = false;
                            }
                            else
                            {
                                Org.Apache.Hadoop.Security.Token.Token <AbstractDelegationTokenIdentifier> dt = new
                                                                                                                Org.Apache.Hadoop.Security.Token.Token();
                                try
                                {
                                    dt.DecodeFromUrlString(tokenToCancel);
                                    tokenManager.CancelToken(dt, (requestUgi != null) ? requestUgi.GetShortUserName()
                                                                                         : null);
                                }
                                catch (IOException)
                                {
                                    response.SendError(HttpServletResponse.ScNotFound, "Invalid delegation token, cannot cancel"
                                                       );
                                    requestContinues = false;
                                }
                            }
                            break;
                        }
                        }
                        if (requestContinues)
                        {
                            response.SetStatus(HttpServletResponse.ScOk);
                            if (map != null)
                            {
                                response.SetContentType(MediaType.ApplicationJson);
                                TextWriter   writer     = response.GetWriter();
                                ObjectMapper jsonMapper = new ObjectMapper();
                                jsonMapper.WriteValue(writer, map);
                                writer.Write(Enter);
                                writer.Flush();
                            }
                            requestContinues = false;
                        }
                    }
                }
                else
                {
                    response.SendError(HttpServletResponse.ScBadRequest, MessageFormat.Format("Wrong HTTP method [{0}] for operation [{1}], it should be "
                                                                                              + "[{2}]", request.GetMethod(), dtOp, dtOp.GetHttpMethod()));
                    requestContinues = false;
                }
            }
            return(requestContinues);
        }
        /// <summary>
        /// If the request has a valid authentication token it allows the request to continue to the target resource,
        /// otherwise it triggers an authentication sequence using the configured
        /// <see cref="AuthenticationHandler"/>
        /// .
        /// </summary>
        /// <param name="request">the request object.</param>
        /// <param name="response">the response object.</param>
        /// <param name="filterChain">the filter chain object.</param>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception>
        /// <exception cref="Javax.Servlet.ServletException">thrown if a processing error occurred.
        ///     </exception>
        public virtual void DoFilter(ServletRequest request, ServletResponse response, FilterChain
                                     filterChain)
        {
            bool unauthorizedResponse = true;
            int  errCode = HttpServletResponse.ScUnauthorized;
            AuthenticationException authenticationEx = null;
            HttpServletRequest      httpRequest      = (HttpServletRequest)request;
            HttpServletResponse     httpResponse     = (HttpServletResponse)response;
            bool isHttps = "https".Equals(httpRequest.GetScheme());

            try
            {
                bool newToken = false;
                AuthenticationToken token;
                try
                {
                    token = GetToken(httpRequest);
                }
                catch (AuthenticationException ex)
                {
                    Log.Warn("AuthenticationToken ignored: " + ex.Message);
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token            = null;
                }
                if (authHandler.ManagementOperation(token, httpRequest, httpResponse))
                {
                    if (token == null)
                    {
                        if (Log.IsDebugEnabled())
                        {
                            Log.Debug("Request [{}] triggering authentication", GetRequestURL(httpRequest));
                        }
                        token = authHandler.Authenticate(httpRequest, httpResponse);
                        if (token != null && token.GetExpires() != 0 && token != AuthenticationToken.Anonymous)
                        {
                            token.SetExpires(Runtime.CurrentTimeMillis() + GetValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null)
                    {
                        unauthorizedResponse = false;
                        if (Log.IsDebugEnabled())
                        {
                            Log.Debug("Request [{}] user [{}] authenticated", GetRequestURL(httpRequest), token
                                      .GetUserName());
                        }
                        AuthenticationToken authToken = token;
                        httpRequest = new _HttpServletRequestWrapper_532(authToken, httpRequest);
                        if (newToken && !token.IsExpired() && token != AuthenticationToken.Anonymous)
                        {
                            string signedToken = signer.Sign(token.ToString());
                            CreateAuthCookie(httpResponse, signedToken, GetCookieDomain(), GetCookiePath(), token
                                             .GetExpires(), isHttps);
                        }
                        DoFilter(filterChain, httpRequest, httpResponse);
                    }
                }
                else
                {
                    unauthorizedResponse = false;
                }
            }
            catch (AuthenticationException ex)
            {
                // exception from the filter itself is fatal
                errCode          = HttpServletResponse.ScForbidden;
                authenticationEx = ex;
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("Authentication exception: " + ex.Message, ex);
                }
                else
                {
                    Log.Warn("Authentication exception: " + ex.Message);
                }
            }
            if (unauthorizedResponse)
            {
                if (!httpResponse.IsCommitted())
                {
                    CreateAuthCookie(httpResponse, string.Empty, GetCookieDomain(), GetCookiePath(),
                                     0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.ScUnauthorized) && (!httpResponse.ContainsHeader
                                                                                (KerberosAuthenticator.WwwAuthenticate)))
                    {
                        errCode = HttpServletResponse.ScForbidden;
                    }
                    if (authenticationEx == null)
                    {
                        httpResponse.SendError(errCode, "Authentication required");
                    }
                    else
                    {
                        httpResponse.SendError(errCode, authenticationEx.Message);
                    }
                }
            }
        }
Exemple #20
0
        /// <exception cref="Javax.Servlet.ServletException"/>
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest request, HttpServletResponse response
                                      )
        {
            string path        = ServletUtil.GetDecodedPath(request, "/streamFile");
            string rawPath     = ServletUtil.GetRawPath(request, "/streamFile");
            string filename    = JspHelper.ValidatePath(path);
            string rawFilename = JspHelper.ValidatePath(rawPath);

            if (filename == null)
            {
                response.SetContentType("text/plain");
                PrintWriter @out = response.GetWriter();
                @out.Write("Invalid input");
                return;
            }
            Enumeration <string> reqRanges = request.GetHeaders("Range");

            if (reqRanges != null && !reqRanges.MoveNext())
            {
                reqRanges = null;
            }
            DFSClient dfs;

            try
            {
                dfs = GetDFSClient(request);
            }
            catch (Exception e)
            {
                response.SendError(400, e.Message);
                return;
            }
            HdfsDataInputStream @in   = null;
            OutputStream        out_1 = null;

            try
            {
                @in   = dfs.CreateWrappedInputStream(dfs.Open(filename));
                out_1 = response.GetOutputStream();
                long fileLen = @in.GetVisibleLength();
                if (reqRanges != null)
                {
                    IList <InclusiveByteRange> ranges = InclusiveByteRange.SatisfiableRanges(reqRanges
                                                                                             , fileLen);
                    StreamFile.SendPartialData(@in, out_1, response, fileLen, ranges);
                }
                else
                {
                    // No ranges, so send entire file
                    response.SetHeader("Content-Disposition", "attachment; filename=\"" + rawFilename
                                       + "\"");
                    response.SetContentType("application/octet-stream");
                    response.SetHeader(ContentLength, string.Empty + fileLen);
                    StreamFile.CopyFromOffset(@in, out_1, 0L, fileLen);
                }
                @in.Close();
                @in = null;
                out_1.Close();
                out_1 = null;
                dfs.Close();
                dfs = null;
            }
            catch (IOException ioe)
            {
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("response.isCommitted()=" + response.IsCommitted(), ioe);
                }
                throw;
            }
            finally
            {
                IOUtils.Cleanup(Log, @in);
                IOUtils.Cleanup(Log, out_1);
                IOUtils.Cleanup(Log, dfs);
            }
        }