Beispiel #1
0
void deliver (FILE * ds, char * filename) {
	FILE * datei;
	if (*filename == '/')
		filename = &filename[1];
		
	datei = fopen(filename, "rb");
	
	if (datei == NULL) return;
	
	struct stat st;
	stat(filename, &st);
	char size[255];
	sprintf(size, "%lld", st.st_size);
	
	fputs("Content-Type: ", ds);
	fputs(content_type(filename), ds);
	fputs("\nContent-Length: ", ds);
	fputs(size, ds);
	fputs("\n\n", ds);
	
	printf("# Delivering: %s\n", filename);
	
	size_t n, m;
	unsigned char buff[128];
	do {
	    n = fread(buff, 1, sizeof buff, datei);
	    if (n) m = fwrite(buff, 1, n, ds);
	    else   m = 0;
		usleep(500);
	} while ((n > 0) && (n == m));
	
	fclose(datei);
}
Beispiel #2
0
void *request_handler(void* arg) {
    int clnt_sock = *((int*)arg);
    char req_line[SMALL_BUF];
    FILE* clnt_read;
    FILE* clnt_write;

    char method[10];
    char ct[15];
    char file_name[30];

    clnt_read = fdopen(clnt_sock, "r");
    clnt_write = fdopen(dup(clnt_sock), "w");
    fgets(req_line, SMALL_BUF, clnt_read);
    if (strstr(req_line, "HTTP/") == NULL) {
        send_error(clnt_write);
        fclose(clnt_read);
        fclose(clnt_write);
        return NULL;
    }
    strcpy(method, strtok(req_line, " /"));
    strcpy(file_name, strtok(NULL, " /"));
    strcpy(ct, content_type(file_name));
    if (strcmp(method, "GET") != 0) {
        send_error(clnt_write);
        fclose(clnt_read);
        fclose(clnt_write);
        return NULL;
    }

    fclose(clnt_read);
    send_data(clnt_write, ct, file_name);
    return NULL;
}
Beispiel #3
0
 /// Get the charset from the CONTENT_TYPE header
 string_type charset()
 {
   string_type ctype(content_type());
   std::size_t pos = ctype.find("charset=");
   string_type val(ctype.substr(pos+8, ctype.find(";", pos)));
   boost::algorithm::trim(val);
   return val.empty() ?  BOOST_CGI_DEFAULT_CHARSET : val;
 }
Beispiel #4
0
int
mimetype_handler(File fc)
{
	if (!fc)  {
		error("File not found 404");
		return error_handler(404);
	}
	if (!fc->mime) fc->mime = lookup_mimetype(fc->name.data);
	content_type(client.response->headers, fc->mime->type.data);
	return fc->mime->handler(fc);
}
Beispiel #5
0
void validate_regex(void* val, void* data, xmlChar* key){
    struct handler_args* h = data;

    // fetch the prompt rule
    char* form_name = get_uri_part(h, QZ_URI_FORM_NAME);
    struct prompt_rule* rule = fetch_prompt_rule(h, form_name, key);
    if (rule == NULL) return;

    // does it have a pattern?
    if (rule->comp_regex == NULL) return;
    
    // is there data there to check?
    int subject_length = strlen(val);
    if (subject_length == 0) return;

    // does the value fit the pattern?
    const int   ovectcount = 30;
    int ovector[ovectcount];
    int rc;

    rc = pcre_exec(rule->comp_regex, NULL, val, subject_length, 0, 0,
        ovector, ovectcount);

    if (rc < 0){ // match failed

        if (h->data == NULL){
            // Then this is the first one, start with an
            // explanatory note about the failure.
            static char* regex_failure_hdr = 
                "One or more fields submitted failed validation.\n"
                "This error should have been caught by the client\n"
                "before the data was submitted.\n"
                "You may be able to recover by using your back\n"
                "button and correcting your data (or may not).\n\n";

            h->data = new_strbuf(regex_failure_hdr, 0);
            content_type(h, "text/plain");
        }

        char* error_msg;
        asprintf(&error_msg, "attribute %s failed regex_pattern %s rc=%d\n\n",
             rule->fieldname, rule->regex_pattern, rc);

        strbuf_append(h->data, new_strbuf(error_msg,0));

        fprintf(h->log, "%f %d %s:%d "
            "fail attribute \"%s\" val [%s] regex_pattern %s rc=%d\n\n",
            gettime(), h->request_id, __func__, __LINE__,
            rule->fieldname, (char*)val, rule->regex_pattern, rc);
        
        free(error_msg);
    }
}
Beispiel #6
0
void
ContainerPainter::add(boost::shared_ptr<Painter> painter, const util::point<double>& offset) {

	{
		// get a write lock
		boost::unique_lock<boost::shared_mutex> lock(_paintersMutex);

		LOG_ALL(containerpainterlog) << "new painter: "
		                             << typeName(*painter) << std::endl;

		// store it in list
		_content.push_back(content_type(painter, offset));
	}

	// update size of this painter
	updateSize();
}
Beispiel #7
0
		bool response_file(Request& req, bool keep_alive, const boost::asio::yield_context& yield)
		{
			std::string path = public_dir_ + req.path();
			std::fstream in(path, std::ios::binary | std::ios::in);
			if (!in)
			{
				return false;
			}

			LOG_DBG << "Response a file";
			in.seekg(0, std::ios::end);

			std::string header =
				boost::str(boost::format(
				"HTTP/1.1 200 OK\r\n"
				"Server: cinatra/0.1\r\n"
				"Date: %1%\r\n"
				"Content-Type: %2%\r\n"
				"Content-Length: %3%\r\n"
				)
				% header_date_str()
				% content_type(path)
				% in.tellg());

			if (keep_alive)
			{
				header += "Connection: Keep-Alive\r\n";
			}

			header += "\r\n";
			in.seekg(0, std::ios::beg);

			boost::asio::async_write(socket_, boost::asio::buffer(header), yield);
			std::vector<char> data(1024 * 1024);
			while (!in.eof())
			{
				in.read(&data[0], data.size());
				//FIXME: warning C4244: “参数”: 从“std::streamoff”转换到“unsigned int”,可能丢失数据.
				boost::asio::async_write(socket_, boost::asio::buffer(data, size_t(in.gcount())), yield);
			}

			return true;
		}
void DndData::Fill(const char* uris)
{
  Reset();

  const char* pch = strtok (const_cast<char*>(uris), "\r\n");
  while (pch)
  {
    glib::String content_type(g_content_type_guess(pch,
                                                   nullptr,
                                                   0,
                                                   nullptr));

    if (content_type)
    {
      types_.insert(content_type.Str());
      uris_to_types_[pch] = content_type.Str();
      types_to_uris_[content_type.Str()].insert(pch);
    }

    uris_.insert(pch);

    pch = strtok (NULL, "\r\n");
  }
}
Beispiel #9
0
//! Generate the HttpBody for the current state of the resource list.
HttpBody* ResourceList::generateRlmiBody(UtlBoolean consolidated,
                                         UtlBoolean fullRlmi,
                                         UtlSList& listToSend)
{
   if (Os::Logger::instance().willLog(FAC_RLS, PRI_DEBUG))
   {
      UtlString l;

      UtlSListIterator resourcesItor(listToSend);
      ResourceReference* resource;
      while ((resource = dynamic_cast <ResourceReference*> (resourcesItor())))
      {
         l.append(*resource->getUri());
         l.append(",");
      }
      if (!l.isNull())
      {
         l.remove(l.length() - 1);
      }

      Os::Logger::instance().log(FAC_RLS, PRI_DEBUG,
                    "ResourceList::generateRlmiBody cons=%d URI='%s' full=%d listToSend='%s'",
                    consolidated,
                    (consolidated ? mResourceListNameCons.data() : mResourceListName.data()),
                    fullRlmi,
                    l.data());
   }

   // Construct the multipart body.
   // We add the <...> here, as they are used in all the contexts where
   // rlmiBodyPartCid appears.
   UtlString rlmiBodyPartCid;
   rlmiBodyPartCid += "<rlmi@";
   rlmiBodyPartCid += getResourceListServer()->getDomainName();
   rlmiBodyPartCid += ">";

   UtlString content_type(CONTENT_TYPE_MULTIPART_RELATED
                          ";type=\"" RLMI_CONTENT_TYPE "\""
                          ";start=\"");
   content_type += rlmiBodyPartCid;
   content_type += "\"";
   HttpBody* body = new HttpBodyMultipart(content_type);

   // This is the Resource List Meta-Information, XML describing the resources
   // and their instances.  It is the main part of the NOTIFY body.
   UtlString rlmi;

   // Generate the initial part of the RLMI.
   rlmi += "<?xml version=\"1.0\"?>\r\n";
   rlmi += "<list xmlns=\"" RLMI_XMLNS "\" uri=\"";
   XmlEscape(rlmi,
             consolidated ? mResourceListNameCons : mResourceListName);
   // Placeholder for version from SIP stack.
   rlmi += "\" version=\"" VERSION_PLACEHOLDER "\" ";

   // Generate either the full or the partial RLMI.
   if (fullRlmi)
   {
      rlmi += "fullState=\"true\">\r\n";
   }
   else
   {
      rlmi += "fullState=\"false\">\r\n";
   }

   // If we implemented names for resource lists, <name> elements would be added here.

   // Iterate through the resources.
   UtlSListIterator resourcesItor(listToSend);
   ResourceReference* resource;
   while ((resource = dynamic_cast <ResourceReference*> (resourcesItor())))
   {
      // Add the content for the resource.
      resource->generateBody(rlmi, *body, consolidated);
   }

   // Generate the postamble for the resource list.
   rlmi += "</list>\r\n";

   // Construct the RLMI body part.
   HttpBody rlmi_body(rlmi.data(), rlmi.length(), RLMI_CONTENT_TYPE);
   UtlDList rlmi_body_parameters;
   rlmi_body_parameters.append(new NameValuePair(HTTP_CONTENT_ID_FIELD,
                                                 rlmiBodyPartCid));

   // Attach the RLMI.
   body->appendBodyPart(rlmi_body, rlmi_body_parameters);

   // Clean up the parameter list.
   rlmi_body_parameters.destroyAll();

   return body;
}
Beispiel #10
0
    //CP_XML_SERIALIZE_ATTR(L"ContentType", content_type());
    //_Wostream << L" />";
    return _Wostream;
}

const wchar_t * override_content_type::ns = L"";
const wchar_t * override_content_type::name = L"Override";

::std::wostream & override_content_type::xml_to_stream(::std::wostream & _Wostream) const
{
    CP_XML_WRITER(_Wostream)
    {
        CP_XML_NODE(L"Override")
        {
            CP_XML_ATTR(L"PartName", part_name());
            CP_XML_ATTR(L"ContentType", content_type());
        }
    }

    //_Wostream << L"<Override ";
    //CP_XML_SERIALIZE_ATTR(L"PartName", part_name());
    //CP_XML_SERIALIZE_ATTR(L"ContentType", content_type());
    //_Wostream << L" />";
    return _Wostream;
}

const wchar_t * content_type::ns = L"";
const wchar_t * content_type::name = L"Types";

::std::wostream & content_type::xml_to_stream(::std::wostream & _Wostream) const
{
/* ****************************************************************************
*
* httpRequestSendWithCurl -
*
* The waitForResponse arguments specifies if the method has to wait for response
* before return. If this argument is false, the return string is ""
*
* NOTE
* We are using a hybrid approach, consisting in a static thread-local buffer of a
* small size that copes with most notifications to avoid expensive
* calloc/free syscalls if the notification payload is not very large.
*
* RETURN VALUES
*   httpRequestSendWithCurl returns 0 on success and a negative number on failure:
*     -1: Invalid port
*     -2: Invalid IP
*     -3: Invalid verb
*     -4: Invalid resource
*     -5: No Content-Type BUT content present
*     -6: Content-Type present but there is no content
*     -7: Total outgoing message size is too big
*     -9: Error making HTTP request
*/
int httpRequestSendWithCurl
(
   CURL                   *curl,
   const std::string&     _ip,
   unsigned short         port,
   const std::string&     protocol,
   const std::string&     verb,
   const std::string&     tenant,
   const std::string&     servicePath,
   const std::string&     xauthToken,
   const std::string&     resource,
   const std::string&     orig_content_type,
   const std::string&     content,
   const std::string&     fiwareCorrelation,
   const std::string&     ngisv2AttrFormat,
   bool                   useRush,
   bool                   waitForResponse,
   std::string*           outP,
   const std::string&     acceptFormat,
   long                   timeoutInMilliseconds
)
{
  char                       portAsString[STRING_SIZE_FOR_INT];
  static unsigned long long  callNo             = 0;
  std::string                result;
  std::string                ip                 = _ip;
  struct curl_slist*         headers            = NULL;
  MemoryStruct*              httpResponse       = NULL;
  CURLcode                   res;
  int                        outgoingMsgSize       = 0;
  std::string                content_type(orig_content_type);

  ++callNo;

  // For content-type application/json we add charset=utf-8
  if (orig_content_type == "application/json")
  {
    content_type += "; charset=utf-8";
  }

  if (timeoutInMilliseconds == -1)
  {
    timeoutInMilliseconds = defaultTimeout;
  }

  lmTransactionStart("to", ip.c_str(), port, resource.c_str());

  // Preconditions check
  if (port == 0)
  {
    LM_E(("Runtime Error (port is ZERO)"));
    lmTransactionEnd();

    *outP = "error";
    return -1;
  }

  if (ip.empty())
  {
    LM_E(("Runtime Error (ip is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -2;
  }

  if (verb.empty())
  {
    LM_E(("Runtime Error (verb is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -3;
  }

  if (resource.empty())
  {
    LM_E(("Runtime Error (resource is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -4;
  }

  if ((content_type.empty()) && (!content.empty()))
  {
    LM_E(("Runtime Error (Content-Type is empty but there is actual content)"));
    lmTransactionEnd();

    *outP = "error";
    return -5;
  }

  if ((!content_type.empty()) && (content.empty()))
  {
    LM_E(("Runtime Error (Content-Type non-empty but there is no content)"));
    lmTransactionEnd();

    *outP = "error";
    return -6;
  }



  // Allocate to hold HTTP response
  httpResponse = new MemoryStruct;
  httpResponse->memory = (char*) malloc(1); // will grow as needed
  httpResponse->size = 0; // no data at this point

  //
  // Rush
  // Every call to httpRequestSend specifies whether RUSH should be used or not.
  // But, this depends also on how the broker was started, so here the 'useRush'
  // parameter is cancelled in case the broker was started without rush.
  //
  // If rush is to be used, the IP/port is stored in rushHeaderIP/rushHeaderPort and
  // after that, the host and port of rush is set as ip/port for the message, that is
  // now sent to rush instead of to its final destination.
  // Also, a few HTTP headers for rush must be setup.
  //
  if ((rushPort == 0) || (rushHost == ""))
  {
    useRush = false;
  }

  if (useRush)
  {
    char         rushHeaderPortAsString[STRING_SIZE_FOR_INT];
    uint16_t     rushHeaderPort     = port;
    std::string  rushHeaderIP       = ip;
    std::string  headerRushHttp;

    ip    = rushHost;
    port  = rushPort;

    snprintf(rushHeaderPortAsString, sizeof(rushHeaderPortAsString), "%d", rushHeaderPort);
    headerRushHttp = "X-relayer-host: " + rushHeaderIP + ":" + rushHeaderPortAsString;
    LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerRushHttp.c_str()));
    headers = curl_slist_append(headers, headerRushHttp.c_str());
    outgoingMsgSize += headerRushHttp.size();

    if (protocol == "https:")
    {
      headerRushHttp = "X-relayer-protocol: https";
      LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerRushHttp.c_str()));
      headers = curl_slist_append(headers, headerRushHttp.c_str());
      outgoingMsgSize += headerRushHttp.size();
    }
  }

  snprintf(portAsString, sizeof(portAsString), "%u", port);

  // ----- User Agent
  char cvBuf[CURL_VERSION_MAX_LENGTH];
  char headerUserAgent[HTTP_HEADER_USER_AGENT_MAX_LENGTH];

  snprintf(headerUserAgent, sizeof(headerUserAgent), "User-Agent: orion/%s libcurl/%s", versionGet(), curlVersionGet(cvBuf, sizeof(cvBuf)));
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerUserAgent));
  headers = curl_slist_append(headers, headerUserAgent);
  outgoingMsgSize += strlen(headerUserAgent) + 1;

  // ----- Host
  char headerHost[HTTP_HEADER_HOST_MAX_LENGTH];

  snprintf(headerHost, sizeof(headerHost), "Host: %s:%d", ip.c_str(), (int) port);
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerHost));
  headers = curl_slist_append(headers, headerHost);
  outgoingMsgSize += strlen(headerHost) + 1;

  // ----- Tenant
  if (tenant != "")
  {
    headers = curl_slist_append(headers, ("fiware-service: " + tenant).c_str());
    outgoingMsgSize += tenant.size() + 16; // "fiware-service: "
  }

  // ----- Service-Path
  if (servicePath != "")
  {
    headers = curl_slist_append(headers, ("Fiware-ServicePath: " + servicePath).c_str());
    outgoingMsgSize += servicePath.size() + strlen("Fiware-ServicePath: ");
  }

  // ----- X-Auth-Token
  if (xauthToken != "")
  {
    headers = curl_slist_append(headers, ("X-Auth-Token: " + xauthToken).c_str());
    outgoingMsgSize += xauthToken.size() + strlen("X-Auth-Token: ");
  }

  // ----- Accept
  std::string acceptedFormats = "application/json";
  if (acceptFormat != "")
  {
    acceptedFormats = acceptFormat;
  }

  std::string acceptString = "Accept: " + acceptedFormats;
  headers = curl_slist_append(headers, acceptString.c_str());
  outgoingMsgSize += acceptString.size();

  // ----- Expect
  headers = curl_slist_append(headers, "Expect: ");
  outgoingMsgSize += 8; // from "Expect: "

  // ----- Content-length
  std::stringstream contentLengthStringStream;
  contentLengthStringStream << content.size();
  std::string headerContentLength = "Content-length: " + contentLengthStringStream.str();
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerContentLength.c_str()));
  headers = curl_slist_append(headers, headerContentLength.c_str());
  outgoingMsgSize += contentLengthStringStream.str().size() + 16; // from "Content-length: "
  outgoingMsgSize += content.size();

  // ----- Content-type
  headers = curl_slist_append(headers, ("Content-type: " + content_type).c_str());
  outgoingMsgSize += content_type.size() + 14; // from "Content-type: "

  // Fiware-Correlator
  std::string correlation = "Fiware-Correlator: " + fiwareCorrelation;
  headers = curl_slist_append(headers, correlation.c_str());
  outgoingMsgSize += correlation.size();

  // Notify Format
  if ((ngisv2AttrFormat != "") && (ngisv2AttrFormat != "JSON") && (ngisv2AttrFormat != "legacy"))
  {
    std::string nFormat = "X-Ngsiv2-AttrsFormat: " + ngisv2AttrFormat;
    headers = curl_slist_append(headers, nFormat.c_str());
    outgoingMsgSize += nFormat.size();
  }

  // Check if total outgoing message size is too big
  if (outgoingMsgSize > MAX_DYN_MSG_SIZE)
  {
    LM_E(("Runtime Error (HTTP request to send is too large: %d bytes)", outgoingMsgSize));

    curl_slist_free_all(headers);

    free(httpResponse->memory);
    delete httpResponse;

    lmTransactionEnd();
    *outP = "error";
    return -7;
  }

  // Contents
  const char* payload = content.c_str();
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (u_int8_t*) payload);

  // Set up URL
  std::string url;
  if (isIPv6(ip))
    url = "[" + ip + "]";
  else
    url = ip;
  url = url + ":" + portAsString + (resource.at(0) == '/'? "" : "/") + resource;

  // Prepare CURL handle with obtained options
  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, verb.c_str()); // Set HTTP verb
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // Allow redirection (?)
  curl_easy_setopt(curl, CURLOPT_HEADER, 1); // Activate include the header in the body output
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // Put headers in place
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeMemoryCallback); // Send data here
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*) httpResponse); // Custom data for response handling

  //
  // There is a known problem in libcurl (see http://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame)
  // which is solved using CURLOPT_NOSIGNAL. If we update some day from libcurl 7.19 (the one that comes with CentOS 6.x) to a newer version
  // (there are some reports about the bug is no longer in libcurl 7.32), using CURLOPT_NOSIGNAL could be not necessary and this be removed).
  // See issue #1016 for more details.
  //
  curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

  //
  // Timeout 
  //
  // The parameter timeoutInMilliseconds holds the timeout time in milliseconds.
  // If the timeout time requested is 0, then no timeuot is used.
  //
  if (timeoutInMilliseconds != 0) 
  {
    curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeoutInMilliseconds);
  }


  // Synchronous HTTP request
  // This was previously a LM_T trace, but we have "promoted" it to INFO due to it is needed to check logs in a .test case (case 000 notification_different_sizes.test)
  LM_I(("Sending message %lu to HTTP server: sending message of %d bytes to HTTP server", callNo, outgoingMsgSize));
  res = curl_easy_perform(curl);

  if (res != CURLE_OK)
  {
    //
    // NOTE: This log line is used by the functional tests in cases/880_timeout_for_forward_and_notifications/
    //       So, this line should not be removed/altered, at least not without also modifying the functests.
    //    
    alarmMgr.notificationError(url, "(curl_easy_perform failed: " + std::string(curl_easy_strerror(res)) + ")");
    *outP = "notification failure";
  }
  else
  {
    // The Response is here
    LM_I(("Notification Successfully Sent to %s", url.c_str()));
    outP->assign(httpResponse->memory, httpResponse->size);
  }

  // Cleanup curl environment

  curl_slist_free_all(headers);

  free(httpResponse->memory);
  delete httpResponse;

  lmTransactionEnd();

  return res == CURLE_OK ? 0 : -9;
}
Beispiel #12
0
/* fills in file-based stuff in the request structure */
void file_stuff(request *r) {
  int fildes;
  int len;
  struct stat statbuf;
  struct tm *tm_time;

  /* no file */
  if(!r->file) {
    r->status = 400;
    return;
  }

  free(r->content_type);
  r->content_type = strdup(content_type(r->file));

  /* forbidden path */
  if(forbidden(r->file)) {
    r->status = 403;
    return;
  }

  /* built-in image? */
  /* skip one out because of the / at the start */
  if(strncmp(r->file, IMAGE_PATH, strlen(IMAGE_PATH)) == 0) {
    builtin_file_stuff(r);
    return;
  }

  /* check file exists */
  if(stat(r->file, &statbuf) != 0) {
    r->status = 404;
    return;
  }

  /* check if dir */
  if(statbuf.st_mode & S_IFDIR) {
    r->is_dir = 1;
    len = strlen(r->reqfile);
    /* redirect if a directory was requested without ending with a '/' */
    if(r->reqfile[len - 1] != '/') {
      r->status = 301;
      r->location = malloc(len + 2);
      strcpy(r->location, r->reqfile);
      strcpy(r->location + len, "/");
    }
  } else {
    r->is_dir = 0;
    /* not a directory, check if file can be read from */
    if((fildes = open(r->file, O_RDONLY)) < 0) {
      r->status = 403;
      return;
    }
    close(fildes);
  }

  /* WARNING: Only responses with status code 200 have content_length and
     last_modified! */

  r->last_modified_t = statbuf.st_mtime;
  tm_time = gmtime(&statbuf.st_mtime);
  if(!r->last_modified) r->last_modified = malloc(64);
  strftime(r->last_modified, 64, "%a, %d %b %Y %T GMT", tm_time);

  r->content_length = statbuf.st_size;
}
Beispiel #13
0
void callback(const HttpRequest* req, HttpResponse* res) {
    Buffer content;
    ServerInfo svr_info;
    StatementsInfo smt_info;

    if (req->path() == "/") {
            res->setStatusCode(HttpResponse::HTTP_OK);
            res->setContentType(CONTEXT_TYPE_HTML);
            res->addHeader("Server", JOINTCOM_FLAG);
            char date[128] = {0};
            get_now(date);
            res->setBody("<html><head><title>JOINTCOM</title></head>"
                                 "<body><h1>Welcom to JOINTCOM</h1>Now is " + std::string(date) +
                         "</body></html>");
    }
    else if (readUrlConfig(req->method(), req->path(), svr_info, smt_info) != -1) {
        if (req->method() == HTTP_GET || req->method() == HTTP_DELETE) {
            if(smt_info.param_count > 0) {
                //固定参数
                //固定参数需匹配参数数量,不匹配时返回404
                if(smt_info.param_count != req->query_param().size()) {
                    res->setHttp404Status("Query-Param error!");
                    return;
                }
                auto it = req->query_param().begin();
                for (int i = 0; i < smt_info.param_count; i++) {
                    auto n = smt_info.sql.find_first_of('?');
                    if (n != std::string::npos) {
                        smt_info.sql.replace(n, 1, it->first);
                        it++;
                    }
                }
            }
            else if (smt_info.param_count == 0 && req->query_param().size() > 0) {
                //自由参数
                auto it = req->query_param().begin();
                std::string temp = " where ";
                for (int i = 0; i < req->query_param().size(); i++) {
                    temp += "[";
                    temp += it->first;
                    temp += "] = '";
                    temp += it->second;
                    temp += "'";
                    if (i != req->query_param().size() - 1) {
                        temp += " and ";
                        it++;
                    }
                }
                smt_info.sql += temp;
            }
            else if(smt_info.param_count == 0 && req->query_param().size() == 0 && req->method() == HTTP_DELETE) {
                //删除方法的参数不允许参数为0, 返回404
                res->setHttp404Status("Delete-Param error!");
                return;
            }
        }
        else if(req->method() == HTTP_POST) {
            std::string body = req->body();
            std::string sql = "";
            std::vector<std::string> vec = split_string(body, "\n");
            for(auto it = vec.begin(); it != vec.end(); it++) {
                std::string val = *it;
                if(val == "") continue;
                std::string temp = smt_info.sql;
                auto n = temp.find_first_of('?');
                if (n != std::string::npos)
                    temp.replace(n, 1, val.c_str());
                else {
                    res->setHttp404Status("Config-Sql error!");
                    return;
                }
                sql += temp + "\n";
            }
            smt_info.sql = sql;
        }

        std::string content_type(CONTEXT_TYPE_PLAIN);
        int ret = db_odbc_exec(svr_info, smt_info, &content, content_type);
        if (ret == -1) {
            res->setHttp404Status(content.buffer());
            return;
        }
        res->setStatusCode(HttpResponse::HTTP_OK);
        res->setContentType(content_type);
        res->addHeader("Server", JOINTCOM_FLAG);
        res->setBody(content.buffer());
    }
    else {
            res->setHttp404Status();
    }
}
Beispiel #14
0
static void do_header(struct rfc2045 *p)
{
struct rfc822t *header;
char	*t;

	if (p->headerlen == 0)	return;
	rfc2045_add_buf( &p->header, &p->headersize, &p->headerlen, "", 1);
				/* 0 terminate */

	/* Parse the header line according to RFC822 */

	header=rfc822t_alloc_new(p->header, NULL, NULL);

	if (!header)	return;	/* Broken header */

	if (header->ntokens < 2 ||
		header->tokens[0].token ||
		header->tokens[1].token != ':')
	{
		rfc822t_free(header);
		return;	/* Broken header */
	}

	t=lower_paste_token(header, 0);

	if (t == 0)
		;
	else if (strcmp(t, "mime-version") == 0)
	{
		free(t);
		mime_version(p, header);
	}
	else if (strcmp(t, "content-type") == 0)
	{
		free(t);
		content_type(p, header);
	} else if (strcmp(t, "content-transfer-encoding") == 0)
	{
		free(t);
		content_transfer_encoding(p, header);
	} else if (strcmp(t, "content-disposition") == 0)
	{
		free(t);
		content_disposition(p, header);
	} else if (strcmp(t, "content-id") == 0)
	{
		free(t);
		content_id(p, header);
	} else if (strcmp(t, "content-description") == 0)
	{
		free(t);
		t=strchr(p->header, ':');
		if (t)	++t;
		while (t && isspace((int)(unsigned char)*t))
			++t;
		content_description(p, t);
	} else if (strcmp(t, "content-language") == 0)
	{
		free(t);
		t=strchr(p->header, ':');
		if (t)	++t;
		while (t && isspace((int)(unsigned char)*t))
			++t;
		content_language(p, t);
	} else if (strcmp(t, "content-base") == 0)
	{
		free(t);
		content_base(p, header);
	} else if (strcmp(t, "content-location") == 0)
	{
		free(t);
		content_location(p, header);
	} else if (strcmp(t, "content-md5") == 0)
	{
		free(t);
		t=strchr(p->header, ':');
		if (t)	++t;
		while (t && isspace((int)(unsigned char)*t))
			++t;
		content_md5(p, t);
	}
	else	free(t);
	rfc822t_free(header);
}
Beispiel #15
0
 this_type& body(const T& t, const std::string& ct = common::content_type<T>::name)
 {
     content_type(ct);
     body_stream() << t;
     return *this;
 }