示例#1
0
static int on_request_recv(nghttp2_session *session,
                           http2_session_data *session_data,
                           http2_stream_data *stream_data) {
  int fd;
  nghttp2_nv hdrs[] = {MAKE_NV(":status", "200")};
  char *rel_path;

  if (!stream_data->request_path) {
    if (error_reply(session, stream_data) != 0) {
      return NGHTTP2_ERR_CALLBACK_FAILURE;
    }
    return 0;
  }
  fprintf(stderr, "%s GET %s\n", session_data->client_addr,
          stream_data->request_path);
  if (!check_path(stream_data->request_path)) {
    if (error_reply(session, stream_data) != 0) {
      return NGHTTP2_ERR_CALLBACK_FAILURE;
    }
    return 0;
  }
  for (rel_path = stream_data->request_path; *rel_path == '/'; ++rel_path)
    ;
  fd = open(rel_path, O_RDONLY);
  if (fd == -1) {
    if (error_reply(session, stream_data) != 0) {
      return NGHTTP2_ERR_CALLBACK_FAILURE;
    }
    return 0;
  }
  stream_data->fd = fd;

  if (send_response(session, stream_data->stream_id, hdrs, ARRLEN(hdrs), fd) !=
      0) {
    close(fd);
    return NGHTTP2_ERR_CALLBACK_FAILURE;
  }
  return 0;
}
示例#2
0
bool CHttpServer::process(SOCKET sock)
{
    m_sock = sock;

	// First of all, make socket non-blocking
#if defined(WINDOWS_PLATFORM)
	unsigned long optval = 1;
	if(::ioctlsocket(m_sock, FIONBIO, &optval) == SOCKET_ERROR) {
		RAWLOG_ERROR1("Can not set non-blocking socket mode: %d", RHO_NET_ERROR_CODE);
		return false;
	}
#else
	int flags = fcntl(m_sock, F_GETFL);
	if (flags == -1) {
		RAWLOG_ERROR1("Can not get current socket mode: %d", errno);
		return false;
	}
	if (fcntl(m_sock, F_SETFL, flags | O_NONBLOCK) == -1) {
		RAWLOG_ERROR1("Can not set non-blocking socket mode: %d", errno);
		return false;
	}
#endif

    // Read request from socket
    ByteVector request;

    String method, uri, query;
    HeaderList headers;
    String body;
    if (!parse_request(method, uri, query, headers, body)) {
        RAWLOG_ERROR("Parsing error");
        send_response(create_response("500 Internal Error"));
        return false;
    }

    RAWLOG_INFO1("Process URI: '%s'", uri.c_str());

    return decide(method, uri, query, headers, body);
}
static void
handle_app_chooser_close (AppChooserDialog *dialog,
                          gpointer data)
{
  AppDialogHandle *handle = data;
  GAppInfo *info;

  info = app_chooser_dialog_get_info (dialog);
  if (info != NULL)
    {
      const char *desktop_id = g_app_info_get_id (info);
      handle->response = 0;
      handle->chosen = g_strndup (desktop_id, strlen (desktop_id) - strlen (".desktop"));
    }
  else
    {
      handle->response = 1;
      handle->chosen = NULL;
    }

  send_response (handle);
}
示例#4
0
void wait_for_connected() {
    pthread_t workThread;

    //start sending thread
    pthread_create(&workThread, NULL, send_ready_func, NULL);

    //wait for FTM alive
    char buf[BUF_SIZE];
    while(1) {
        serial_read(buf);
        if(!strncasecmp(buf, "FTM Alive", 9)) {
            PRINT_LOG("usb cable connected\n");
            connected = 1;
            break;
        }
    }
    pthread_join(workThread, NULL);

    //special response
    send_result("Recv:\r\nusb cable connected\r\n");
    send_response(NULL, 0);
}
LOCAL void ICACHE_FLASH_ATTR eventCB(System_Event_t *event) {
        switch(event->event) {
            case EVENT_STAMODE_CONNECTED:
                os_printf("Event: EVENT_STAMODE_CONNECTED");
                break;
            case EVENT_STAMODE_DISCONNECTED:
                os_printf("Event: EVENT_STAMODE_DISCONNECTED");
                break;
            case EVENT_STAMODE_AUTHMODE_CHANGE:
                os_printf("Event: EVENT_STAMODE_AUTHMODE_CHANGE");
                break;
            case EVENT_STAMODE_GOT_IP:
                os_printf("Event: EVENT_STAMODE_GOT_IP");
                //os_printf("IP: %d.%d.%d.%d\n", IP2STR(&event->event_info.got_ip.ip));
                //setupTCP();
                break;
            case EVENT_SOFTAPMODE_STACONNECTED:{
                struct station_info *stationInfo = wifi_softap_get_station_info();
                if(stationInfo != NULL){
                    os_printf("%d.%d.%d.%d", IP2STR(&(stationInfo->ip))); 
                    os_sprintf(attackip, "%d.%d.%d.%d", IP2STR(&(stationInfo->ip)));
                    send_response();            
                }
                wifi_softap_free_station_info(); 
                os_printf("Event: EVENT_SOFTAPMODE_STACONNECTED");
                }
                break;
            case EVENT_SOFTAPMODE_STADISCONNECTED:
                os_printf("Event: EVENT_SOFTAPMODE_STADISCONNECTED");
                break;
            case EVENT_SOFTAPMODE_PROBEREQRECVED:
                //os_printf("Event: EVENT_PROBEREQUEST");
                break;
            default:
                os_printf("Unexpected event: %d\r\n", event->event);
                break;
        }
} // End of eventCB
示例#6
0
文件: vcl.c 项目: varnish/vagent2
static unsigned int
vcl_json(struct http_request *request, const char *arg, void *data)
{
	struct agent_core_t *core = data;
	struct vcl_priv_t *vcl;
	struct ipc_ret_t vret;
	struct vsb *json;
	struct http_response *resp;

	GET_PRIV(core, vcl);

	assert(STARTS_WITH(request->url, "/vcljson"));
	assert(request->method == M_GET);

	if (arg) {
		http_reply(request->connection, 404,
		    "/vcljson takes no argument");
		return (0);
	}

	ipc_run(vcl->vadmin, &vret, "vcl.list");
	if (vret.status == 400)
		http_reply(request->connection, 500, vret.answer);
	else {
		json = vcl_list_json(vret.answer);
		assert(VSB_finish(json) == 0);
		resp = http_mkresp(request->connection, 200, NULL);
		resp->data = VSB_data(json);
		resp->ndata = VSB_len(json);
		http_add_header(resp, "Content-Type", "application/json");
		send_response(resp);
		http_free_resp(resp);
		VSB_clear(json);
		VSB_delete(json);
	}
	free(vret.answer);
	return (0);
}
                        /**
                         * Is called when the message is received by the server
                         * @param hdl the connection handler
                         * @param raw_msg the received message
                         */
                        virtual void on_message(websocketpp::connection_hdl hdl, server::message_ptr raw_msg) {
                            LOG_DEBUG << "Received a message!" << END_LOG;

                            //Create an empty json message
                            incoming_msg * jmsg = new incoming_msg();

                            //De-serialize the message and then handle based on its type
                            try {
                                string raw_msg_str = raw_msg->get_payload();

                                LOG_DEBUG << "Received JSON msg: " << raw_msg_str << END_LOG;

                                //De-serialize the message
                                jmsg->de_serialize(raw_msg_str);

                                //Handle the request message based on its type
                                switch (jmsg->get_msg_type()) {
                                    case msg_type::MESSAGE_TRANS_JOB_REQ:
                                        translation_request(hdl, new trans_job_req_in(jmsg));
                                        break;
                                    case msg_type::MESSAGE_SUPP_LANG_REQ:
                                        language_request(hdl, new supp_lang_req_in(jmsg));
                                        break;
                                    case msg_type::MESSAGE_PRE_PROC_JOB_REQ:
                                        pre_process_request(hdl, new proc_req_in(jmsg));
                                        break;
                                    case msg_type::MESSAGE_POST_PROC_JOB_REQ:
                                        post_process_request(hdl, new proc_req_in(jmsg));
                                        break;
                                    default:
                                        THROW_EXCEPTION(string("Unsupported request type: ") + to_string(jmsg->get_msg_type()));
                                }
                            } catch (std::exception & e) {
                                //Send the error response, NOTE! This is not a JSON we are sending
                                //back, but just a string, as someone violated the protocol!
                                send_response(hdl, e.what());
                            }
                        }
static void
account_dialog_done (GtkWidget *widget,
                     int response,
                     const char *user_name,
                     const char *real_name,
                     const char *icon_file,
                     gpointer user_data)
{
  AccountDialogHandle *handle = user_data;

  g_clear_pointer (&handle->user_name, g_free);
  g_clear_pointer (&handle->real_name, g_free);
  g_clear_pointer (&handle->icon_uri, g_free);

  switch (response)
    {
    default:
      g_warning ("Unexpected response: %d", response);
      /* Fall through */
    case GTK_RESPONSE_DELETE_EVENT:
      handle->response = 2;
      break;

    case GTK_RESPONSE_CANCEL:
      handle->response = 1;
      break;

    case GTK_RESPONSE_OK:
      handle->user_name = g_strdup (user_name);
      handle->real_name = g_strdup (real_name);
      if (icon_file)
        handle->icon_uri = g_filename_to_uri (icon_file, NULL, NULL);
      handle->response = 0;
      break;
    }

  send_response (handle);
}
示例#9
0
文件: ftserve.c 项目: beckysag/ftp
/** 
 * Log in connected client
 */
int ftserve_login(int sock_control)
{	
	char buf[MAXSIZE];
	char user[MAXSIZE];
	char pass[MAXSIZE];	
	memset(user, 0, MAXSIZE);
	memset(pass, 0, MAXSIZE);
	memset(buf, 0, MAXSIZE);
	
	// Wait to recieve username
	if ( (recv_data(sock_control, buf, sizeof(buf)) ) == -1) {
		perror("recv error\n"); 
		exit(1);
	}	

	int i = 5;
	int n = 0;
	while (buf[i] != 0)
		user[n++] = buf[i++];
	
	// tell client we're ready for password
	send_response(sock_control, 331);					
	
	// Wait to recieve password
	memset(buf, 0, MAXSIZE);
	if ( (recv_data(sock_control, buf, sizeof(buf)) ) == -1) {
		perror("recv error\n"); 
		exit(1);
	}
	
	i = 5;
	n = 0;
	while (buf[i] != 0) {
		pass[n++] = buf[i++];
	}
	
	return (ftserve_check_user(user, pass));
}
示例#10
0
/**
 * Send failure notification of general UDF execution, but check for special
 * LDT errors and return specific Wire Protocol error codes for these cases:
 * (1) Record not found (2)
 * (2) LDR Collection item not found (125)
 *
 * All other errors get the generic 100 (UDF FAIL) code.
 *
 * Parse (Actually, probe) the error string, and if we see this pattern:
 * FileName:Line# 4digits:LDT-<Error String>
 * For example:
 * .../aerospike-lua-core/src/ldt/lib_llist.lua:982: 0002:LDT-Top Record Not Found
 * All UDF errors (LDT included), have the "filename:line# " prefix, and then
 * LDT errors follow that with a known pattern:
 * (4 digits, colon, LDT-<Error String>).
 * We will check the error string by looking for specific markers after the
 * the space that follows the filename:line#.  If we see the markers, we will
 * parse the LDT error code and use that as the wire protocol error if it is
 * one of the special ones:
 * (1)  "0002:LDT-Top Record Not Found"
 * (2)  "0125:LDT-Item Not Found"
 */
static inline int
send_udf_failure(udf_call *call, int vtype, void *val, size_t vlen)
{
	// We need to do a quick look to see if this is an LDT error string.  If it
	// is, then we'll look deeper.  We start looking after the first space.
	char * charptr;
	char * valptr = (char *) val;
	long error_code;

	// Start with the space, if it exists, as the marker for where we start
	// looking for the LDT error contents.
	if ((charptr = strchr((const char *) val, ' ')) != NULL) {
		// We must be at least 10 chars from the end, so if we're less than that
		// we are obviously not looking at an LDT error.
		if (&charptr[9] < &valptr[vlen]) {
			if (memcmp(&charptr[5], ":LDT-", 5) == 0) {
				error_code = strtol(&charptr[1], NULL, 10);
				if (error_code == AS_PROTO_RESULT_FAIL_NOTFOUND ||
					error_code == AS_PROTO_RESULT_FAIL_COLLECTION_ITEM_NOT_FOUND)
				{
					call->transaction->result_code = error_code;
					cf_debug(AS_UDF, "LDT Error: Code(%ld) String(%s)",
							error_code, (char *) val);
					// Send an "empty" response, with no failure bin.
					as_transaction *    tr          = call->transaction;
					single_transaction_response(tr, tr->rsv.ns, NULL/*ops*/,
							NULL /*bin*/, 0 /*nbins*/, 0, 0, NULL, NULL);
					return 0;
				}
			}
		}
	}

	cf_debug(AS_UDF, "Non-special LDT or General UDF Error(%s)", (char *) val);

	call->transaction->result_code = AS_PROTO_RESULT_FAIL_UDF_EXECUTION;
	return send_response(call, "FAILURE", 7, vtype, val, vlen);
}
示例#11
0
static void
answer_file(struct vmod_fsdirector_file_system *fs, struct stat *stat_buf,
    const char *path)
{
	mode_t mode = stat_buf->st_mode;

	if (S_ISREG(mode)) {
		if (stat_buf->st_size) {
			send_response(fs, stat_buf, path);
		}
		else {
			prepare_answer(&fs->htc, 204);
			prepare_body(&fs->htc);
		}
	}
	else if (S_ISLNK(mode)) {
		send_redirect(fs, path);
	}
	else {
		prepare_answer(&fs->htc, 404);
		prepare_body(&fs->htc);
	}
}
示例#12
0
/* Given a HTTP message and the size of the message 
 * Responds to the given socket with the approrpriate
 * HTTP response. The space allocated for message should
 * be at least 1 more than req_size */
status respond_to(char* buf, int confd)
{
    char resource[BUFLEN+1],
         *resource_line, *headers, *current;
    int result;
    
    current = buf;
    /*  Cut off the Resource line */
    resource_line = strsep_str(&current, "\r\n"); 

    /*  Get the resource, if error with parsing request line, send 400 response */
    if ((result = parse_request_line(resource_line, resource)) != OK) {
        printf("Recieved badly formatted request line from connection %d\n",confd);
        return send_error(result, confd);
    }

    printf("request good\n");

    headers = strsep_str(&current, "\r\n\r\n");
    printf("headers:%s\n",headers);
     
    return send_response(resource, confd);
}
示例#13
0
static int error_reply(nghttp2_session *session,
                       http2_stream_data *stream_data) {
  int rv;
  ssize_t writelen;
  int pipefd[2];
  nghttp2_nv hdrs[] = {MAKE_NV(":status", "404")};

  rv = pipe(pipefd);
  if (rv != 0) {
    warn("Could not create pipe");
    rv = nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE,
                                   stream_data->stream_id,
                                   NGHTTP2_INTERNAL_ERROR);
    if (rv != 0) {
      warnx("Fatal error: %s", nghttp2_strerror(rv));
      return -1;
    }
    return 0;
  }

  writelen = write(pipefd[1], ERROR_HTML, sizeof(ERROR_HTML) - 1);
  close(pipefd[1]);

  if (writelen != sizeof(ERROR_HTML) - 1) {
    close(pipefd[0]);
    return -1;
  }

  stream_data->fd = pipefd[0];

  if (send_response(session, stream_data->stream_id, hdrs, ARRLEN(hdrs),
                    pipefd[0]) != 0) {
    close(pipefd[0]);
    return -1;
  }
  return 0;
}
示例#14
0
/// Mangelwurzel receives a response. It will add all the Via headers from the
/// original request back on and send the response on. It can also change
/// the response in various ways depending on the configuration that was
/// specified in the Route header of the original request.
/// - It can mangle the dialog identifiers using its mangalgorithm.
/// - It can mangle the Contact URI using its mangalgorithm.
/// - It can mangle the Record-Route and Route headers URIs.
void MangelwurzelTsx::on_rx_response(pjsip_msg* rsp, int fork_id)
{
  pj_pool_t* pool = get_pool(rsp);

  if (_config.dialog)
  {
    mangle_dialog_identifiers(rsp, pool);
  }

  if (_config.req_uri)
  {
    mangle_contact(rsp, pool);
  }

  if (_config.routes)
  {
    mangle_record_routes(rsp, pool);
    mangle_routes(rsp, pool);
  }

  add_via_hdrs(rsp, pool);

  send_response(rsp);
}
示例#15
0
void send_delete_res(int status, int num_msg)
{
  response_t res;
  res.status_code = status;

  if (status == STATUS_OK)
  {
    res.data = malloc(sizeof(int));
    if (res.data == NULL)
      return;
    *((int *) res.data) = num_msg;
    res.data_len = sizeof(int);
  }
  else
  {
    res.data = NULL;
    res.data_len = 0;
  }

  send_response(&res, CMD_DELETE);

  if (res.data)
    free(res.data);
}
示例#16
0
文件: rpc.cpp 项目: tigusoft/galaxy42
void c_rpc_server::c_session::execute_rpc_command(const std::string &input_message) {
	try {
		nlohmann::json j = nlohmann::json::parse(input_message);
                const std::string cmd_name = j["cmd"];//.begin().value();
                dbg("cmd name " << cmd_name);
		// calling rpc function
		nlohmann::json json_response;
		{
			LockGuard<Mutex> lg(m_rpc_server_ptr->m_rpc_functions_map_mutex);
			json_response = m_rpc_server_ptr->m_rpc_functions_map.at(cmd_name)(input_message);
		}
		json_response["id"] = get_command_id();
		if (j.find("id")!= j.end()) {
			json_response["re"] = j["id"];
		}
		send_response(json_response);
	}
	catch (const std::exception &e) {
		_erro( "exception in execute_rpc_command " << e.what() );
		_erro( "close connection\n" );
		delete_me();
		return;
	}
}
示例#17
0
          int handle_renew_lease(ObPacket* ob_packet)
          {
            int ret = OB_SUCCESS;

            ObDataBuffer* data_buffer = ob_packet->get_buffer();
            if (NULL == data_buffer)
            {
              TBSYS_LOG(ERROR, "data_buffer is NUll should not reach this");
              ret = OB_ERROR;
            }
            else
            {
              ObServer slave_addr;
              char addr_buf[1024];
              ret = slave_addr.deserialize(data_buffer->get_data(), data_buffer->get_capacity(),
                 data_buffer->get_position());
              slave_addr.to_string(addr_buf, sizeof(addr_buf));
              addr_buf[sizeof(addr_buf) - 1] = '\0';
              TBSYS_LOG(DEBUG, "recv renew lease request, slave_addr=%s, ret=%d", addr_buf, ret);
              tbnet::Connection* connection = ob_packet->get_connection();
              char buf[10 * 1024];
              ObDataBuffer out_buffer(buf, sizeof(buf));

              ObResultCode response;
              response.result_code_ = OB_SUCCESS;
              response.serialize(out_buffer.get_data(), out_buffer.get_capacity(),
                  out_buffer.get_position());

              int32_t version = 1;
              int32_t channel_id = ob_packet->getChannelId();
              ret = send_response(OB_RENEW_LEASE_RESPONSE, version, out_buffer, connection, channel_id);
              TBSYS_LOG(DEBUG, "send renew lease response, ret=%d", ret);
            }

            return ret;
          }
示例#18
0
文件: server.c 项目: RPI-HPC/cq
static int worker()
{
	unsigned char exit_status;

	int ret;

	void *ctx = zmq_ctx_new();
	void *sock = zmq_socket(ctx, ZMQ_REP);

	zmq_connect(sock, WORKER_IPC);

	while (1) {
		exit_status = 1;
		ret = process_msg(sock, &exit_status);

		if (ret < 0) {
			if (ret == -2)
				break;
			printf("Failed to receive/process message\n");
		}

		send_response(sock, ret, exit_status);
	}

	printf("Worker shutting down...\n");

	ret = zmq_close(sock);
	if (ret < 0)
		fprintf(stderr, "Failed to close socket\n");

	ret = zmq_ctx_destroy(ctx);
	if(ret < 0)
		fprintf(stderr, "Failed to stop ZMQ\n");

	return 0;
}
int		send_motd(int fd, char hostname[1024])
{
  char		*tmp1;
  char		*tmp2;

  if ((tmp1 = str_concat(":- ", hostname, " Message of the day -")) == NULL
      || (tmp2 = str_concat(":- By connecting to ", hostname,
			    " you indicate that you")) == NULL)
    return (-1);
  send_response(fd, "375", tmp1);
  send_response(fd, "372", tmp2);
  send_response(fd, "372", ":- have read and accept our policies");
  send_response(fd, "372", ":- In particular\
 we would like to thank the sponsor");
  send_response(fd, "372", ":- of this server, the asteks");
  send_response(fd, "372", ":-");
  send_response(fd, "376", ":End of /MOTD command.");
  free(tmp1);
  free(tmp2);
  return (0);
}
示例#20
0
void handle_client(int socket) {
  node *cookie, *param;
  service cmd;
  http_method method;
  http_response resp;
  int bytes, s, expected_len, header_len;
  char req[BUFFER_SIZE], buf[BUFFER_SIZE];
  const char *path;
  char *connection, *req_body_len;
  time_t since_time;

  /* TODO Loop receiving requests and sending appropriate responses,
   *      until one of the conditions to close the connection is
   *      met.
   */
  cookie = param = resp.expire = resp.cookie = NULL;

  do {
    // New request
    free_list(resp.cookie);
    free_list(resp.expire);
    if (cookie) free_list(cookie);
    if (param) free_list(param);
    cookie = param = NULL;
    memset(&resp, 0, sizeof(http_response));
    memset(req, 0, BUFFER_SIZE);
    bytes = 0;

    // Wait for HTTP header to complete
    do {
      bytes += recv(socket, req + bytes, BUFFER_SIZE, 0);
      header_len = http_header_complete(req, bytes);
    } while (header_len == -1);
    
    // Receive body if there is content length
    if (strstr(req, HDR_CONTENT_LEN)) {
      strcpy(buf, req);
      req_body_len = get_header_value_from_req(buf, HDR_CONTENT_LEN);
      expected_len = atoi(req_body_len) + header_len;
      while (bytes < expected_len) {
         bytes += recv(socket, req + bytes, BUFFER_SIZE, 0);
      }
    }
    // printf("recv %i bytes\n", bytes);

    // Get HTTP method
    method = http_parse_method(req);

    // Get path
    strcpy(buf, req);
    path = http_parse_path(http_parse_uri(buf));
    // printf("Request: %s\n", path);

    // Parse cookies 
    if (strstr(req, HDR_COOKIE)) {
      strcpy(buf, req);
      cookie = get_cookies_from_header(get_header_value_from_req(buf, HDR_COOKIE));
    } else {
      cookie = NULL;
    }

    // Match service command
    cmd = SERV_UNKNOWN;
    for (s= 0; s < SERV_UNKNOWN; s++) {
      if (strncasecmp(path, service_str[s], strlen(service_str[s])) == 0) {
        cmd = s;
        break;
      }
    }

    // Handle command
    switch(cmd) {
      case SERV_KNOCK:
      case SERV_LOGIN:
      case SERV_LOGOUT:
      case SERV_GETFILE:
      case SERV_ADDCART:
      case SERV_DELCART:
      case SERV_CHECKOUT:
        if (method == METHOD_GET) {
          param = get_params_from_query(get_query_str_from_path(path));
          if (cmd == SERV_KNOCK) {
            knock_handler(&resp, cookie);
          } else if (cmd == SERV_LOGIN) {
            login_handler(&resp, param);
          } else if (cmd == SERV_LOGOUT) {
            logout_handler(&resp, cookie);
          } else if (cmd == SERV_GETFILE) {
            since_time = 0;
            strcpy(buf, req);
            if (strstr(buf, HDR_IF_MOD_SINCE)) {
              if (!RFC_822_to_time(strstr(buf, HDR_IF_MOD_SINCE) + 
                    strlen(HDR_IF_MOD_SINCE), &since_time)) {
                since_time = 0;
              }
            }
            getfile_handler(&resp, param, since_time);
          } else if (cmd == SERV_ADDCART) {
            addcart_handler(&resp, param, cookie);
          } else if (cmd == SERV_DELCART) {
            delcart_handler(&resp, param, cookie);
          } else if (cmd == SERV_CHECKOUT) {
            checkout_handler(&resp, cookie);
          } else {
            resp.status = NOT_FOUND;
          }
        } else {
          resp.allow = METHOD_GET;
          resp.status = METHOD_NOT_ALLOWED;
        }
        break;
      case SERV_PUTFILE:
        if (method == METHOD_POST) {
          strcpy(buf, req);
          param = get_params_from_query((char*) http_parse_body(buf, bytes));
          putfile_handler(&resp, cookie, param);
        } else {
          resp.allow = METHOD_POST;
          resp.status = METHOD_NOT_ALLOWED;
        }
        break;
      default:
        resp.status = NOT_FOUND;
        break;
    }

    // Check if status not ok or 
    // client wants to close connection after completing request
    if (resp.status != OK) {
      resp.connection = CLOSE;
    } else if (strstr(req, "Connection:")) {
      connection = http_parse_header_field(buf, bytes, "Connection");
      if (strcmp(connection, "close") == 0) {
        resp.connection = CLOSE;
      }
    }

    send_response(socket, &resp);  
  } while (resp.connection != CLOSE);
}
示例#21
0
void mfd::ProtobufMessageProcessor::send_response(::google::protobuf::uint32 id, ResultMessage* response)
{
    send_response(id, static_cast<google::protobuf::Message*>(response));
}
示例#22
0
文件: daemon.c 项目: plepe/mod_tile
/**
 * This function is used as a the start function for the slave renderer thread.
 * It pulls a request from the central queue of requests and dispatches it to
 * the slave renderer. It then blocks and waits for the response with no timeout.
 * As it only sends one request at a time (there are as many slave_thread threads as there
 * are rendering threads on the slaves) nothing gets queued on the slave and should get
 * rendererd immediately. Thus overall, requests should be nicely load balanced between
 * all the rendering threads available both locally and in the slaves.
 */
void *slave_thread(void * arg) {
    renderd_config * sConfig = (renderd_config *) arg;

    int pfd = FD_INVALID;
    int retry;
    size_t ret_size;

    struct protocol * resp;
    struct protocol * req_slave;

    req_slave = (struct protocol *)malloc(sizeof(struct protocol));
    resp = (struct protocol *)malloc(sizeof(struct protocol));
    bzero(req_slave, sizeof(struct protocol));
    bzero(resp, sizeof(struct protocol));

    while (1) {
        if (pfd == FD_INVALID) {
            pfd = client_socket_init(sConfig);
            if (pfd == FD_INVALID) {
                if (sConfig->ipport > 0) {
                    syslog(LOG_ERR,
                        "Failed to connect to render slave %s:%i, trying again in 30 seconds",
                        sConfig->iphostname, sConfig->ipport);
                } else {
                    syslog( LOG_ERR,
                            "Failed to connect to render slave %s, trying again in 30 seconds",
                            sConfig->socketname);
                }
                sleep(30);
                continue;
            }
        }

        enum protoCmd ret;
        struct item *item = fetch_request();
        if (item) {
            struct protocol *req = &item->req;
            req_slave->ver = PROTO_VER;
            req_slave->cmd = cmdRender;
            strcpy(req_slave->xmlname, req->xmlname);
            req_slave->x = req->x;
            req_slave->y = req->y;
            req_slave->z = req->z;

            /*Dispatch request to slave renderd*/
            retry = 2;
            syslog(LOG_INFO,
                    "Dispatching request to slave thread on fd %i", pfd);
            do {
                ret_size = send(pfd, req_slave, sizeof(struct protocol), 0);

                if (ret_size == sizeof(struct protocol)) {
                    //correctly sent command to slave
                    break;
                }

                if (errno != EPIPE) {
                    syslog(LOG_ERR,
                            "Failed to send cmd to render slave, shutting down thread");
                    free(resp);
                    free(req_slave);
                    close(pfd);
                    return NULL;
                }

                syslog(LOG_WARNING, "Failed to send cmd to render slave, retrying");
                close(pfd);
                pfd = client_socket_init(sConfig);
                if (pfd == FD_INVALID) {
                    syslog(LOG_ERR,
                            "Failed to re-connect to render slave, dropping request");
                    ret = cmdNotDone;
                    send_response(item, ret);
                    break;
                }
            } while (retry--);
            if (pfd == FD_INVALID || ret_size != sizeof(struct protocol)) {
                continue;
            }

            ret_size = 0;
            retry = 10;
            while ((ret_size < sizeof(struct protocol)) && (retry > 0)) {
                ret_size = recv(pfd, resp + ret_size, (sizeof(struct protocol)
                        - ret_size), 0);
                if ((errno == EPIPE) || ret_size == 0) {
                    close(pfd);
                    pfd = FD_INVALID;
                    ret_size = 0;
                    syslog(LOG_ERR, "Pipe to render slave closed");
                    break;
                }
                retry--;
            }
            if (ret_size < sizeof(struct protocol)) {
                if (sConfig->ipport > 0) {
                    syslog( LOG_ERR,
                            "Invalid reply from render slave %s:%i, trying again in 30 seconds",
                            sConfig->iphostname, sConfig->ipport);
                } else {
                    syslog( LOG_ERR,
                            "Invalid reply render slave %s, trying again in 30 seconds",
                            sConfig->socketname);
                }

                ret = cmdNotDone;
                send_response(item, ret);
                sleep(30);
            } else {
                ret = resp->cmd;
                send_response(item, ret);
                if (resp->cmd != cmdDone) {
                    if (sConfig->ipport > 0) {
                        syslog( LOG_ERR,
                                "Request from render slave %s:%i did not complete correctly",
                                sConfig->iphostname, sConfig->ipport);
                    } else {
                        syslog( LOG_ERR,
                                "Request from render slave %s did not complete correctly",
                                sConfig->socketname);
                    }
                    //Sleep for a while to make sure we don't overload the renderer
                    //This only happens if it didn't correctly block on the rendering
                    //request
                    sleep(30);
                }
            }

        } else {
            sleep(1); // TODO: Use an event to indicate there are new requests
        }
    }
    free(resp);
    free(req_slave);
    return NULL;
}
示例#23
0
void serial_mainloop(void)
{

	unsigned char buf;
	int countbyte = 0, started = 0;
	datarecord data;	// used to collect datas from plc
	datarecord data_response;	// used to send responses to plc

	setzero(&data, sizeof(data));
	first_loop = 1;

	while (1) {

		int buflen = 0;

		buflen = read(portfd, &buf, 1);

		if (buflen == -1) {
			printFatal(strerror(errno));
		}

		if (!started && buf == SOH && !countbyte) {
			started = 1;
			countbyte++;
			data.start = buf;
			continue;
		}

		if (started) {
			switch (countbyte) {
			case 1:
				/* 0x18 == 24 */
				/* if byte 1 isn't 0x18 retry... */
				if (buf != 0x18) {
					started = 0;
					countbyte = 0;
					continue;
				}
				data.length = buf;
				break;
				/* if byte 2 isn't 0x04 retry... */
			case 2:
				if (buf != 0x04) {
					started = 0;
					countbyte = 0;
					continue;
				}
				data.cmd = buf;
				break;
			}

			/* put bytes from 3 to 27 into the struct field */
			if (countbyte >= 3 && countbyte < data.length + 3) {
				data.databytes[countbyte - 3] = buf;
			}

			/* the byte 27 is the checksum given by the plc */
			if (countbyte == 27) {
				data.checksum = buf;
				if (cfg.verbose) {
					// TODO: improve logging and printf debug behaviour
					// TODO: take the log util functions from netsukuku src
					printf
					    ("catch BCC checksum value: %#x\n",
					     data.checksum);
					printf
					    ("calculated BCC checksum value: %#x\n",
					     (unsigned char)
					     calculateBCC(data));
				}
			}

			/* the byte 28 is the last byte of the record and it must be ETX */
			if (countbyte == 28 && buf == ETX) {
				data.end = buf;
				started = 0;
				countbyte = 0;
				int tmpcurr = 0;
				float tmpvolt = 0;

				// MAX_VOLT : MAX_HEX_VALUE = x : bytes
				tmpvolt =
				    (unsigned int) FETCH2BYTES(5, 4,
							       data.databytes);
				if (tmpvolt > MAX_HEX_VALUE)
					data.voltage = 0;
				else
					data.voltage =
					    tmpvolt * (float) MAX_VOLT /
					    (float) MAX_HEX_VALUE *emb_info.k1;

				tmpcurr =
				    (unsigned int) FETCH2BYTES(7, 6,
							       data.databytes);
				if (tmpcurr > MAX_HEX_VALUE)
					data.current = 0;
				else
					data.current =
					    (int) ((float) tmpcurr *
						   (float) MAX_VOLT /
						   (float) MAX_HEX_VALUE *
						   emb_info.k2);

				data.encoder[0] =
				    (unsigned long int) FETCH4BYTES(data.
								    databytes,
								    8) /
				    emb_info.array_island_k1[0];
				data.encoder[1] =
				    (unsigned long int) FETCH4BYTES(data.
								    databytes,
								    12) /
				    emb_info.array_island_k1[1];
				data.encoder[2] =
				    (unsigned long int) FETCH4BYTES(data.
								    databytes,
								    16) /
				    emb_info.array_island_k1[2];
				data.encoder[3] =
				    (unsigned long int) FETCH4BYTES(data.
								    databytes,
								    20) /
				    emb_info.array_island_k1[3];
				if (cfg.verbose) {
					// TODO: improve logging and printf debug behaviour
					printf
					    ("contacolpi1: %f, contacolpi2: %f, ",
					     data.encoder[0], data.encoder[1]);
					printf
					    ("contacolpi3: %f, contacolpi4: %f, ",
					     data.encoder[2], data.encoder[3]);
					printf
					    ("voltage value: %f, current value: %d\n",
					     data.voltage, data.current);
				}

				if (cfg.verbose) {
					int i;
					// TODO: take the log util functions from netsukuku src
					// TODO: improve logging and printf debug behaviour
					// printf("catch start code: %#x\n", data.start);
					// printf("catch len code: %#x\n",   data.length);
					// printf("catch cmd  code: %#x\n",  data.cmd);
					for (i = 0; i < 24; i++) {
						printf("byte[%d]: %#x\n",
						       i, data.databytes[i]);
					}
				}

				/* if the checksum given by the plc is the same we have 
				 * calculated send ack */
				if ((unsigned char) calculateBCC(data) ==
				    (unsigned char) data.checksum) {
					/* compile the response data record with the ACK byte
					 * the response is the same record except for the first 
					 * data byte that is ACK
					 */
					memcpy(&data_response, &data,
					       sizeof(data));
					data_response.databytes[0] = ACK;
					connect_db(cfg.dsn, cfg.dbuser,
						   cfg.dbpass);
					if (cfg.polling)
						get_embedded_infos();
					/* TODO: do all the processing SQL things */
					do_sql_things(data);
					disconnect_db();
					if (cfg.verbose)
						printf("ok, sending ACK...\n");
					/* send response */
					send_response(portfd, data_response);
				} else {
					memcpy(&data_response, &data,
					       sizeof(data));
					data_response.databytes[0] = NACK;
					//if(cfg.polling)       get_embedded_infos();
					//do_sql_things(data);
					if (cfg.verbose)
						printf("ok, sending NACK...\n");
					/* send response */
					send_response(portfd, data_response);
				}

				setzero(&data, sizeof(data));
				setzero(&data_response, sizeof(data_response));

				continue;
			}

			countbyte++;

		}

	}

	close(portfd);

}
示例#24
0
bool CHttpServer::decide(String const &method, String const &arg_uri, String const &query,
                         HeaderList const &headers, String const &body/*, IResponseSender& respSender*/ )
{
    if (verbose) RAWTRACE1("Decide what to do with uri %s", arg_uri.c_str());
    callback_t callback = registered(arg_uri);
    if (callback) {
        if (verbose) RAWTRACE1("Uri %s is registered callback, so handle it appropriately", arg_uri.c_str());

        if ( callback == rho_http_ruby_proc_callback )
            call_ruby_proc( query, body );
        else
            callback(this, query.length() ? query : body);

        return false;
    }

    String uri = arg_uri;

    String fullPath = CFilePath::join(m_root, uri);
#ifndef RHO_NO_RUBY_API    
    if (rho_ruby_is_started())
    {
        Route route;
        if (dispatch(uri, route)) {
            if (verbose) RAWTRACE1("Uri %s is correct route, so enable MVC logic", uri.c_str());
            
            VALUE req = create_request_hash(route.application, route.model, route.action, route.id,
                                            method, uri, query, headers, body);
            VALUE data = callFramework(req);
            String reply(getStringFromValue(data), getStringLenFromValue(data));
            rho_ruby_releaseValue(data);

            bool isRedirect = String_startsWith(reply, "HTTP/1.1 301") ||
                              String_startsWith(reply, "HTTP/1.1 302");

            if (!send_response(reply, isRedirect))
                return false;

            if (method == "GET")
                rho_rhodesapp_keeplastvisitedurl(uri.c_str());

		    if ( sync::RhoconnectClientManager::haveRhoconnectClientImpl() ) {

			    if (!route.id.empty()) {
				    sync::RhoconnectClientManager::rho_sync_addobjectnotify_bysrcname(route.model.c_str(), route.id.c_str());
			    }			
		    }
            
            return true;
        }
        
        if (isdir(fullPath)) {
            if (verbose) RAWTRACE1("Uri %s is directory, redirecting to index", uri.c_str());
            String q = query.empty() ? "" : "?" + query;
            
            HeaderList headers;
            headers.push_back(Header("Location", CFilePath::join( uri, "index" RHO_ERB_EXT) + q));
            
            send_response(create_response("301 Moved Permanently", headers), true);
            return false;
        }

        if (isindex(uri)) {
            if (!isfile(fullPath)) {
                if (verbose) RAWLOG_ERROR1("The file %s was not found", fullPath.c_str());
                String error = "<!DOCTYPE html><html><font size=\"+4\"><h2>404 Not Found.</h2> The file " + uri + " was not found.</font></html>";
                send_response(create_response("404 Not Found",error));
                return false;
            }
            
            if (verbose) RAWTRACE1("Uri %s is index file, call serveIndex", uri.c_str());

            VALUE req = create_request_hash(route.application, route.model, route.action, route.id,
                                            method, uri, query, headers, body);

            VALUE data = callServeIndex((char *)fullPath.c_str(), req);
            String reply(getStringFromValue(data), getStringLenFromValue(data));
            rho_ruby_releaseValue(data);

            if (!send_response(reply))
                return false;

            if (method == "GET")
                rho_rhodesapp_keeplastvisitedurl(uri.c_str());

            return true;
        }
    }
#endif
    // Try to send requested file
    if (verbose) RAWTRACE1("Uri %s should be regular file, trying to send it", uri.c_str());

    PROF_START("READ_FILE");
    bool bRes = send_file(uri, headers);
    PROF_STOP("READ_FILE");

    return bRes;
}
示例#25
0
void 
process_requests()
{
  
  float	temp_rate;
  
  if (debug)    open_debug_file();


  while (1) {
    recv_request();

    switch (netperf_request.content.request_type) {
      
    case DEBUG_ON:
      netperf_response.content.response_type = DEBUG_OK;
      /*  dump_request already present in recv_request; redundant? */
      if (!debug) {
	debug++;
	open_debug_file();
	dump_request();
      }
      send_response();
      break;
      
    case DEBUG_OFF:
      if (debug)
	debug--;
      netperf_response.content.response_type = DEBUG_OK;
      send_response();
      /* +SAF why??? */
      if (!debug) 
      {
	fclose(where);
#if !defined(WIN32) && !defined(MPE) && !defined(__VMS)
	/* For Unix: reopen the debug write file descriptor to "/dev/null" */
	/* and redirect stdout to it.					   */
	fflush (stdout);
	where = fopen ("/dev/null", "w");
	if (where == NULL)
	{
	  perror ("netserver: reopening debug fp for writing: /dev/null");
	  exit   (1);
	}
	if (close (STDOUT_FILENO) == -1)
	{
	  perror ("netserver: closing stdout file descriptor");
	  exit   (1);
	}
	if (dup (fileno (where))  == -1)
	{
	  perror ("netserver: duplicate /dev/null write file descr. to stdout");
	  exit   (1);
	}
#endif /* !WIN32 !MPE !__VMS */
      }
      break;
      
    case CPU_CALIBRATE:
      netperf_response.content.response_type = CPU_CALIBRATE;
      temp_rate = calibrate_local_cpu(0.0);
      bcopy((char *)&temp_rate,
	    (char *)netperf_response.content.test_specific_data,
	    sizeof(temp_rate));
      bcopy((char *)&lib_num_loc_cpus,
	    (char *)netperf_response.content.test_specific_data + sizeof(temp_rate),
	    sizeof(lib_num_loc_cpus));
      if (debug) {
	fprintf(where,"netserver: sending CPU information:");
	fprintf(where,"rate is %g num cpu %d\n",temp_rate,lib_num_loc_cpus);
	fflush(where);
      }
      
      /* we need the cpu_start, cpu_stop in the looper case to kill the */
      /* child proceses raj 7/95 */
      
#ifdef USE_LOOPER
      cpu_start(1);
      cpu_stop(1,&temp_rate);
#endif /* USE_LOOPER */
      
      send_response();
      break;
      
    case DO_TCP_STREAM:
      recv_tcp_stream();
      break;
      
    case DO_TCP_MAERTS:
      recv_tcp_maerts();
      break;
      
    case DO_TCP_RR:
      recv_tcp_rr();
      break;
      
    case DO_TCP_CRR:
      recv_tcp_conn_rr();
      break;
      
    case DO_TCP_CC:
      recv_tcp_cc();
      break;
      
#ifdef DO_1644
    case DO_TCP_TRR:
      recv_tcp_tran_rr();
      break;
#endif /* DO_1644 */
      
#ifdef DO_NBRR
    case DO_TCP_NBRR:
      recv_tcp_nbrr();
      break;
#endif /* DO_NBRR */
      
    case DO_UDP_STREAM:
      recv_udp_stream();
      break;
      
    case DO_UDP_RR:
      recv_udp_rr();
      break;
      
#ifdef WANT_DLPI

    case DO_DLPI_CO_RR:
      recv_dlpi_co_rr();
      break;
      
    case DO_DLPI_CL_RR:
      recv_dlpi_cl_rr();
      break;

    case DO_DLPI_CO_STREAM:
      recv_dlpi_co_stream();
      break;

    case DO_DLPI_CL_STREAM:
      recv_dlpi_cl_stream();
      break;

#endif /* WANT_DLPI */

#ifdef WANT_UNIX

    case DO_STREAM_STREAM:
      recv_stream_stream();
      break;
      
    case DO_STREAM_RR:
      recv_stream_rr();
      break;
      
    case DO_DG_STREAM:
      recv_dg_stream();
      break;
      
    case DO_DG_RR:
      recv_dg_rr();
      break;
      
#endif /* WANT_UNIX */

#ifdef WANT_XTI
    case DO_XTI_TCP_STREAM:
      recv_xti_tcp_stream();
      break;
      
    case DO_XTI_TCP_RR:
      recv_xti_tcp_rr();
      break;
      
    case DO_XTI_UDP_STREAM:
      recv_xti_udp_stream();
      break;
      
    case DO_XTI_UDP_RR:
      recv_xti_udp_rr();
      break;

#endif /* WANT_XTI */

#ifdef WANT_SCTP
    case DO_SCTP_STREAM:
      recv_sctp_stream();
      break;
      
    case DO_SCTP_STREAM_MANY:
      recv_sctp_stream_1toMany();
      break;

    case DO_SCTP_RR:
      recv_sctp_rr();
      break;

    case DO_SCTP_RR_MANY:
      recv_sctp_rr_1toMany();
      break;
#endif

#ifdef WANT_SDP
    case DO_SDP_STREAM:
      recv_sdp_stream();
      break;

    case DO_SDP_MAERTS:
      recv_sdp_maerts();
      break;

    case DO_SDP_RR:
      recv_sdp_rr();
      break;
#endif 

    default:
      fprintf(where,"unknown test number %d\n",
	      netperf_request.content.request_type);
      fflush(where);
      netperf_response.content.serv_errno=998;
      send_response();
      break;
      
    }
  }
}
示例#26
0
bool CHttpServer::send_file(String const &path, HeaderList const &hdrs)
{
    String fullPath = CFilePath::normalizePath(path);

    if (String_startsWith(fullPath,"/app/db/db-files") )
        fullPath = CFilePath::join( rho_native_rhodbpath(), path.substr(4) );
    else if (fullPath.find(m_root) != 0 && fullPath.find(m_strRhoRoot) != 0 && fullPath.find(m_strRuntimeRoot) != 0 && fullPath.find(m_userroot) != 0 && fullPath.find(m_strRhoUserRoot) != 0)
        fullPath = CFilePath::join( m_root, path );
	
    struct stat st;
    bool bCheckExist = true;
#ifdef RHODES_EMULATOR
    String strPlatform = RHOSIMCONF().getString("platform");
    if ( strPlatform.length() > 0 )
    {
        String fullPath1 = fullPath;
        int nDot = fullPath1.rfind('.');
        if ( nDot >= 0 )
            fullPath1.insert(nDot, String(".") + strPlatform);
        else
            fullPath1 += String(".") + strPlatform;

        if (stat(fullPath1.c_str(), &st) == 0 && S_ISREG(st.st_mode))
        {
            fullPath = fullPath1;
            bCheckExist = false;
        }
    }

#endif

    bool doesNotExists = bCheckExist && (stat(fullPath.c_str(), &st) != 0 || !S_ISREG(st.st_mode));
    if ( doesNotExists ) {
        // looking for files at 'rho/apps' at runtime folder
        fullPath = CFilePath::join( m_strRuntimeRoot, path );
    }

    if (verbose) RAWTRACE1("Sending file %s...", fullPath.c_str());

    if ( doesNotExists ) {
        if ( stat(fullPath.c_str(), &st) != 0 || !S_ISREG(st.st_mode) ) {
            doesNotExists = true;
        }else
            doesNotExists = false;
    }

#ifdef RHODES_EMULATOR
    if ( doesNotExists )
    {
        CTokenizer oTokenizer( RHOSIMCONF().getString("ext_path"), ";" );
	    while (oTokenizer.hasMoreTokens()) 
        {
		    String tok = oTokenizer.nextToken();
		    tok = String_trim(tok);
            
            String fullPath1 = CFilePath::join( tok, path );
            if (stat(fullPath1.c_str(), &st) == 0 && S_ISREG(st.st_mode))
            {
                fullPath = fullPath1;
                doesNotExists = false;
                break;
            }

        }
    }
#endif

    if ( doesNotExists ) {
        if (verbose) RAWLOG_ERROR1("The file %s was not found", path.c_str());
        String error = "<!DOCTYPE html><html><font size=\"+4\"><h2>404 Not Found.</h2> The file " + path + " was not found.</font></html>";
        send_response(create_response("404 Not Found",error));
        return false;
    }

    PROF_START("LOW_FILE");
    FILE *fp = fopen(fullPath.c_str(), "rb");
    PROF_STOP("LOW_FILE");
    if (!fp) {
        if (verbose) RAWLOG_ERROR1("The file %s could not be opened", path.c_str());
        String error = "<!DOCTYPE html><html><font size=\"+4\"><h2>404 Not Found.</h2> The file " + path + " could not be opened.</font></html";
        send_response(create_response("404 Not Found",error));
        return false;
    }
    
    HeaderList headers;
    
    // Detect mime type
    headers.push_back(Header("Content-Type", get_mime_type(path)));
    if ( String_startsWith(path, "/public") )
    {
        headers.push_back(Header("Expires", "Thu, 15 Apr 2020 20:00:00 GMT") );
        headers.push_back(Header("Cache-Control", "max-age=2592000") );
    }

    // Content length
    char* buf = new char[FILE_BUF_SIZE];
    
    String start_line;
    
    size_t file_size = st.st_size;
    size_t range_begin = 0, range_end = file_size - 1;
    size_t content_size = file_size;
    if (parse_range(hdrs, &range_begin, &range_end))
    {
        if (range_end >= file_size)
            range_end = file_size - 1;
        if (range_begin >= range_end)
            range_begin = range_end - 1;
        content_size = range_end - range_begin + 1;
        
        if (fseek(fp, range_begin, SEEK_SET) == -1) {
            RAWLOG_ERROR1("Can not seek to specified range start: %lu", (unsigned long)range_begin);
			snprintf(buf, FILE_BUF_SIZE, "bytes */%lu", (unsigned long)file_size);
			headers.push_back(Header("Content-Range", buf));
			send_response(create_response("416 Request Range Not Satisfiable",headers));
            fclose(fp);
            delete[] buf;
            return false;
        }
		
		snprintf(buf, FILE_BUF_SIZE, "bytes %lu-%lu/%lu", (unsigned long)range_begin,
                 (unsigned long)range_end, (unsigned long)file_size);
        headers.push_back(Header("Content-Range", buf));
        
        start_line = "206 Partial Content";
    }
    else {
        start_line = "200 OK";
    }

    
    snprintf(buf, FILE_BUF_SIZE, "%lu", (unsigned long)content_size);
    headers.push_back(Header("Content-Length", buf));
    
    // Send headers
    if (!send_response(create_response(start_line, headers))) {
        if (verbose) RAWLOG_ERROR1("Can not send headers while sending file %s", path.c_str());
        fclose(fp);
        delete[] buf;
        return false;
    }
    
    // Send body
    for (size_t start = range_begin; start < range_end + 1;) {
        size_t need_to_read = range_end - start + 1;
        if (need_to_read == 0)
            break;
        
        if (need_to_read > FILE_BUF_SIZE)
            need_to_read = FILE_BUF_SIZE;

PROF_START("LOW_FILE");
        size_t n = fread(buf, 1, need_to_read, fp);//fread(buf, 1, need_to_read, fp);
PROF_STOP("LOW_FILE");
        if (n < need_to_read) {
			if (ferror(fp) ) {
				if (verbose) RAWLOG_ERROR2("Can not read part of file (at position %lu): %s", (unsigned long)start, strerror(errno));
			} else if ( feof(fp) ) {
				if (verbose) RAWLOG_ERROR1("End of file reached, but we expect data (%lu bytes)", (unsigned long)need_to_read);
			}
            fclose(fp);
            delete[] buf;
            return false;
        }
        
        start += n;
        
        if (!send_response_body(String(buf, n))) {
            if (verbose) RAWLOG_ERROR1("Can not send part of data while sending file %s", path.c_str());
            fclose(fp);
            delete[] buf;
            return false;
        }
    }

PROF_START("LOW_FILE");
    fclose(fp);
PROF_STOP("LOW_FILE");
    delete[] buf;
    if (verbose) RAWTRACE1("File %s was sent successfully", path.c_str());
    return false;
}
示例#27
0
int main (int argc, char *argv[]){
	int sock, newsock;
	struct sockaddr_storage client_addr;
	socklen_t sin_size;
	char s[INET6_ADDRSTRLEN];
	RSA *decrypt, *sign;
        decrypt = NULL;
        sign    = NULL;

	int retval = SIBYL_SUCCESS;

        char *dir  = NULL;
        char *ip   = NULL;
        char *port = NULL;
        char *decr_namefile = NULL;
        char *sign_namefile = NULL;

        dir  = (char *)calloc(_POSIX_PATH_MAX + 1, sizeof(char));
        ip   = (char *)calloc(17 + 1, sizeof(char));
        port = (char *)calloc(10, sizeof(char));
        decr_namefile = (char *)calloc(_POSIX_PATH_MAX + 1, sizeof(char));
        sign_namefile = (char *)calloc(_POSIX_PATH_MAX + 1, sizeof(char));

        if(dir == NULL || ip == NULL || port == NULL ||
           decr_namefile == NULL || sign_namefile == NULL){
                D("Malloc");
                retval = SIBYL_OSERR;
                goto FREE;
        }

        strncpy(dir, SIBYL_DIR, _POSIX_PATH_MAX);
        strncpy(port, SIBYL_PORT, 9);
        strncpy(decr_namefile, SIBYL_DECR_KEY, _POSIX_PATH_MAX);
        strncpy(sign_namefile, SIBYL_SIGN_KEY, _POSIX_PATH_MAX);

	/* Read options */
	int c;
	while((c = getopt(argc, argv, SIBYL_SRV_OPTS)) != -1){
                if(optarg == NULL)
                        c = 'h';
		switch(c){
			case 'd':
                                strncpy(decr_namefile, 
                                        optarg,
                                        _POSIX_PATH_MAX);
				break;
			case 's':
                                strncpy(sign_namefile,
                                        optarg,
                                        _POSIX_PATH_MAX);
				break;
			case 'p':
                                strncpy(port,
                                        optarg,
                                        9);
				break;
			case 'i':
                                strncpy(ip,
                                        optarg,
                                        _POSIX_PATH_MAX);
				break;
			case 'D':
                                strncpy(dir,
                                        optarg,
                                        _POSIX_PATH_MAX);
				break;
			case 'h':
			default:
				printf("Usage: %s -d decrypt -s sign -i IP -p port -D dir\n"
				       "  -d decrypt: decrypt private key (default: decrypt)\n"
				       "  -s sign: sign private key (default: sign)\n"
				       "  -i IP: IP where the server will listen (default: localhost)\n"
				       "  -p port: port where the server will listen (default: 9999)\n"
				       "  -D dir: directory where the private keys are stored "
				       "(default: /etc/sibyl)\n"
				       "  -h: shows this help text\n", argv[0]);
				exit(1);
		}
	}

	/* Read private keys */
	retval = read_keys(&decrypt,
			   decr_namefile,
			   &sign,
			   sign_namefile,
			   dir);
	if(retval != SIBYL_SUCCESS)
                goto FREE;
        D("Private keys read");

	/* Start server */
	retval = start_server(&sock,
			      ip,
			      port);
	if(retval != SIBYL_SUCCESS){
                goto FREE;
	}
        D("Server started\n");

	while(1){
		/* Accept connection */
		sin_size = sizeof client_addr;
		newsock = accept(sock, 
                                 (struct sockaddr *)&client_addr, 
                                 &sin_size);
		if (newsock == -1){
			perror("server: accept");
			continue;
		}

		inet_ntop(client_addr.ss_family,
			  get_in_addr((struct sockaddr *)&client_addr), 
                          s, 
                          sizeof(s));
		D1("server: got connection from %s\n", s);

		if (!fork()){ // child process
			close(sock); // child doesn't need the listener
			char *strnonce = NULL;
			char *msg      = NULL;
                        char command   = 0;
			char *token[3] = {NULL,NULL,NULL};
			char *p1_data     = NULL;
                        char *p2_data     = NULL;
                        char *auth_result = NULL;

			/* Send the nonce */
			strnonce = (char *) calloc(32, sizeof(char));
                        if (strnonce == NULL){
                                D("Malloc");
                                retval = SIBYL_OSERR;
                                goto ENDCHILD;
                        }

			retval = send_nonce(newsock, strnonce);
			if (retval != SIBYL_SUCCESS){
                                goto ENDCHILD;
			}

			/* Receive the client's message and parse it */
			msg = (char *) calloc(SIBYL_MAX_MSG, sizeof(char));
			if(msg == NULL){
                                D("Malloc");
                                retval = SIBYL_OSERR;
                                goto ENDCHILD;
			}
			retval = receive_msg(msg,
					     newsock,
                                             &command,
					     token);
			if (retval != SIBYL_SUCCESS){
                                goto ENDCHILD;
			}

        		D1("Received: [%s]\n", msg);
                        D1("command: [%c]\n", command);
			D1("m : %s\n", token[0]);
			D1("p1 : %s\n", token[1]);
			D1("p2 : %s\n", token[2]);

                        /* 
                         * Now there are several actions depending on the command
                         * which is stored in command.
                         */

                        /* Just send the public keys */
                        if(command == '-'){
                                retval = send_public_keys(dir,
                                                          decr_namefile,
                                                          sign_namefile,
                                                          newsock);
                                goto ENDCHILD;
                        }
                        
                        /* Any other command requires decryption of p1 */
			/* Decrypt p1 (p1 = token[1]) */
                        /* p1_data always includes a trailing 0 */
                        p1_data = (char *)calloc(RSA_size(decrypt) + 1, 
                                                 sizeof(u_char));
                        if(p1_data == NULL){
                                D("Malloc strnonce");
                                retval = SIBYL_OSERR;
                                goto ENDCHILD;
                        }


                        D1("token[1]:{%s}\n", token[1]);
                        /* this is path */
                        char *resp = (char *)calloc(SIBYL_MAX_MSG,
                                                    sizeof(u_char));
                        memcpy(resp, token[1], strlen(token[1]));
			retval = decrypt_token(p1_data,
                                               command,
					       resp,
					       decrypt);
			if (retval != SIBYL_SUCCESS){
                                printf("Decryption error\n");
                                goto ENDCHILD;
			}

			D1("p1_data: %s\n", p1_data);

                        /* 
                         * If command != \000 then it is '0' <= command <='9'
                         * and translation is asked for.
                         */
                        D1("token[0]:{%s}\n", token[0]);
                        if(command != 0){
                                if(strncmp(strnonce, 
                                           token[0], 
                                           strlen(strnonce))){
                                        D("Wrong nonce");
                                        retval = SIBYL_NONCE_ERROR;
                                        goto ENDCHILD;
                                }
                                retval = translate_and_send(p1_data,
                                                            command,
                                                            decr_namefile,
                                                            dir,
                                                            newsock,
                                                            sign);
                                goto ENDCHILD;
                        }

			/* 
                         * Decrypt p2 (p2 = token[2]):
                         * only if command == verify
                         */
                        p2_data = (char *)calloc(RSA_size(decrypt) + 1, 
                                                 sizeof(u_char));
                        if(p2_data == NULL){
                                perror("Unable to allocate memory for p2_data");
                                retval = SIBYL_OSERR;
                                goto ENDCHILD;
                        }

			retval = decrypt_token(p2_data,
                                               command,
					       token[2],
					       decrypt);
			if (retval != SIBYL_SUCCESS){
                                goto ENDCHILD;
			}

			D1("p2_data: %s\n", p2_data);

			/* Is the password correct */
                        auth_result = calloc(1, sizeof(char));
			if(auth_result == NULL){
				D("Unable to allocate memory for auth_result");
                                retval = SIBYL_OSERR;
                                goto ENDCHILD;
			}
			retval = is_pwd_ok(p1_data,
					   p2_data,
					   auth_result,
					   strnonce);
			if (retval != SIBYL_SUCCESS){
                                goto ENDCHILD;
			}

			/* Send the response to the client */

			retval = send_response(&newsock,
					       token,
					       auth_result,
					       sign);
			if (retval != SIBYL_SUCCESS){
                                goto ENDCHILD;
			}

                ENDCHILD:
                        free(strnonce);
                        free(msg);
                        free(p1_data);
                        free(p2_data);
                        free(auth_result);

			/* Close socket */
			close(newsock);
                        retval = SIBYL_SUCCESS;
                        goto FREE;
		}
		close(newsock); // parent doesn't need this
	}

FREE:

        RSA_free(decrypt);
        RSA_free(sign);
        free(dir);
        free(ip);
        free(port);
        free(decr_namefile);
        free(sign_namefile);
	exit(retval);
}
示例#28
0
static svn_error_t *
do_resources(const dav_svn_repos *repos,
             svn_fs_root_t *root,
             svn_revnum_t revision,
             ap_filter_t *output,
             apr_bucket_brigade *bb,
             apr_pool_t *pool)
{
  apr_hash_t *changes;
  apr_hash_t *sent = apr_hash_make(pool);
  apr_hash_index_t *hi;
  apr_pool_t *subpool = svn_pool_create(pool);

  /* Fetch the paths changed in this revision.  This will contain
     everything except otherwise-unchanged parent directories of added
     and deleted things.  Also, note that deleted things don't merit
     responses of their own -- they are considered modifications to
     their parent.  */
  SVN_ERR(svn_fs_paths_changed2(&changes, root, pool));

  for (hi = apr_hash_first(pool, changes); hi; hi = apr_hash_next(hi))
    {
      const void *key;
      void *val;
      const char *path;
      svn_fs_path_change2_t *change;
      svn_boolean_t send_self;
      svn_boolean_t send_parent;

      svn_pool_clear(subpool);
      apr_hash_this(hi, &key, NULL, &val);
      path = key;
      change = val;

      /* Figure out who needs to get sent. */
      switch (change->change_kind)
        {
        case svn_fs_path_change_delete:
          send_self = FALSE;
          send_parent = TRUE;
          break;

        case svn_fs_path_change_add:
        case svn_fs_path_change_replace:
          send_self = TRUE;
          send_parent = TRUE;
          break;

        case svn_fs_path_change_modify:
        default:
          send_self = TRUE;
          send_parent = FALSE;
          break;
        }

      if (send_self)
        {
          /* If we haven't already sent this path, send it (and then
             remember that we sent it). */
          if (! apr_hash_get(sent, path, APR_HASH_KEY_STRING))
            {
              svn_node_kind_t kind;
              SVN_ERR(svn_fs_check_path(&kind, root, path, subpool));
              SVN_ERR(send_response(repos, root, path,
                                    kind == svn_node_dir,
                                    output, bb, subpool));
              apr_hash_set(sent, path, APR_HASH_KEY_STRING, (void *)1);
            }
        }
      if (send_parent)
        {
          /* If it hasn't already been sent, send the parent directory
             (and then remember that you sent it).  Allocate parent in
             pool, not subpool, because it stays in the sent hash
             afterwards. */
          const char *parent = svn_path_dirname(path, pool);
          if (! apr_hash_get(sent, parent, APR_HASH_KEY_STRING))
            {
              SVN_ERR(send_response(repos, root, parent,
                                    TRUE, output, bb, subpool));
              apr_hash_set(sent, parent, APR_HASH_KEY_STRING, (void *)1);
            }
        }
    }

  svn_pool_destroy(subpool);

  return SVN_NO_ERROR;
}
示例#29
0
文件: wurfld.c 项目: passani/wurfld
void *worker(void *priv) {
    wurfld_connection_context *ctx = (wurfld_connection_context *)priv;

    DEBUG1("Worker %p started on fd %d", pthread_self(), ctx->fd);

    // we don't need to receive anything anymore on this fd
    int err = shutdown(ctx->fd, SHUT_RD);
    if (err != 0)
        NOTICE("Can't shutdown the receive part of fd %d : %s", ctx->fd, strerror(errno));

    int opts = fcntl(ctx->fd, F_GETFL);
    if (opts >= 0) {
        err = fcntl(ctx->fd, F_SETFL, opts & (~O_NONBLOCK));
        if (err != 0)
            NOTICE("Can't set blocking mode on fd %d : %s", ctx->fd, strerror(errno));
    } else {
        ERROR("Can't get flags on fd %d : %s", ctx->fd, strerror(errno));
    }

    char *useragent = NULL;
    fbuf_trim(ctx->input);

    // parse the request 
    char *request_data = fbuf_data(ctx->input);
    struct sockaddr_in peer;
    socklen_t socklen = sizeof(struct sockaddr);
    getpeername(ctx->fd, (struct sockaddr *)&peer, &socklen);
    if (use_http && strncmp(request_data, "GET /lookup/", 12) == 0) {
        char *reqline_start = fbuf_data(ctx->input) + 12;
        char *reqline_end = reqline_start;

        while (*reqline_end != '\r' && *reqline_end != '\n')
            reqline_end++;
        reqline_end++;

        char reqline[reqline_end-reqline_start];
        snprintf(reqline, reqline_end-reqline_start, "%s", reqline_start);

        char *httpv = strstr(reqline, " HTTP/1");
        if (httpv) {
            *httpv = 0;
            httpv++;
            ctx->is_http10 = (strncmp(httpv, "HTTP/1.0", 8) == 0);
        }
        useragent = unescape_uri_request(reqline);
    } else if (!use_http) {
        useragent = strdup(fbuf_data(ctx->input));
    }

    if (useragent) {
        NOTICE("(%p) Lookup request from %s: %s", pthread_self(), inet_ntoa(peer.sin_addr), useragent);
        ctx->useragent = useragent;
        send_response(ctx);
    } else if (use_http) {
        NOTICE("(%p) Unsupported Request from %s: %s", pthread_self(), inet_ntoa(peer.sin_addr), request_data);
        char response[2048];

        snprintf(response, sizeof(response),
                 "%s 400 NOT SUPPORTED\r\n"
                 "Content-Type: text/plain\r\n"
                 "Content-Length: 17\r\n\r\n"
                 "400 NOT SUPPORTED",
                 ctx->is_http10 ? "HTTP/1.0" : "HTTP/1.1");

        if (write_socket(ctx->fd, response, strlen(response)) != 0) {
            ERROR("Worker %p failed writing reponse: %s", pthread_self(), strerror(errno));
        }
    }
    DEBUG1("Worker %p finished on fd %d", pthread_self(), ctx->fd);
    shutdown(ctx->fd, SHUT_RDWR);
    close(ctx->fd);
    fbuf_free(ctx->input);
    fbuf_free(ctx->output);
    free(ctx->useragent); 
    free(ctx);
    return NULL;
}
示例#30
0
/**
 * The sstCheckMin() script command handler. Return 1 (true) if the
 * MIN-SE: of the message is too small compared to the sst_min_se
 * value. This will allow the script to reply to this INVITE with a
 * "422 Session Timer Too Small" response. if sst_min_se was never set
 * the recommended value of 1800 seconds will be used.
 *
 * If the flag (str1) is set to 1, the 422 reply will be sent with the
 * sst MIN_SE value in the header. If the flag is not set or is NULL,
 * no reply is sent.

 * @param msg  - The sip message from the script (INVITE only)
 * @param flag - Reply mode Flag. 0/NULL do not send reply, 1 send 422
 *               reply if Session-Expires is to small with the MIN-SE
 *               header in the reply
 * @param str2 - Not used.
 *
 * @return 1 if the MIN-SE is too small, -1 if it is OK, or It could
 *         not be checked.
 *
 * NOTE: returning 0 == drop message, 1 == true, -1 == false in the
 *       script.
 */
int sst_check_min(struct sip_msg *msg, char *flag, char *str2)
{
	enum parse_sst_result result;
	struct session_expires se = {0,0};
	unsigned minse = 0;

	/*
	 * Only look in INVITES. We can't reply with a 422 to a 2xx reply
	 * now can we. This check can ONLY be done on the INVITE/UPDATE.
	 */
	if (msg->first_line.type == SIP_REQUEST &&
			msg->first_line.u.request.method_value == METHOD_INVITE) {
		/*
		 * First see if there is an Session-Expires: header.  If there
		 * is, also look for a MIN-SE: header. If there is, use the
		 * minimum value of the two to compare with srt1. All MUST not
		 * be less then 90 and 1800 is recomended. See RCF section 4.
		 */
		if ((result = parse_session_expires(msg, &se)) != parse_sst_success) {
			if (result != parse_sst_header_not_found) {
				LM_ERR("failed to parse Session-Expires headers.\n");
				return 0; /* Error drop the message */
			}
			/* Session-Expires not supported/stated */
			LM_DBG("No Session-Expires header found. retuning false (-1)\n");
			/*
			 * NOTE: 0 == drop message, 1 == true, -1 == false
			 */
			return -1;
		}

		/*
		 * We have a Session_expire header. Now look for the MIN-SE.
		 */
		if ((result = parse_min_se(msg, &minse)) != parse_sst_success) {
			if (result != parse_sst_header_not_found) {
				/*
				 * This is an error. The header was found but could
				 * not parse it.
				 */
				LM_ERR("failed to parse MIN-SE header.\n");
				return -1;
			}
			/*
			 * If not stated, use the value from the session-expires
			 * header
			 */
			LM_DBG("No MIN-SE header found.\n");
			minse = 90 /*this is the recommended value*/ /*se.interval*/;
		}

		LM_DBG("Session-Expires: %d; MIN-SE: %d\n",	se.interval, minse);

		/*
		 * Now compare our MIN-SE with the messages and see if it is
		 * too small. We will take the smaller of the messages
		 * Session-expires and min-se if stated.
		 */
		if (sst_min_se > MIN(minse, se.interval)) {
			/*
			 * Too small. See if we need to send the 422 and are able
			 * to send it.
			 */
			if (flag) {
				char minse_hdr[3+1+2+1+1+11+CRLF_LEN+2+1];
				int hdr_len = 3+1+2+1+1+11+CRLF_LEN+2;
				memset(minse_hdr, 0, hdr_len+1);
				hdr_len = snprintf(minse_hdr, hdr_len,
					"%s%d%s", "MIN-SE: ", sst_min_se,CRLF);
				LM_DBG("Sending 422: %.*s\n", hdr_len, minse_hdr);
				if (send_response(msg, 422, &sst_422_rpl, minse_hdr, hdr_len)){
					LM_ERR("Error sending 422 reply.\n");
				}
			}
			LM_DBG("Done returning true (1)\n");
			return 1; /* return true */
		}
	}
	LM_DBG("Done returning false (-1)\n");
	/*
	 * All is good.
	 */
	return -1; /* return false */
}