简体   繁体   中英

Trying to force Keep-alive via apache module

The task seems simple for me but I'm stumped. What I'm trying to achieve with this code is for connection:keep-alive to be added to every output header no matter what page I request from the server. Then later, I'll only add that header if the page returned gives a 301 or 302 (redirect status). This is because I don't want clients to have to open a new connection as a result of reaching a redirect page.

My code is shown below and I tried following instructions from http://www.apachetutor.org/dev/brigades but instead made things simpler and easier to understand.

The code compiles fine with apxs but it does not do anything to the output. What could I be doing wrong? I'm looking for a solution that won't waste unnecessary memory.

#include "httpd.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_config.h"
#include "apr_buckets.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "util_filter.h"
#include "http_request.h"

static apr_status_t OUTF(ap_filter_t *f,apr_bucket_brigade *pbbIn){
  char *lp=0;
  const char *data;
  request_rec* r=f->r;
  conn_rec* c=r->connection;
  apr_bucket *pbktIn;
  apr_size_t len;
  for (pbktIn=APR_BRIGADE_FIRST(pbbIn);pbktIn!=APR_BRIGADE_SENTINEL(pbbIn);pbktIn=APR_BUCKET_NEXT(pbktIn)){
    if(APR_BUCKET_IS_EOS(pbktIn)){continue;}
    if (apr_bucket_read(pbktIn,&data,&len,APR_BLOCK_READ) != APR_SUCCESS){continue;}
      if (!lp){
        lp=strstr(data,"\r\n");
        if (lp){
          apr_bucket_split(pbktIn,(lp-data));
          pbktIn=APR_BUCKET_NEXT(pbktIn);
          const char* ka="connection:keep-alive\r\n";
          //trying to insert "connection:keep-alive" into output data
          APR_BUCKET_INSERT_BEFORE(pbktIn,apr_bucket_transient_create(ka,strlen(ka),c->bucket_alloc));
          apr_bucket_split(pbktIn,strlen(ka));
          APR_BUCKET_REMOVE(pbktIn);
          pbktIn=APR_BUCKET_NEXT(pbktIn);
        }
      }
    }
  return ap_pass_brigade(f->next,pbbIn);
}

static void INS(request_rec *r){ap_add_output_filter("30X",NULL,r,r->connection);}

static void f301_register_hooks(apr_pool_t *p){
  ap_hook_insert_filter(INS,NULL,NULL,APR_HOOK_FIRST);
  ap_register_output_filter("30X",OUTF,NULL,AP_FTYPE_RESOURCE);
}

module AP_MODULE_DECLARE_DATA f301_module = {STANDARD20_MODULE_STUFF,NULL,NULL,NULL,NULL,NULL,f301_register_hooks};

In HTTP 1.1, persistent connections are the default. Just make sure KeepAlive on is in your server config and don't overthink it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM