Ejemplo n.º 1
0
param_list_t *param_create (const char *query_string) /* {{{ */
{
  char *tmp;
  param_list_t *pl;

  if (query_string == NULL)
    query_string = getenv ("QUERY_STRING");

  if (query_string == NULL)
    return (NULL);

  tmp = strdup (query_string);
  if (tmp == NULL)
    return (NULL);
  
  pl = malloc (sizeof (*pl));
  if (pl == NULL)
  {
    free (tmp);
    return (NULL);
  }
  memset (pl, 0, sizeof (*pl));

  parse_query_string (pl, tmp);

  free (tmp);
  return (pl);
} /* }}} param_list_t *param_create */
Ejemplo n.º 2
0
void
sl_request_set_opts(sl_vm_t* vm, sl_request_opts_t* opts)
{
    size_t i;
    SLVAL n, v, cookies;
    sl_string_t* str;
    sl_request_internal_opts_t* req = sl_alloc(vm->arena, sizeof(sl_request_internal_opts_t));
    req->method       = sl_make_cstring(vm, opts->method);
    req->uri          = sl_make_cstring(vm, opts->uri);
    req->path_info    = sl_make_cstring(vm, opts->path_info ? opts->path_info : "");
    req->query_string = sl_make_cstring(vm, opts->query_string ? opts->query_string : "");
    req->remote_addr  = sl_make_cstring(vm, opts->remote_addr);
    req->headers      = sl_make_dict(vm, 0, NULL);
    req->env          = sl_make_dict(vm, 0, NULL);
    req->get          = sl_make_dict(vm, 0, NULL);
    req->post         = sl_make_dict(vm, 0, NULL);
    req->post_data    = sl_make_string(vm, (uint8_t*)opts->post_data, opts->post_length);
    req->cookies      = sl_make_dict(vm, 0, NULL);
    for(i = 0; i < opts->header_count; i++) {
        n = sl_make_cstring(vm, opts->headers[i].name);
        v = sl_make_cstring(vm, opts->headers[i].value);
        sl_dict_set(vm, req->headers, n, v);
    }
    for(i = 0; i < opts->env_count; i++) {
        n = sl_make_cstring(vm, opts->env[i].name);
        v = sl_make_cstring(vm, opts->env[i].value);
        sl_dict_set(vm, req->env, n, v);
    }
    if(opts->query_string) {
        parse_query_string(vm, req->get, strlen(opts->query_string), (uint8_t*)opts->query_string);
    }
    if(opts->content_type && strcmp(opts->content_type, "application/x-www-form-urlencoded") == 0) {
        parse_query_string(vm, req->post, opts->post_length, (uint8_t*)opts->post_data);
    }
    cookies = sl_dict_get(vm, req->headers, sl_make_cstring(vm, "Cookie"));
    if(sl_is_a(vm, cookies, vm->lib.String)) {
        str = (sl_string_t*)sl_get_ptr(cookies);
        parse_cookie_string(vm, req->cookies, str->buff_len, str->buff);
    }
    req->params = sl_dict_merge(vm, req->get, req->post);
    sl_vm_store_put(vm, &Request_opts, sl_make_ptr((sl_object_t*)req));
}
Ejemplo n.º 3
0
bool parse_url(const std::string url,
               parsed_url_type& parsed_url,
               bool parse_path,
               bool parse_query)
{
    if (!(parsed_url.path.empty() && parsed_url.path_components.empty())) {
        // Already parsed
        return true;
    }

    http_parser_url p;
    if (::http_parser_parse_url(url.c_str(), url.length(), false, &p)) return false;

    if (p.field_set & (1 << ::UF_SCHEMA)) {
        parsed_url.schema.assign(url.begin() + p.field_data[UF_SCHEMA].off,
                                 url.begin() + p.field_data[UF_SCHEMA].off
                                     + p.field_data[UF_SCHEMA].len);
    }
    if (p.field_set & (1 << ::UF_HOST)) {
        parsed_url.host.assign(url.begin() + p.field_data[UF_HOST].off,
                               url.begin() + p.field_data[UF_HOST].off + p.field_data[UF_HOST].len);
    }
    if (p.field_set & (1 << ::UF_PORT)) {
        parsed_url.port = p.port;
    }
    if (p.field_set & (1 << ::UF_PATH)) {
        parsed_url.path.assign(url.begin() + p.field_data[UF_PATH].off,
                               url.begin() + p.field_data[UF_PATH].off + p.field_data[UF_PATH].len);
        if (parse_path && !parse_path_components(parsed_url.path, parsed_url.path_components))
            return false;
    }
    if (p.field_set & (1 << ::UF_QUERY)) {
        parsed_url.query.assign(url.begin() + p.field_data[UF_QUERY].off,
                                url.begin() + p.field_data[UF_QUERY].off
                                    + p.field_data[UF_QUERY].len);
        if (parse_query && !parse_query_string(parsed_url.query, parsed_url.query_params))
            return false;
    }
    if (p.field_set & (1 << ::UF_FRAGMENT)) {
        parsed_url.fragment.assign(url.begin() + p.field_data[UF_FRAGMENT].off,
                                   url.begin() + p.field_data[UF_FRAGMENT].off
                                       + p.field_data[UF_FRAGMENT].len);
    }
    if (p.field_set & (1 << ::UF_USERINFO)) {
        parsed_url.userinfo.assign(url.begin() + p.field_data[UF_USERINFO].off,
                                   url.begin() + p.field_data[UF_USERINFO].off
                                       + p.field_data[UF_USERINFO].len);
    }
    return true;
}
Ejemplo n.º 4
0
GHashTable *http_parse_query (http_request *h, gchar *post) {
    gchar *q = NULL;

    g_assert( h != NULL );

    if (h->uri != NULL) {
	if(CONFd("Verbosity") >= 9) g_message( "http_parse_query: URI: %s", url_decode(h->uri) );
	q = strchr( h->uri, '?' );
    }

    if (post != NULL) {
	h->query = parse_query_string( post );
    } else if (q != NULL) {
	h->query = parse_query_string( q + 1 );
    } else {
	h->query = NULL;
    }

    if (q != NULL)
	*q = '\0'; /* remove the query string from the URI */

    return h->query;
}
Ejemplo n.º 5
0
void test_query_string() {
  void* ctx;
  parse_query_string(&ctx, "width=640&height=360&video=bigbunny.ogg");
  const char* width = get_parameter(ctx, "width");
  const char* height = get_parameter(ctx, "height");
  const char* video = get_parameter(ctx, "video");
  if(!strcmp(width,"640")) {
      printf("Querystring width esperado:%s - recebido:%s\n", "640", width);
  }
  if(!strcmp(height,"360")) {
      printf("Querystring height esperado:%s - recebido:%s\n", "360", height);
  }
  if(!strcmp(video,"bigbunny.ogg")) {
      printf("Querystring video esperado:%s - recebido:%s\n", "bigbunny.ogg", video);
  }
  release_context(ctx);
}
Ejemplo n.º 6
0
void Request::parse_header(std::string line) {
  if (line.find("GET") == 0) {
    method = Method::GET;
  } else
  if (line.find("HEAD") == 0) {
    method = Method::HEAD;
  } else
  if (line.find("POST") == 0) {
    method = Method::POST;
  } else
  if (line.find("PUT") == 0) {
    method = Method::PUT;
  } else
  if (line.find("PATCH") == 0) {
    method = Method::PATCH;
  } else
  if (line.find("DELETE") == 0) {
    method = Method::DELETE;
  } else
  if (line.find("TRACE") == 0) {
    method = Method::TRACE;
  } else
  if (line.find("CONNECT") == 0) {
    method = Method::CONNECT;
  } else
  if (line.find("OPTIONS") == 0) {
    method = Method::OPTIONS;
  }

  size_t path_start = line.find_first_of(" ")+1;
  size_t path_end = line.rfind("HTTP/1.")-1;

  path = line.substr(path_start, path_end - path_start);

  size_t path_query = path.find("?");

  if (path_query != std::string::npos) {
    std::string query = path.substr(path_query+1, path.size() - path_query);

    parse_query_string(query);

    path.erase(path_query, query.size()+1);
  }
}
Ejemplo n.º 7
0
/* This function parses the data from the client to make sure we got something we can 
   recognize. If we find points, we will populate them in p1 and p2.
*/
enum INPUT parse_input(char* buffer,point* p1,point* p2){
  /*printf("SERVER: parsing the data from the client\n");*/
  if (is_match("quit",buffer)){
    /*printf("SERVER: found the quit command, the server will be shutting down momentarily\n");*/
    return INPUT_QUIT;
  }else{ /* If we didn't find the quit command, let's assume we were given an enviornment variable
	    that holds the query string and try to parse it to obtain our two points */
    /*printf("SERVER: found points (%d,%d) and (%d,%d)\n",p1->x,p1->y,p2->x,p2->y);*/   
    char* queryenv = getenv(buffer); // STONESOUP:INTERACTION_POINT // STONESOUP:SOURCE_TAINT:ENVIRONMENT_VARIABLE
    
    if ( queryenv == NULL ){/* The environment variable could not be found return error */
      return INPUT_ERROR;
    }
    
    /* The query string should follow the format "x1=n1&y1=n2&x2=n3&y2=n4" where n1, n2, n3, and n4 are any integer value.*/
    assoc_t query = parse_query_string(queryenv);
    if(!query){ /* Failed ot parse the query string return error */
      return INPUT_ERROR;
    }else{
      assoc_t q = query;
      for(;q->key;q++){
	if(is_match("x1",q->key)){
	  p1->x = atoi(q->val);
	}else if(is_match("y1",q->key)){
	  p1->y = atoi(q->val);
	}else if(is_match("x2",q->key)){
	  p2->x = atoi(q->val);
	}else if(is_match("y2",q->key)){
	  p2->y = atoi(q->val);
	}
      }
      free(query);
      query = NULL;
    }
    return INPUT_POINTS;
  }
}
Ejemplo n.º 8
0
http_status http_server::http_request_state::parse_body()
// Read the body section from the socket and fills m_req.m_body.
//
// Sets m_request_state to PARSE_DONE.
//
// Returns an error code >= 400 on error; < 400 on success.
{
	assert(m_req.m_body.length() == 0);

	// Get the body data and stash it in m_req.m_body.
	switch (m_request_state)
	{
	default:
		assert(0);
		break;

	case PARSE_BODY_IDENTITY:
		m_request_state = PARSE_DONE;

		// We assume we can get the whole body within 100 ms.
		m_req.m_body.resize(m_content_length);
		int bytes_read = m_req.m_sock->read(&(m_req.m_body[0]), m_content_length, 0.100f);
		if (bytes_read < m_content_length)
		{
			return HTTP_BAD_REQUEST;
		}
		break;

#if 0
	case PARSE_BODY_CHUNKED_CHUNK:
		read a line;
		get chunk size;
		while (chunk_size > 0)
		{
			read chunk data and CRLF;
			m_body += chunk data;
			read a line;
			get chunk size;
		}

		read entity_header;
		while (entity_header.length() > 0)
		{
			parse entity_header;
			read entity_header;
		}

		m_request_state = PARSE_DONE;

		break;
#endif // 0
	}

	// Parse the body data if necessary.
	tu_string type_str;
	if (m_req.m_method == "POST" && m_req.m_header.get("content-type", &type_str)) {
		if (type_str == "application/x-www-form-urlencoded") {
			// Parse "Content-type: application/x-www-form-urlencoded" in the body
			//
			// Basically this is a long string that looks like:
			//
			//  key1=value1&key2=value2&key3=value3 [...]
			//
			// I.e. just like in the URL.
			//
			// http://www.w3.org/TR/REC-html40/interact/forms.html says
			// it's "the default content type".  Quote from that doc:
			//
			//    1. Control names and values are escaped. Space
			//    characters are replaced by `+', and then reserved
			//    characters are escaped as described in [RFC1738],
			//    section 2.2: Non-alphanumeric characters are replaced by
			//    `%HH', a percent sign and two hexadecimal digits
			//    representing the ASCII code of the character. Line
			//    breaks are represented as "CR LF" pairs (i.e.,
			//    `%0D%0A').
			//
			//    2. The control names/values are listed in the order they
			//    appear in the document. The name is separated from the
			//    value by `=' and name/value pairs are separated from
			//    each other by `&'.
			parse_query_string(m_req.m_body.c_str());
			
		} else if (type_str == "multipart/form-data") {
			// Parse "Content-type: multipart/form-data" in the body
			// (i.e. file uploads, non-ASCII fields, ... -- what else?)
			//   etc...
			//   // each part has a header like: Content-disposition: form-data; name="something"
			//   // each part optionally has a Content-type: header.  The default is "text/plain".
			//   // each part may have a Content-transfer-encoding:, if it differs from the body
			//
			//   // http://www.faqs.org/rfcs/rfc2388.html covers multipart/form-data for HTTP 1.1
			//   // http://www.faqs.org/rfcs/rfc2046.html covers MIME multipart encoding generically
			return HTTP_UNSUPPORTED_MEDIA_TYPE;
		} else {
			return HTTP_UNSUPPORTED_MEDIA_TYPE;
		}
	}

	return HTTP_OK;
}
Ejemplo n.º 9
0
http_status http_server::http_request_state::process_header()
// Call this after finishing parsing the header.  Sets the following
// parse state.  Returns an HTTP status code.
{
	assert(m_request_state == PARSE_HEADER);
	assert(m_req.m_body.length() == 0);

	// Set up path/file vars.
	const char* pathend = strchr(m_req.m_uri.c_str(), '?');
	const char* query = NULL;
	if (pathend) {
		query = pathend + 1;
	} else {
		pathend = m_req.m_uri.c_str() + m_req.m_uri.length();
	}
	m_req.m_path = tu_string(m_req.m_uri.c_str(), pathend - m_req.m_uri.c_str());
	unescape_url_component(&m_req.m_path);
	
	const char* filestart = strrchr(m_req.m_path.c_str(), '/');
	if (filestart)
	{
		m_req.m_file = (filestart + 1);
		unescape_url_component(&m_req.m_file);
	}

	// Parse params in the request string.
	parse_query_string(query);

	m_content_length = -1;
	tu_string content_length_str;
	if (m_req.m_header.get("content-length", &content_length_str))
	{
		m_content_length = atol(content_length_str.c_str());
		if (m_content_length > MAX_CONTENT_LENGTH_ACCEPTED)
		{
			m_request_state = PARSE_DONE;
			return HTTP_REQUEST_ENTITY_TOO_LARGE;
		}
	}
	
	tu_string transfer_encoding;
	if (m_req.m_header.get("transfer-encoding", &transfer_encoding))
	{
		if (transfer_encoding.to_tu_stringi() == "chunked")
		{
			// We're required to ignore the content-length
			// header.
			m_content_length = -1;
			m_request_state = PARSE_BODY_CHUNKED_CHUNK;
			return parse_body();
		}
		else if (transfer_encoding.to_tu_stringi() == "identity")
		{
			// This is OK; basically a no-op.
		}
		else
		{
			// A transfer encoding we don't know how to handle.
			// Reject it.
			m_request_state = PARSE_DONE;
			return HTTP_NOT_IMPLEMENTED;
		}
	}

	// If there's a body section, then we need to read it & parse it.
	if (m_content_length >= 0)
	{
		m_request_state = PARSE_BODY_IDENTITY;
		return parse_body();
	}
	else
	{
		m_request_state = PARSE_DONE;
	}
	
	return HTTP_OK;
}
static int videothumb_handler(request_rec *r) 
{
  char fullVideoPath[MAX_PATH_LENGTH];

  if (!r) return DECLINED;
  module_config* conf = ap_get_module_config(r->server->module_config, &videothumb_module);

  if (!conf->enabled) 
  {
    return DECLINED;
  }
  if (!(conf->app_path && (strstr(r->parsed_uri.path, conf->app_path) == r->parsed_uri.path)))
  {
    return DECLINED;
  }

  if (r->args)
  {
    void* ctx;
    parse_query_string(&ctx, r->args, r->pool);
    strncpy(fullVideoPath, conf->medias_path, MAX_PATH_LENGTH);
    if (!r->path_info) {
       LOG_ERROR("Could not find 'filename' on the URI");
       return DECLINED;
    }
    strncat(fullVideoPath, r->path_info + 1, MAX_PATH_LENGTH);

    const char* temp = get_parameter(ctx, "split");
    RequestInfo requestInfo;
    requestInfo.split = atoi(temp ? temp : ONE_VALUE);
    temp = get_parameter(ctx, "columns");
    requestInfo.columns = atoi(temp ? temp : ONE_VALUE);
    requestInfo.file = fullVideoPath;
    requestInfo.jpegQuality = conf->quality;
  
    temp = get_parameter(ctx,"width");
    if(temp == NULL) requestInfo.width = 0;
    else requestInfo.width = atoi(temp);
  
    temp = get_parameter(ctx,"height");
    if(temp == NULL) requestInfo.height = 0;
    else requestInfo.height = atoi(temp);

    temp = get_parameter(ctx,"pageSize");
    requestInfo.pageSize = temp ? atoi(temp) : requestInfo.split;

    temp = get_parameter(ctx,"currentPage");
    requestInfo.currentPage = atoi(temp ? temp : ONE_VALUE);

    init_libraries();
    temp = get_parameter(ctx, "second");

    ImageBuffer jpeg;
    if(temp == NULL) {
      jpeg = get_storyboard(requestInfo, r->pool);
    } else {
      requestInfo.second = atoi(temp ? temp : ONE_VALUE);
      jpeg = get_thumbnail(requestInfo, r->pool);
    }
  
    if (jpeg.buffer) {
      ap_set_content_type(r, "image/jpeg");
      ap_rwrite(jpeg.buffer, jpeg.size, r);
      free(jpeg.buffer);
    } else {
      LOG_ERROR("Cannot render thumbnail for this video");
      return DECLINED;
    }
  } else {
    LOG_ERROR("Querystring null");
    return DECLINED;
  }
  return OK;
}
Ejemplo n.º 11
0
int main(void) {

  char *request_method = NULL;
  char *size_of_query_string = NULL;
  char *query_string = NULL;
  char *decoded_query_string = NULL;
  blocking_struct_t *bs = NULL;
  query_str_t *qs = NULL;
  char filepath[MAX_PATH_LENGTH];
  struct stat64 file_stats;
  struct stat fdtfile_stats;
  char *fdt_buf = NULL;
  unsigned int fdt_length;
  unsigned fdt_nbytes;
  FILE *fdt_fp;
  fdt_t *fdt = NULL;
  file_t *file = NULL;

  int fec_ratio = 0;
  
  char *buf = NULL;
  unsigned long long nbytes;
  unsigned long long pos;
  int fp;

  trans_block_t *tr_block = NULL;
  trans_unit_t *tr_unit = NULL;

  qs_missing_block_t *ms_block = NULL;
  qs_missing_symbol_t *ms_symbol = NULL;

  int i;
  char *uri_path = NULL;

  char *repair_conf_file = NULL;
  repair_arguments_t ra;
  int retval;
  FILE *ptm_repair_file;

  unsigned int sbn = 0;

  repair_conf_file = getenv("RepairConfFile");

  if(repair_conf_file == NULL) {
    return -1;
  }

  if(repair_conf_file[strlen(repair_conf_file)-1] == '\r') {
    repair_conf_file[strlen(repair_conf_file)-1] = '\0';
  }
  
  retval = parse_repair_conf_file(repair_conf_file, &ra);
    
  if(retval == -1) {
    return -1;
  }

  retval = parse_flute_conf_file(&ra);
    
  if(retval == -1) {
    return -1;
  }

  if(stat(ra.fdt_file, &fdtfile_stats) == -1) {
    return -1;
  }

  fdt_length = fdtfile_stats.st_size;

  /* Allocate memory for buf, to read fdt file to it */
  if(!(fdt_buf = (char*)calloc((fdt_length + 1), sizeof(char)))) {
    return -1;
  }

  if((fdt_fp = fopen(ra.fdt_file, "rb")) == NULL) {
    free(fdt_buf);
    return -1;
  }

  fdt_nbytes = fread(fdt_buf, 1, fdt_length, fdt_fp);

  if(fdt_nbytes <= 0) {
    fclose(fdt_fp);
    free(fdt_buf);
    return -1;
  }

  fdt = decode_fdt_payload(fdt_buf);
  free(fdt_buf);
  fclose(fdt_fp);

  request_method = getenv("REQUEST_METHOD");

  if(strcmp(request_method, "GET") == 0) {
    query_string = getenv("QUERY_STRING");

    if(query_string == NULL) {
      FreeFDT(fdt);
      return -1;
    }
  }
  else {
      size_of_query_string = getenv("CONTENT_LENGTH");

      if(!(query_string = (char*)calloc((atoi(size_of_query_string) + 1), sizeof(char)))) {
	FreeFDT(fdt);
	return -1;
      }

      read(0, query_string, atoi(size_of_query_string)); /* 0 is stdin */
  }

  decoded_query_string = decode_query_string(query_string);
  
  if(decoded_query_string == NULL) {

    if(strcmp(request_method, "POST") == 0) {
      free(query_string);
    }
    FreeFDT(fdt);
    return -1;
  }

  /* parse query string */
  qs = parse_query_string(decoded_query_string);
  
  if(qs == NULL) {
    free(decoded_query_string);

    if(strcmp(request_method, "POST") == 0) {
      free(query_string);
    }

    FreeFDT(fdt);
    return -1;
  }

  /* Find file struct */

  file = fdt->file_list;

  while(file != NULL) {
    uri_path = get_uri_host_and_path(qs->fileURI);

    if(strstr(file->location, uri_path) != NULL) {
      break;
    }

    file = file->next;
  }

  if(file == NULL) {

    free(decoded_query_string);

    if(strcmp(request_method, "POST") == 0) {
      free(query_string);
    }

    FreeFDT(fdt);
    free_query_str(qs);
    return -1;
  }

  if(strcmp(ra.repair_method, "PTM") == 0){

    if((ptm_repair_file = fopen(ra.requested_blocks_file, "a")) == NULL) {
      free(decoded_query_string);

      if(strcmp(request_method, "POST") == 0) {
	free(query_string);
      }

      free_query_str(qs);
      FreeFDT(fdt);
      return -1;
    }

    ms_block = qs->block_list;

    if(ms_block == NULL) {
      fprintf(ptm_repair_file, "%llu:*\n", file->toi);
    }
    else {
      while(ms_block != NULL) {
	fprintf(ptm_repair_file, "%llu:%i\n", file->toi, ms_block->sbn);
	ms_block = ms_block->next;
      }
    }
    
    free(decoded_query_string);

    if(strcmp(request_method, "POST") == 0) {
      free(query_string);
    }

    free_query_str(qs);
    FreeFDT(fdt);
    fclose(ptm_repair_file);
    
    printf("%s%c%c", "Location:", 13, 10);
    printf("%c%c", 13, 10);
  }
  else {
    memset(filepath, 0, MAX_PATH_LENGTH);
    
    if(ra.base_dir != NULL) {
      if(!(strcmp(ra.base_dir, "") == 0)) {
	strcpy(filepath, ra.base_dir);
	strcat(filepath, "/");
      }
    } 
    strcat(filepath, get_uri_host_and_path(qs->fileURI));

    if(file->encoding != NULL) {
#ifdef USE_ZLIB
      if(strcmp(file->encoding, "gzip") == 0) {
	strcat(filepath, GZ_SUFFIX);
      }
#endif
    }

    /* use stat to get file size */
    
    if(stat64(filepath, &file_stats) == -1) {
      free(decoded_query_string);

      if(strcmp(request_method, "POST") == 0) {
	free(query_string);
      }

      free_query_str(qs);
      FreeFDT(fdt);
      return -1;

    }
    
    if(file_stats.st_size == 0) {
      free(decoded_query_string);

      if(strcmp(request_method, "POST") == 0) {
	free(query_string);
      }

      free_query_str(qs);
      FreeFDT(fdt);
      return -1;
    }
    
    /* calculate blocking structure */

    bs = compute_blocking_structure((unsigned long long)file_stats.st_size, file->max_sb_len, file->es_len);
       
    /* Allocate memory for buf */
    if(!(buf = (char*)calloc((unsigned int)(file->es_len * file->max_sb_len), sizeof(char)))) {
      free(decoded_query_string);

      if(strcmp(request_method, "POST") == 0) {
	free(query_string);
      }

      free_query_str(qs);
      free(bs);
      FreeFDT(fdt);
      return -1;
    }
    
    /* File to repair */
    if((fp = open64(filepath, 0, 0)) < 0) {
      free(decoded_query_string);

      if(strcmp(request_method, "POST") == 0) {
	free(query_string);
      }

      free_query_str(qs);
      free(bs);
      free(buf);
      FreeFDT(fdt);
      return -1;
    }
        
    /* http response message */    
    /* http response message headers*/

    printf("%s%c%c", "Content-Type: application/simpleSymbolContainer", 13, 10);
    printf("%s%c%c", "Content-Transfer-Encoding: binary", 13, 10);
    printf("%c%c", 13, 10);
    
    ms_block = qs->block_list;

    if(ms_block == NULL) {
     
      while(sbn < bs->N) {
	
	if(sbn < bs->I) {
          nbytes = file->es_len * (bs->A_large);
        }
        else {
          nbytes = file->es_len * (bs->A_small);
        }
	
	memset(buf, 0, (file->es_len * file->max_sb_len));
        nbytes = read(fp, buf, (unsigned int)nbytes);
	
	if(nbytes < 0) {
	  free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

          free_query_str(qs);
          free(buf);
          free(bs);
          close(fp);
          FreeFDT(fdt);
	  return -1;
	}
	
	/* all could use null_fec_encode_src_block() functions, because FEC symbols are not transmitted */
	
        if(file->fec_enc_id == COM_NO_C_FEC_ENC_ID) {
          tr_block = null_fec_encode_src_block(buf, nbytes, sbn, file->es_len);
        }
        else if(file->fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
          tr_block = xor_fec_encode_src_block(buf, nbytes, sbn, file->es_len);
        }
        else if(((file->fec_enc_id == SB_SYS_FEC_ENC_ID) && (file->fec_inst_id == REED_SOL_FEC_INST_ID))) {
          tr_block = rs_fec_encode_src_block(buf, nbytes, sbn, file->es_len, fec_ratio, file->max_sb_len);
        }
        else {
          free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

          free_query_str(qs);
          free(buf);
          free(bs);
          close(fp);
          FreeFDT(fdt);
          return -1;
        }
	
	if(tr_block == NULL) {
          free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

          free_query_str(qs);
          free(buf);
          free(bs);
          close(fp);
          FreeFDT(fdt);
          return -1;
        }
	
	tr_unit = tr_block->unit_list;
	
	add_length_indicator(tr_block->k);

	if(file->fec_enc_id == COM_NO_C_FEC_ENC_ID) {
	  add_fec_plid_0_130((unsigned short)tr_block->sbn, (unsigned short)tr_unit->esi);
	}
	else if(file->fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
	  add_fec_plid_128(tr_block->sbn, tr_unit->esi);
	}
	else if(((file->fec_enc_id == SB_SYS_FEC_ENC_ID) && (file->fec_inst_id == REED_SOL_FEC_INST_ID))) {
	  add_fec_plid_129(tr_block->sbn, (unsigned int)tr_block->k, (unsigned int)tr_unit->esi);
	}
	
	while(1) {
	  
	  for(i = 0; i < tr_unit->len; i++) {
	    printf("%c", tr_unit->data[i]);
	  }
	  
	  if(tr_unit->esi == (tr_block->k - 1)) { /* no FEC symbols */
	    break;
	  }
	  
	  tr_unit++;
	}

	tr_unit = tr_block->unit_list;

        while(1) {
          free(tr_unit->data);

          if(tr_unit->esi == (tr_block->n - 1)) {
            break;
          }

          tr_unit++;
        }

        free(tr_block->unit_list);
        free(tr_block);

        sbn++;
      }
    }
    else {
    
      while(ms_block != NULL) {
	
	/* Set place where to read */
	
	if(ms_block->sbn < bs->I) {
	  pos = (unsigned long long)ms_block->sbn * (unsigned long long)bs->A_large * (unsigned long long)file->es_len;
	}
	else {
	  pos = ( ( ( (unsigned long long)bs->I * (unsigned long long)bs->A_large ) + 
		    ( (unsigned long long)ms_block->sbn - (unsigned long long)bs->I ) * (unsigned long long)bs->A_small ) * (unsigned long long)file->es_len );
	}

	/* set correct position */
	
	if(lseek64(fp, pos, SEEK_SET) == -1) {
	  free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

	  free_query_str(qs);
	  free(buf);
	  free(bs);
	  close(fp);
	  FreeFDT(fdt);
	  return -1;
	}
	
	if(ms_block->sbn < bs->I) {
	  nbytes = file->es_len * (bs->A_large);
	}
	else {
	  nbytes = file->es_len * (bs->A_small);
	}
	
	memset(buf, 0, (file->es_len * file->max_sb_len));
	nbytes = read(fp, buf, (unsigned int)nbytes);
	
	/* all could use null_fec_encode_src_block() functions, because FEC symbols are not transmitted */
	
	if(file->fec_enc_id == COM_NO_C_FEC_ENC_ID) {
	  tr_block = null_fec_encode_src_block(buf, nbytes, ms_block->sbn, file->es_len);
	}
	else if(file->fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
	  tr_block = xor_fec_encode_src_block(buf, nbytes, ms_block->sbn, file->es_len);
	}
	else if(((file->fec_enc_id == SB_SYS_FEC_ENC_ID) && (file->fec_inst_id == REED_SOL_FEC_INST_ID))) {
	  tr_block = rs_fec_encode_src_block(buf, nbytes, ms_block->sbn, file->es_len, fec_ratio, file->max_sb_len);
	}
	else {
	  free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

	  free_query_str(qs);
	  free(buf);
	  free(bs);
	  close(fp);
	  FreeFDT(fdt);
	  return -1; 
	}
	
	if(tr_block == NULL) {
	  free(decoded_query_string);

	  if(strcmp(request_method, "POST") == 0) {
	    free(query_string);
	  }

	  free_query_str(qs);
	  free(buf);
	  free(bs);
	  close(fp);
	  FreeFDT(fdt);
	  return -1;
	}
	
	ms_symbol = ms_block->es_list;
	
	if(ms_symbol == NULL) {
	  tr_unit = tr_block->unit_list;
	  
	  add_length_indicator(tr_block->k);
	  
	  if(file->fec_enc_id == COM_NO_C_FEC_ENC_ID) {
	    add_fec_plid_0_130((unsigned short)ms_block->sbn, (unsigned short)tr_unit->esi);
	  }
	  else if(file->fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
	    add_fec_plid_128(ms_block->sbn, tr_unit->esi);
	  }
	  else if(((file->fec_enc_id == SB_SYS_FEC_ENC_ID) && (file->fec_inst_id == REED_SOL_FEC_INST_ID))) {
	    add_fec_plid_129(ms_block->sbn, (unsigned int)tr_block->k, (unsigned int)tr_unit->esi);
	  }
	  
	  while(1) {
	    
	    for(i = 0; i < tr_unit->len; i++) {
	      printf("%c", tr_unit->data[i]);
	    }
	    
	    if(tr_unit->esi == (tr_block->k - 1)) { /* no FEC symbols */
	      break;
	    }
	    
	    tr_unit++;
	  }
	}
	else {
	  
	  while(ms_symbol != NULL) {
	    
	    tr_unit = tr_block->unit_list;
	    
	    while(1) {
	      if(tr_unit->esi == ms_symbol->esi) {
		add_length_indicator(1);
		
		if(file->fec_enc_id == COM_NO_C_FEC_ENC_ID) {
		  add_fec_plid_0_130((unsigned short)ms_block->sbn, (unsigned short)ms_symbol->esi);
		}
		else if(file->fec_enc_id == SIMPLE_XOR_FEC_ENC_ID) {
		  add_fec_plid_128(ms_block->sbn, ms_symbol->esi);
		}
		else if(((file->fec_enc_id == SB_SYS_FEC_ENC_ID) && (file->fec_inst_id == REED_SOL_FEC_INST_ID))) {
		  add_fec_plid_129(ms_block->sbn, (unsigned short)tr_block->k,
				   (unsigned short)ms_symbol->esi);
		}
		
		for(i = 0; i < tr_unit->len; i++) {
		  printf("%c", tr_unit->data[i]);
		}
		
		break;
	      }
	      
	      if(tr_unit->esi == (tr_block->k - 1)) { /* no FEC symbols */
		break;
	      }
	      
	      tr_unit++;
	    }
	    ms_symbol = ms_symbol->next;
	  }
	}
	
	tr_unit = tr_block->unit_list;
	
	while(1) {
	  free(tr_unit->data);
	  
	  if(tr_unit->esi == (tr_block->n - 1)) {
	    break;
	  }
	  
	  tr_unit++;
	} 
	
	free(tr_block->unit_list);
	free(tr_block);
	
	ms_block = ms_block->next;
      }
    }

    free(decoded_query_string);

    if(strcmp(request_method, "POST") == 0) {
      free(query_string);
    }

    free_query_str(qs);
    free(bs);
    free(buf);
    close(fp);        
    FreeFDT(fdt);
  }

  return 0;
}
Ejemplo n.º 12
0
http::request* http::request::parse (std::string str)
{
	request* req = new request();
	req->raw_message = str;
	
	std::stringstream ss(str);
	std::string line;
	
	/**
	 * parsing the request line, e.g. "GET /index.html?name=hey HTTP/1.1"
	 */
	utils::ioutils::getline(ss, line);
	std::stringstream lineStream(line);
	std::getline (lineStream, req->request_method, ' ');
	std::getline (lineStream, req->request_uri, ' ');
	
	req->file_name = req->request_uri;
	
	unsigned pos;
	if (req->request_uri.length() > 1 && (pos = req->request_uri.find('?')) != std::string::npos && pos <= req->request_uri.length())
	{
		// name=hey
		req->request_query_string = req->request_uri.substr (pos + 1);
		// index.html
		req->file_name = req->request_uri.substr(0, pos);
		req->query_string_map = parse_query_string (req->request_query_string);
	}
	
	utils::ioutils::getline (lineStream, req->server_protocol);
	
	/**
	 * parsing additional request headers. Ends when no more lines can be fetched (i.e. an "\r\n" line).
	 */
	while (utils::ioutils::getline(ss, line) && line.size() > 0)
	{
		std::stringstream headerStream(line);
		std::string key, value;
		std::getline (headerStream, key, ':');
		std::getline (headerStream, value);
		
		if ( value[0] == ' ')
			value.erase (0, 1);
		
		req->header(key, value);
	}
	
	/**
	 * the next line should give us the query string, if method equals POST
	 */
	utils::ioutils::getline(ss, line);
	if (req->method() == "POST" && line.length() > 0)
	{
		req->request_query_string = line;
		req->query_string_map = parse_query_string (line);
	}
	
	std::string host = req->header("Host");
	
	if (host == "")
		return NULL;
	
	req->request_url = std::string("http://");
	req->request_url.append (host);
	
	return req;
}
Ejemplo n.º 13
0
int
main(void)
{
	struct req	 req;
	struct itimerval itimer;
	const char	*path;
	const char	*querystring;
	int		 i;

	/* Poor man's ReDoS mitigation. */

	itimer.it_value.tv_sec = 2;
	itimer.it_value.tv_usec = 0;
	itimer.it_interval.tv_sec = 2;
	itimer.it_interval.tv_usec = 0;
	if (setitimer(ITIMER_VIRTUAL, &itimer, NULL) == -1) {
		warn("setitimer");
		pg_error_internal();
		return EXIT_FAILURE;
	}

	/*
	 * First we change directory into the MAN_DIR so that
	 * subsequent scanning for manpath directories is rooted
	 * relative to the same position.
	 */

	if (chdir(MAN_DIR) == -1) {
		warn("MAN_DIR: %s", MAN_DIR);
		pg_error_internal();
		return EXIT_FAILURE;
	}

	memset(&req, 0, sizeof(struct req));
	req.q.equal = 1;
	parse_manpath_conf(&req);

	/* Parse the path info and the query string. */

	if ((path = getenv("PATH_INFO")) == NULL)
		path = "";
	else if (*path == '/')
		path++;

	if (*path != '\0') {
		parse_path_info(&req, path);
		if (req.q.manpath == NULL || access(path, F_OK) == -1)
			path = "";
	} else if ((querystring = getenv("QUERY_STRING")) != NULL)
		parse_query_string(&req, querystring);

	/* Validate parsed data and add defaults. */

	if (req.q.manpath == NULL)
		req.q.manpath = mandoc_strdup(req.p[0]);
	else if ( ! validate_manpath(&req, req.q.manpath)) {
		pg_error_badrequest(
		    "You specified an invalid manpath.");
		return EXIT_FAILURE;
	}

	if ( ! (NULL == req.q.arch || validate_urifrag(req.q.arch))) {
		pg_error_badrequest(
		    "You specified an invalid architecture.");
		return EXIT_FAILURE;
	}

	/* Dispatch to the three different pages. */

	if ('\0' != *path)
		pg_show(&req, path);
	else if (NULL != req.q.query)
		pg_search(&req);
	else
		pg_index(&req);

	free(req.q.manpath);
	free(req.q.arch);
	free(req.q.sec);
	free(req.q.query);
	for (i = 0; i < (int)req.psz; i++)
		free(req.p[i]);
	free(req.p);
	return EXIT_SUCCESS;
}
Ejemplo n.º 14
0
Request::Request(int client, struct sockaddr_storage client_addr) : handle(client), addr(client_addr) {
  std::string line;
  bool is_header = true;
  char buffer[BUFFER_SIZE];

  // receive data from client
  recv(client, buffer, BUFFER_SIZE, 0);

  // parse each line
  std::istringstream request_stream(buffer);
  while (std::getline(request_stream, line)) {
    // if method is undefined, assumie its first line
    if (method == Method::UNDEFINED) {
      // so parse header
      parse_header(line);
      continue;
    }

    // next lines are headers, strip them
    line.erase(line.find_last_not_of(" \n\r\t")+1);

    // if line is empty, then content should follow
    if (line.size() == 0) {
      is_header = false;
      break;
    }

    // extract name and value from header
    size_t colon;
    std::string name = line.substr(0, colon = line.find(":"));
    std::string value = line.substr(colon+1);
    value.erase(0, value.find_first_not_of(" \n\r\t"));

    headers.insert(std::make_pair(name, value));
  }

  // if has content
  if (!is_header) {
    // assume proper content length
    size_t content_length = header("Content-Length", 0);

    if (content_length == 0)
      content_length = header("Content-length", 0);

    raw.reserve(content_length);
    content.reserve(content_length);
    
    if (content_length > 0) {
      // read whats left in header
      length = std::min(content_length, (size_t)(BUFFER_SIZE - request_stream.tellg()));
      raw = std::string(buffer, BUFFER_SIZE).substr(request_stream.tellg(), length);
      content = "";

      // receive some more
      while (length < content_length) {
        memset(buffer, 0, BUFFER_SIZE);
        size_t buffer_length = recv(client, buffer, BUFFER_SIZE, 0);
        raw += std::string(buffer, buffer_length);
        content += std::string(buffer, buffer_length);
        length += buffer_length;
      }
    }
    //std::cout << "content o "<<content_length<<" == "<<length<<" == " <<raw.size()<<"\n";
  }

  // delete [] buffer;

  time = std::chrono::high_resolution_clock::now();

  // if has some content
  if (!raw.empty()) {
    // try to parse it
    auto ct = headers.find("Content-Type");

    if (ct == headers.end())
      ct = headers.find("Content-type");

    if (ct != headers.end()) {
      if (ct->second == "application/x-www-form-urlencoded") {
        parse_query_string(raw);
      } else
      if (ct->second == "application/json" || ct->second == "text/json") {
        Json::Reader json_reader;
        // data = std::make_shared<Json::Value>();
        json_reader.parse(raw, data, false);
      }
    }
  }
}
Ejemplo n.º 15
0
int oversight_main(int argc,char **argv,int send_content_type_header)
{
    int result=0;
    int done=0;

    g_start_clock = time(NULL);
    assert(sizeof(long long) >= 8);

    init_view();
    adjust_path();

    char *q=getenv("QUERY_STRING");
    char *sp=getenv("SCRIPT_NAME");

    char *p;
    char *req;
    if (q && (p = delimited_substring(q,"&",REMOTE_VOD_PREFIX2,"=",1,0)) != NULL) {

        gaya_auto_load(p+strlen(REMOTE_VOD_PREFIX2)+1);
        done=1;

    } else if (q && strstr(q,YAMJ_PREFIX2)) {

        g_query=parse_query_string(q,g_query);
        //req = url_decode(q+strlen(YAMJ_PREFIX2));
        req = url_decode(query_val("yamj"));
        yamj_xml(req);
        FREE(req);
        done=1;
    } else if (sp && (req=strstr(sp,YAMJ_PREFIX)) != NULL) {
        // If oversight script is launched as /oversight/yamj/xxxxx.xml
        // then use xxxxxx.xml as a yamj xml request.
        // This is to allow for Apache ModAlias to serve static images whilst calling oversight for CGI
        // The rewrite rules should be 
        //    ScriptAliasMatch ^/oversight/yamj/(.*).xml  /share/Apps/oversight/oversight.cgi
        //    AliasMatch ^/oversight/yamj/banner_(.*jpg) /oversight/db/global/_b/ovs_$1
        //    AliasMatch ^/oversight/yamj/fanart_(.*jpg) /oversight/db/global/_fa/ovs_$1
        //    AliasMatch ^/oversight/yamj/poster_(.*jpg) /oversight/db/global/_J/ovs_$1
        //    AliasMatch ^/oversight/yamj/thumb_(.*).jpg  /oversight/db/global/_J/ovs_$1.thumb.jpg
        //    AliasMatch ^/oversight/yamj/boxset_(.*).jpg  /oversight/db/global/_J/ovs_$1.thumb.boxset.jpg`
        //
        req += strlen(YAMJ_PREFIX);
        yamj_xml(req);
        done=1;

    } else if (q == NULL || strchr(q,'=') == NULL ) {

        if (argc > 1 ) {

            if ( argv[1] && *argv[1] && argv[2] == NULL && util_starts_with(argv[1],YAMJ_PREFIX) ) {
                char *req = url_decode(argv[1]+strlen(YAMJ_PREFIX));
                yamj_xml(req);
                FREE(req);
                done=1;

            } else if ( argv[1] && *argv[1] && argv[2] == NULL && strchr(argv[1],'=') == NULL) {
                // Single argument passed.
                //
                char *path = url_decode(argv[1]);
                char *dot = strrchr(path,'.');
                if (dot < path) dot = strchr(path,'\0');
                int result = 0;

                fprintf(stderr,"path=[%s]",path);

                // should really use file command or magic number to determine file type

                if (dot && STRCMP(dot,".png") == 0 ) {

                    result = cat(CONTENT_TYPE"image/png",path);

                } else if (dot &&  STRCMP(dot,".jpg") == 0 ) {

                    result = cat(CONTENT_TYPE"image/jpeg",path);

                } else if (dot &&  STRCMP(dot,".gif") == 0) {

                    result = cat(CONTENT_TYPE"image/gif",path);

                } else if (dot &&  (STRCMP(dot,".swf") == 0 || STRCMP(dot,".phf" ) == 0) ) {

                    result = cat(CONTENT_TYPE"application/x-shockwave-flash",path);

                } else if (browsing_from_lan() ) {

                    if (is_dir(path)) {

                        // load_configs(); // load configs so we can use file_to_url() functions 
                        result = ls(path);
                    } else {
                        int exists = is_file(path);

                        char *all_headers = NULL;
                        char *content_headers = NULL;

                        if (exists) {
                            if (strstr(path,".tar.gz") || strcmp(dot,".tgz") == 0) {

                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"application/x-tar",CONTENT_ENC,"gzip");

                            } else if (strcmp(dot,".gz") == 0 ) {

                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"application/x-gzip",CONTENT_ENC,"identity");

                            } else if (strcmp(dot,".html") == 0 ) {

                                ovs_asprintf(&content_headers,"%s%s",
                                        CONTENT_TYPE,"text/html;charset=utf-8");

                            } else {
                                ovs_asprintf(&content_headers,"%s%s",
                                        CONTENT_TYPE,"text/plain;charset=utf-8");
                            }
                        } else {
                            // .gz.txt is a fake extension added by the ls command to view log.gz inline without browser downloading.
                            if (strstr(path,".gz.txt")) {
                                ovs_asprintf(&content_headers,"%s%s\n%s%s",
                                        CONTENT_TYPE,"text/plain;charset=utf-8", CONTENT_ENC,"gzip");
                                // remove .txt to get real zip file.
                                // .txt is needed so a certain browser displays inline. (might be other ways)
                                *dot = '\0';
                            } else {
                                // 404 error would be here
                            }
                        }
                        ovs_asprintf(&all_headers,"%s\n%s%ld",content_headers,CONTENT_LENGTH,file_size(path));
                        FREE(content_headers);
                        result = cat(all_headers,path);
                        FREE(all_headers);

                    }
                }
                FREE(path);
                fflush(stdout);
                done=1;
            }
        }
    }



    if (!done) {
        if (send_content_type_header) {
            printf("Content-Type: text/html; charset=utf-8\n\n");

            start_page("CGI");
        } else {
            start_page("WGET");
        }

        html_log_level_set(2);

        load_configs();
        //html_hashtable_dump(0,"settings",g_nmt_settings);

        long log_level;
        if (config_check_long(g_oversight_config,"ovs_log_level",&log_level)) {
            html_log_level_set(log_level);
        }

        html_comment("Appdir= [%s]",appDir());

        //array_unittest();
        //util_unittest();
        //config_unittest();

        g_query = string_string_hashtable("g_query2",16);

        html_comment("default query ... ");
        add_default_html_parameters(g_query);
        html_hashtable_dump(0,"prequery",g_query);

        html_comment("read query ... ");
        g_query=parse_query_string(getenv("QUERY_STRING"),g_query);
        html_hashtable_dump(0,"query",g_query);

        html_comment("read post ... ");

        struct hashtable *post=read_post_data(getenv("TEMP_FILE"));
        html_hashtable_dump(0,"post",g_query);
        
        html_comment("merge query and post data");
        merge_hashtables(g_query,post,1); // post is destroyed

        html_hashtable_dump(0,"query final",g_query);


#if 0
        html_comment("utf8len expect 2 = %d",utf8len("a"));
        html_comment("utf8len expect 2 = %d",utf8len("à€€a"));
        html_comment("utf8len expect 2 = %d",utf8len("ü€€€€€a"));
        html_comment("utf8cmp_char 0 = %d",utf8cmp_char("ü€€€€€a","ü€€€€€b"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("ü€€€€€a","ü€€€€€a"));
        html_comment("utf8cmp_char 0 = %d",utf8cmp_char("a","a"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("a","b"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("ü€€€€€a","üa"));
        html_comment("utf8cmp_char !0 = %d",utf8cmp_char("a","ü€€€€€a"));
        Abet *a = abet_create("abcdefghijklmnopqrstuvwxyz");
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        html_comment("inc z %d",abet_letter_inc_or_add(a,"z",1));
        html_comment("inc 4 %d",abet_letter_inc_or_add(a,"4",1));
        html_comment("inc 5 %d",abet_letter_inc_or_add(a,"5",1));
        html_comment("inc 5 %d",abet_letter_inc_or_add(a,"5",1));
        html_comment("inc 6* %d",abet_letter_inc_or_add(a,"6",0));
        html_comment("inc 7* %d",abet_letter_inc_or_add(a,"7",0));
        html_comment("inc a %d",abet_letter_inc_or_add(a,"a",1));
        abet_free(a);
#endif


        config_read_dimensions(1);

        HTML_LOG(0,"Begin Actions");
        do_actions();
       
        ViewMode *view;

        DbSortedRows *sortedRows = NULL;


        while(1) {
            view=get_view_mode(1);  
            HTML_LOG(0,"view mode = [%s]",view->name);

            // If movie view but all ids have been removed , then move up
            if (view == VIEW_MOVIE && !*query_val(QUERY_PARAM_IDLIST)) {
                query_pop();
                view=get_view_mode(1);  
            }

            sortedRows = get_sorted_rows_from_params();
            dump_all_rows("sorted",sortedRows->num_rows,sortedRows->rows);

            // If it's not a tv/movie detail or boxset view then break
            if (view == VIEW_MENU ||  view == VIEW_ADMIN ) {
                break;
            }

            // Found some data - as we are on a smaller view - filter it
            if (sortedRows->num_rows && sortedRows->num_rows < 50 ) {
                int new_num = sortedRows->num_rows;
                int max_new = sortedRows->num_rows;
                DbItem **new_list = filter_page_items(0,sortedRows->num_rows,sortedRows->rows,max_new,&new_num);
                FREE(sortedRows->rows);
                sortedRows->rows = new_list;
                sortedRows->num_rows=new_num;
            }
            if (sortedRows->num_rows) break;

            // No data found in this view - try to return to the previous view.
            query_pop();
            // Adjust config - 
            // TODO Change the config structure to reload more efficiently.
            //reload_configs();

            config_read_dimensions(1);

            // Now refetch all data again with new parameters.
            sorted_rows_free_all(sortedRows);
            HTML_LOG(0,"reparsing database");
        }

        // Remove and store the last navigation cell. eg if user clicked on cell 12 this is passed in 
        // the URL as @i=12. The url that returns to this page then has i=12. If we have returned to this
        // page we must remove i=12 from the query so that it is not passed to the new urls created for this 
        // page.
        set_selected_item();

        char *skin_name=get_skin_name();


        if (strchr(skin_name,'/') || *skin_name == '.' || !*skin_name ) {

            html_error("Invalid skin name[%s]",skin_name);

        } else {

            playlist_open();
            //exp_test();

            if (view->view_class == VIEW_CLASS_ADMIN) {

                setPermissions();
                display_admin(sortedRows);

            } else {

                char *template = query_val(QUERY_PARAM_TEMPLATE_NAME);
                if (EMPTY_STR(template)) {