I'm trying to process the response data inside a transformation and
based on the processing send a 301 response header to the client with
a different redirect URL each time.
The code was unfortunately crashing (even on TS 3.0)

In an attempt to locate the crash i created a minimalistic code which
is an amalgamation of null transform and redirect-1 plugin codes
(attached).

This code compiles and crashes with the following callstack

#0  operator= (this=0x464ec250, p=0x464ec380) at ../../lib/ts/Ptr.h:414
#1  clone_reader (this=0x464ec250, p=0x464ec380) at
../../iocore/eventsystem/P_IOBuffer.h:859
#2  HttpTunnel::producer_run (this=0x464ec250, p=0x464ec380) at
HttpTunnel.cc:821
#3  0x081a4a21 in HttpTunnel::tunnel_run (this=0x464ec250, p_arg=0x0)
at HttpTunnel.cc:694
#4  0x0816cab0 in HttpSM::setup_internal_transfer (this=0x464eaa90,
handler_arg=(int (HttpSM::*)(HttpSM *, int, void *)) 0x81549b0
<HttpSM::tunnel_handler(int, void*)>)
    at HttpSM.cc:5477
#5  0x0816cfe7 in HttpSM::handle_api_return (this=0x464eaa90) at HttpSM.cc:1574
#6  0x081642c8 in HttpSM::state_api_callout (this=0x464eaa90,
event=60000, data=0x0) at HttpSM.cc:1448
#7  0x081693bf in HttpSM::state_api_callback (this=0x464eaa90,
event=60000, data=0x0) at HttpSM.cc:1267
#8  0x080e3ea9 in TSHttpTxnReenable (txnp=0x464eaa90,
event=TS_EVENT_HTTP_CONTINUE) at InkAPI.cc:5350
#9  0x4005a1ad in handle_response (contp=0x453a4360,
event=TS_EVENT_HTTP_SEND_RESPONSE_HDR, edata=0x464eaa90) at
redirect-1.c:133
#10 redirect_plugin (contp=0x453a4360,
event=TS_EVENT_HTTP_SEND_RESPONSE_HDR, edata=0x464eaa90) at
redirect-1.c:152
#11 0x08164534 in HttpSM::state_api_callout (this=0x464eaa90, event=0,
data=0x0) at HttpSM.cc:1374
#12 0x0816e5c7 in HttpSM::do_api_callout() ()
#13 0x0816ba6b in HttpSM::set_next_state (this=0x464eaa90) at HttpSM.cc:6684
#14 0x08154e1b in HttpSM::call_transact_and_set_next_state
(this=0x464eaa90, f=0x8189ed0
<HttpTransact::HandleApiErrorJump(HttpTransact::State*)>) at
HttpSM.cc:6325
#15 0x08164427 in HttpSM::state_api_callout (this=0x464eaa90,
event=60001, data=0x0) at HttpSM.cc:1460
#16 0x081693bf in HttpSM::state_api_callback (this=0x464eaa90,
event=60001, data=0x0) at HttpSM.cc:1267
#17 0x080e3ea9 in TSHttpTxnReenable (txnp=0x464eaa90,
event=TS_EVENT_HTTP_ERROR) at InkAPI.cc:5350
#18 0x4005a376 in handle_transform (contp=0x973fff0,
event=TS_EVENT_IMMEDIATE, edata=0x46395dd0) at redirect-1.c:271
#19 eventHandler (contp=0x973fff0, event=TS_EVENT_IMMEDIATE,
edata=0x46395dd0) at redirect-1.c:371
#20 0x082e8702 in handleEvent (this=0x40b4e008, e=0x46395dd0,
calling_code=1) at I_Continuation.h:146
#21 EThread::process_event (this=0x40b4e008, e=0x46395dd0,
calling_code=1) at UnixEThread.cc:140
#22 0x082e912c in EThread::execute (this=0x40b4e008) at UnixEThread.cc:189
#23 0x082e6604 in spawn_thread_internal (a=0x96f0fa8) at Thread.cc:88
#24 0x40063cc9 in start_thread (arg=0x40e50b70) at pthread_create.c:304
#25 0x4057069e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:130


I think I am not using TSHttpTxnReenable the way it should be. I'd
like to know what the proper way to abort the transformation and place
the HTTP State Machine to the SEND_RESPONSE state would be.

Thanks,
Aniket Ray
/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
 */

/*
 *   redirect-1.c:
 *	an example program which redirects clients based on the source IP
 *
 *
 *	Usage:
 * 	(NT): Redirect.dll block_ip url_redirect
 * 	(Solaris): redirect-1.so block_ip url_redirect
 *
 *
 */

#include <stdio.h>
#include <string.h>

#if !defined (_WIN32)
#  include <unistd.h>
#  include <netinet/in.h>
#  include <arpa/inet.h>
#else
#  include <windows.h>
#endif

#include <ts/ts.h>

// This gets the PRI*64 types
 # define __STDC_FORMAT_MACROS 1
 # include <inttypes.h>


typedef struct
{
  TSVIO output_vio;
  TSIOBuffer output_buffer;
  TSIOBufferReader output_reader;
  TSHttpTxn txnp;
  TSCont externalCont;
} MyData;

static MyData *
my_data_alloc()
{
  MyData *data;

  data = (MyData *) TSmalloc(sizeof(MyData));
  data->txnp = NULL;
  data->externalCont = NULL;
  data->output_vio = NULL;
  data->output_buffer = NULL;
  data->output_reader = NULL;

  return data;
}

static void
my_data_destroy(MyData * data)
{
  if (data) {
    if (data->output_buffer)
      TSIOBufferDestroy(data->output_buffer);
    TSfree(data);
  }
}

void transformCreate (TSCont contp, TSHttpTxn txnp);

static void
handle_client_lookup(TSHttpTxn txnp, TSCont contp)
{
    transformCreate(contp, txnp);
    return;
}



static void
handle_response(TSHttpTxn txnp)
{
  TSMBuffer bufp;
  TSMLoc hdr_loc, newfield_loc;
  char *errormsg_body = "All requests from this IP address are redirected.\n";
  char *tmp_body;

  if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {
    TSError("couldn't retrieve client response header\n");
    goto done;
  }

  TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_MOVED_PERMANENTLY);
  TSHttpHdrReasonSet(bufp, hdr_loc,
                      TSHttpHdrReasonLookup(TS_HTTP_STATUS_MOVED_PERMANENTLY),
                      strlen(TSHttpHdrReasonLookup(TS_HTTP_STATUS_MOVED_PERMANENTLY)));

  TSMimeHdrFieldCreate(bufp, hdr_loc, &newfield_loc); /* Probably should check for errors ... */
  TSMimeHdrFieldNameSet(bufp, hdr_loc, newfield_loc, TS_MIME_FIELD_LOCATION, TS_MIME_LEN_LOCATION);
  TSMimeHdrFieldValueStringInsert(bufp, hdr_loc, newfield_loc, -1, "http://192.168.1.3:8080/deepika.flv";, sizeof("http://192.168.1.3:8080/deepika.flv";) - 1);
  TSMimeHdrFieldAppend(bufp, hdr_loc, newfield_loc);

  /*
   *  Note that we can't directly use errormsg_body, as TSHttpTxnErrorBodySet()
   *  will try to free the passed buffer with TSfree().
   */
  tmp_body = TSstrdup(errormsg_body);
  TSHttpTxnErrorBodySet(txnp, tmp_body, strlen(tmp_body), NULL);
  TSHandleMLocRelease(bufp, hdr_loc, newfield_loc);
  TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);


done:
  TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
}



static int
redirect_plugin(TSCont contp, TSEvent event, void *edata)
{

  TSHttpTxn txnp = (TSHttpTxn) edata;

  switch (event) {
  case TS_EVENT_HTTP_READ_REQUEST_HDR:

    handle_client_lookup(txnp, contp);
    return 0;

  case TS_EVENT_HTTP_SEND_RESPONSE_HDR:

    handle_response(txnp);
    return 0;

  default:
    break;
  }

  return 0;
}


int
check_ts_version()
{

  const char *ts_version = TSTrafficServerVersionGet();
  int result = 0;

  if (ts_version) {
    int major_ts_version = 0;
    int minor_ts_version = 0;
    int patch_ts_version = 0;

    if (sscanf(ts_version, "%d.%d.%d", &major_ts_version, &minor_ts_version, &patch_ts_version) != 3) {
      return 0;
    }

    /* Need at least TS 2.0 */
    if (major_ts_version >= 2) {
      result = 1;
    }

  }

  return result;
}

static void
handle_transform(TSCont contp)
{
  TSVConn output_conn;
  TSIOBuffer buf_test;
  TSVIO input_vio;
  MyData *data;
  int64_t towrite;
  int64_t avail;

  TSDebug("null-transform", "Entering handle_transform()");
  /* Get the output (downstream) vconnection where we'll write data to. */

  output_conn = TSTransformOutputVConnGet(contp);

  /* Get the write VIO for the write operation that was performed on
   * ourself. This VIO contains the buffer that we are to read from
   * as well as the continuation we are to call when the buffer is
   * empty. This is the input VIO (the write VIO for the upstream
   * vconnection).
   */
  input_vio = TSVConnWriteVIOGet(contp);

  /* Get our data structure for this operation. The private data
   * structure contains the output VIO and output buffer. If the
   * private data structure pointer is NULL, then we'll create it
   * and initialize its internals.
   */
  data = TSContDataGet(contp);
  if (!data->output_buffer) {
    data->output_buffer = TSIOBufferCreate();
    data->output_reader = TSIOBufferReaderAlloc(data->output_buffer);
    TSDebug("null-transform", "\tWriting %d bytes on VConn", TSVIONBytesGet(input_vio));
    //data->output_vio = TSVConnWrite(output_conn, contp, data->output_reader, INT32_MAX);
    data->output_vio = TSVConnWrite(output_conn, contp, data->output_reader, INT64_MAX);
    // data->output_vio = TSVConnWrite(output_conn, contp, data->output_reader, TSVIONBytesGet(input_vio));
  }

  /* We also check to see if the input VIO's buffer is non-NULL. A
   * NULL buffer indicates that the write operation has been
   * shutdown and that the upstream continuation does not want us to send any
   * more WRITE_READY or WRITE_COMPLETE events. For this simplistic
   * transformation that means we're done. In a more complex
   * transformation we might have to finish writing the transformed
   * data to our output connection.
   */
  buf_test = TSVIOBufferGet(input_vio);

  if (!buf_test) {
    TSVIONBytesSet(data->output_vio, TSVIONDoneGet(input_vio));
    TSVIOReenable(data->output_vio);
    return;
  }

  /* Determine how much data we have left to read. For this null
   * transform plugin this is also the amount of data we have left
   * to write to the output connection.
   */
  towrite = TSVIONTodoGet(input_vio);
  TSDebug("null-transform", "\ttoWrite is %" PRId64 "", towrite);

  if (towrite > 0) {
    /* The amount of data left to read needs to be truncated by
     * the amount of data actually in the read buffer.
     */
    avail = TSIOBufferReaderAvail(TSVIOReaderGet(input_vio));
    TSDebug("null-transform", "\tavail is %" PRId64 "", avail);
    if (towrite > avail) {
      towrite = avail;
    }

    if (towrite > 0) {
      /* Copy the data from the read buffer to the output buffer. */
      //TSIOBufferCopy(TSVIOBufferGet(data->output_vio), TSVIOReaderGet(input_vio), towrite, 0);
       MyData* data = TSContDataGet(contp);
       TSHttpTxnHookAdd(data->txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, data->externalCont);
    TSVIONBytesSet(data->output_vio, TSVIONDoneGet(input_vio));

    /* Call back the input VIO continuation to let it know that we
     * have completed the write operation.
     */

       TSHttpTxnReenable(data->txnp, TS_EVENT_HTTP_ERROR);

       return;

      /* Tell the read buffer that we have read the data and are no
       * longer interested in it.
       */
      TSIOBufferReaderConsume(TSVIOReaderGet(input_vio), towrite);

      /* Modify the input VIO to reflect how much data we've
       * completed.
       */
      TSVIONDoneSet(input_vio, TSVIONDoneGet(input_vio) + towrite);
    }
  }

  /* Now we check the input VIO to see if there is data left to
   * read.
   */
  if (TSVIONTodoGet(input_vio) > 0) {
    if (towrite > 0) {
      /* If there is data left to read, then we reenable the output
       * connection by reenabling the output VIO. This will wake up
       * the output connection and allow it to consume data from the
       * output buffer.
       */
      TSVIOReenable(data->output_vio);

      /* Call back the input VIO continuation to let it know that we
       * are ready for more data.
       */
      TSContCall(TSVIOContGet(input_vio), TS_EVENT_VCONN_WRITE_READY, input_vio);
    }
  } else {
    /* If there is no data left to read, then we modify the output
     * VIO to reflect how much data the output connection should
     * expect. This allows the output connection to know when it
     * is done reading. We then reenable the output connection so
     * that it can consume the data we just gave it.
     */
    TSVIONBytesSet(data->output_vio, TSVIONDoneGet(input_vio));
    TSVIOReenable(data->output_vio);

    /* Call back the input VIO continuation to let it know that we
     * have completed the write operation.
     */
    TSContCall(TSVIOContGet(input_vio), TS_EVENT_VCONN_WRITE_COMPLETE, input_vio);
  }
}


static int
eventHandler(TSCont contp, TSEvent event, void *edata)
{
    /* Check to see if the transformation has been closed by a call to
     * TSVConnClose.
     */
    TSDebug("http", "Entering eventHandler()");

    if (TSVConnClosedGet(contp)) {
        TSDebug("http", "\tVConn is closed");
        my_data_destroy(TSContDataGet(contp));
        TSContDestroy(contp);
        return 0;
    } else {
        switch (event) {
            case TS_EVENT_ERROR:
                {
                    TSVIO input_vio;

                    TSDebug("http", "\tEvent is TS_EVENT_ERROR");
                    /* Get the write VIO for the write operation that was
                     * performed on ourself. This VIO contains the continuation of
                     * our parent transformation. This is the input VIO.
                     */
                    input_vio = TSVConnWriteVIOGet(contp);

                    /* Call back the write VIO continuation to let it know that we
                     * have completed the write operation.
                     */
                    TSContCall(TSVIOContGet(input_vio), TS_EVENT_ERROR, input_vio);
                }
                break;
            case TS_EVENT_VCONN_WRITE_COMPLETE:
                TSDebug("http", "\tEvent is TS_EVENT_VCONN_WRITE_COMPLETE");
                /* When our output connection says that it has finished
                 * reading all the data we've written to it then we should
                 * shutdown the write portion of its connection to
                 * indicate that we don't want to hear about it anymore.
                 */
                TSVConnShutdown(TSTransformOutputVConnGet(contp), 0, 1);
                break;
            case TS_EVENT_VCONN_WRITE_READY:
                TSDebug("http", "\tEvent is TS_EVENT_VCONN_WRITE_READY");
            default:
                TSDebug("http", "\t(event is %d)", event);
                /* If we get a WRITE_READY event or any other type of
                 * event (sent, perhaps, because we were reenabled) then
                 * we'll attempt to transform more data.
                 */
                handle_transform(contp);
                break;
        }
    }

    return 0;
}

void 
transformCreate (TSCont extCont, TSHttpTxn txnp)
{
    TSCont      contp;
    TSDebug("http","Creating Transformation\n");
    MyData* data = my_data_alloc();
    //if default.config does not have caching turned on, disable all caching functions
    contp = TSTransformCreate(eventHandler, txnp);

    data->txnp = txnp;
    data->externalCont = extCont;
    TSContDataSet(contp, data);
    TSHttpTxnHookAdd (txnp, TS_HTTP_RESPONSE_TRANSFORM_HOOK, contp);
    TSHttpTxnReenable (txnp, TS_EVENT_HTTP_CONTINUE);
}
                        

void
TSPluginInit(int argc, const char *argv[])
{
  TSPluginRegistrationInfo info;

  info.plugin_name = "redirect-1";
  info.vendor_name = "MyCompany";
  info.support_email = "[email protected]";

  if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
    TSError("Plugin registration failed.\n");
  }

  if (!check_ts_version()) {
    TSError("Plugin requires Traffic Server 3.0 or later\n");
    return;
  }

 TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(redirect_plugin, NULL));
}

Reply via email to