// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


package google.registry.flows;

import static google.registry.flows.EppXmlTransformer.marshalWithLenientRetry;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;

import com.google.common.net.MediaType;
import google.registry.request.Response;
import google.registry.util.FormattingLogger;
import javax.inject.Inject;

/** Handle an EPP request and response. */
public class EppRequestHandler {

  private static final MediaType APPLICATION_EPP_XML =
      MediaType.create("application", "epp+xml").withCharset(UTF_8);

  private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();

  @Inject EppController eppController;
  @Inject Response response;
  @Inject EppRequestHandler() {}

  /** Handle an EPP request and write out a servlet response. */
  public void executeEpp(
      SessionMetadata sessionMetadata,
      TransportCredentials credentials,
      EppRequestSource eppRequestSource,
      boolean isDryRun,
      boolean isSuperuser,
      byte[] inputXmlBytes) {
    try {
      response.setPayload(new String(
          marshalWithLenientRetry(
              eppController.handleEppCommand(
                  sessionMetadata,
                  credentials,
                  eppRequestSource,
                  isDryRun,
                  isSuperuser,
                  inputXmlBytes)),
          UTF_8));
      response.setContentType(APPLICATION_EPP_XML);
      // Note that we always return 200 (OK) even if the EppController returns an error response.
      // This is because returning an non-OK HTTP status code will cause the proxy server to
      // silently close the connection without returning any data. The only time we will ever return
      // a non-OK status (400) is if we fail to muster even an EPP error response message. In that
      // case it's better to close the connection than to return garbage.
      response.setStatus(SC_OK);
    } catch (Exception e) {
      logger.warning(e, "handleEppCommand general exception");
      response.setStatus(SC_BAD_REQUEST);
    }
  }
}

@@ -612,17 +612,16 @@
 cense.%0A%0A
-%0A
 package 
@@ -723,16 +723,93 @@
 tRetry;%0A
+import static google.registry.model.eppoutput.Result.Code.SUCCESS_AND_CLOSE;%0A
 import s
@@ -1025,16 +1025,66 @@
 iaType;%0A
+import google.registry.model.eppoutput.EppOutput;%0A
 import g
@@ -1555,16 +1555,17 @@
 sponse;%0A
+%0A
   @Injec
@@ -1561,24 +1561,26 @@
 ;%0A%0A  @Inject
+%0A 
  EppRequestH
@@ -1904,79 +1904,30 @@
     
-response.setPayload(new String(%0A          marshalWithLenientRetry(%0A    
+EppOutput eppOutput =%0A
     
@@ -1978,20 +1978,16 @@
         
-    
 sessionM
@@ -1998,152 +1998,62 @@
 ata,
-%0A                  credentials,%0A                  eppRequestSource,%0A                  isDryRun,%0A                  isSuperuser,%0A                 
+ credentials, eppRequestSource, isDryRun, isSuperuser,
  inp
@@ -2067,20 +2067,82 @@
 tes)
-),
+;
 %0A      
-   
+response.setPayload(new String(marshalWithLenientRetry(eppOutput),
  UTF
@@ -2333,17 +2333,16 @@
 urning a
-n
  non-OK 
@@ -2663,16 +2663,16 @@
 arbage.%0A
-
       re
@@ -2696,16 +2696,686 @@
 SC_OK);%0A
+      // Per RFC 5734, a server receiving a logout command must end the EPP session and close the%0A      // TCP connection. Since the app itself only gets HttpServletRequest and is not aware of TCP%0A      // sessions, it simply sets the HTTP response header to indicate the connection should be%0A      // closed by the proxy. Whether the EPP proxy actually terminates the connection with the%0A      // client is up to its implementation.%0A      // See: https://tools.ietf.org/html/rfc5734#section-2%0A      if (eppOutput.isResponse()%0A          && eppOutput.getResponse().getResult().getCode() == SUCCESS_AND_CLOSE) %7B%0A        response.setHeader(%22Epp-Session%22, %22close%22);%0A      %7D%0A
     %7D ca

Set HTTP header when processing logout request