Ejemplo n.º 1
0
Archivo: opend.c Proyecto: clamxyz/apue
void request(char *buf, int nread, int fd)
{
	int newfd;

	if (buf[nread-1] != 0)
	{
		sprintf(errmsg, "request not null terminated:%*.*s\n", nread, nread, buf);
		send_err(fd, -1, errmsg);
		return;
	}

	if (buf_args(buf, cli_args) < 0) {
		send_err(fd, -1, errmsg);
		return;
	}

	if ( (newfd = open(pathname, oflag)) < 0)
	{
		sprintf(errmsg, "can't open %s: %s\n", pathname, strerror(errno));
		send_err(fd, -1, errmsg);
		return;
	}
	
	if (send_fd(fd, newfd) < 0)
		err_sys("send_fd error", errno);
	close(newfd);	
}
Ejemplo n.º 2
0
void handle_request(char *buf, int nread, int fd)
{
	int	newfd;

	if (buf[nread - 1] != 0) {
		/*
		 * "%*.*s", m, n, "string"
		 * total field width is m
		 * precision is n.
		 * this manner can limit print max(m, n) chars up to 
		 * max(n, m)
		 */
		snprintf(errmsg, MAXLINE - 1,
				"request not null terminated: %*.*s\n",
				nread, nread, buf);
		send_err(fd, -1, errmsg);
		return;
	}
	if (buf_args(buf, cli_args) < 0) { /* parse args & set options */
		send_err(fd, -1, errmsg);
		return;
	}
	if ((newfd = open(pathname, oflag)) < 0) {
		snprintf(errmsg, MAXLINE - 1, "can't open %s: %s\n", pathname,
				strerror(errno));
		send_err(fd, -1, errmsg);
		return;
	}
	if (send_fd(fd, newfd) < 0) /* send the descriptor */
		err_sys("send_fd error");
	close(newfd); /* we're done with descriptor */
}
Ejemplo n.º 3
0
void handle_request(char *buf, int nread, int clifd, uid_t uid)
{
	int	newfd;

	if (buf[nread - 1] != 0) {
		snprintf(errmsg, MAXLINE - 1,
				"request from uid %d not null terminated: %*.*s\n",
				uid, nread, nread, buf);
		send_err(clifd, -1, errmsg);
		return;
	}
	log_msg("request: %s, from uid %d", buf, uid);
	/* parse the arguments, set options */
	if (buf_args(buf, cli_args) < 0) {
		send_err(clifd, -1, errmsg);
		log_msg(errmsg);
		return;
	}

	if ((newfd = open(pathname, oflag)) < 0) {
		snprintf(errmsg, MAXLINE - 1, "can't open %s: %s\n",
				pathname, strerror(errno));
		send_err(clifd, -1, errmsg);
		log_msg(errmsg);
		return;
	}

	/* send the desrciptor */
	if (send_fd(clifd, newfd) < 0)
		log_sys("send_fd error");
	log_msg("send fd %d over fd %d for %s", newfd, clifd, pathname);
	close(newfd);	/* we're done with desrciptor */
}
Ejemplo n.º 4
0
static void get_var(nut_ctype_t *client, const char *upsname, const char *var)
{
	const	upstype_t	*ups;
	const	char	*val;

	/* ignore upsname for server.* variables */
	if (!strncasecmp(var, "server.", 7)) {
		get_var_server(client, upsname, var);
		return;
	}

	ups = get_ups_ptr(upsname);

	if (!ups) {
		send_err(client, NUT_ERR_UNKNOWN_UPS);
		return;
	}

	if (!ups_available(ups, client))
		return;

	val = sstate_getinfo(ups, var);

	if (!val) {
		send_err(client, NUT_ERR_VAR_NOT_SUPPORTED);
		return;
	}

	/* handle special case for status */
	if ((!strcasecmp(var, "ups.status")) && (ups->fsd))
		sendback(client, "VAR %s %s \"FSD %s\"\n", upsname, var, val);
	else
		sendback(client, "VAR %s %s \"%s\"\n", upsname, var, val);
}
Ejemplo n.º 5
0
void
handle_request(char *buf, int nread, int fd)
{
	int		newfd;

	if (buf[nread-1] != 0) {
		snprintf(errmsg, MAXLINE-1,
		  "request not null terminated: %*.*s\n", nread, nread, buf);
		send_err(fd, -1, errmsg);
		return;
	}
	if (buf_args(buf, cli_args) < 0) {	/* parse args & set options */
		send_err(fd, -1, errmsg);
		return;
	}
	if ((newfd = open(pathname, oflag)) < 0) {
		snprintf(errmsg, MAXLINE-1, "can't open %s: %s\n", pathname,
		  strerror(errno));
		send_err(fd, -1, errmsg);
		return;
	}
	if (send_fd(fd, newfd) < 0)		/* send the descriptor */
		err_sys("send_fd error");
	close(newfd);		/* we're done with descriptor */
}
Ejemplo n.º 6
0
void
handle_request(char *buf, int nread, int fd)
{
	int		newfd;

	if (buf[nread-1] != 0) {
		snprintf(errmsg, MAXLINE-1,
		  "request not null terminated: %*.*s\n", nread, nread, buf);
		send_err(fd, -1, errmsg);
		return;
	}
	if (buf_args(buf, cli_args) < 0) {	/* 将客户进程请求分解成标准argv型的参数表,调用cli_args处理客户进程的参数*/
		send_err(fd, -1, errmsg);
		return;
	}
	if ((newfd = open(pathname, oflag)) < 0) { // 打开相应文件
		snprintf(errmsg, MAXLINE-1, "can't open %s: %s\n", pathname,
		  strerror(errno));
		send_err(fd, -1, errmsg);
		return;
	}
	if (send_fd(fd, newfd) < 0)		/* 经由fd管道将描述符回送给客户进程*/
		err_sys("send_fd error");
	close(newfd);		/* we're done with descriptor */
}
Ejemplo n.º 7
0
int main(int argc, char ** argv) {
	shm_network_init();

	while(1) {
		/* Listen for requests and handle them */
		switch(shm_cmd[0]) {
			case SHM_CMD_NEW_SERVER: {
				/*
				 * get_packet_ptr is expected to return the start of the string
				 * that must be passed in while communicating with this process.
				 */
				shm_t * new_server = shm_connect(SHM_DEV_SERVER, get_packet_ptr(shm_cmd), get_packet_ptr(shm_cmd));
				if(SHM_IS_ERR(new_server)) {
					/* The server creation failed. Send error to whoever requested the server */
					send_err(new_server);
				} else {
					/* The server is good */
					send_confirmation(new_server, sizeof(shm_t));
				}
				break;
			}
			case SHM_CMD_NEW_CLIENT: {
				shm_id_unique_t * clientname = (shm_id_unique_t *)get_packet_ptr(shm_cmd);
				shm_t * new_client = shm_connect(SHM_DEV_CLIENT, clientname->server_id, clientname->unique_id);
				if(SHM_IS_ERR(new_client)) {
					/* The client creation failed. Send error to whoever requested the client */
					send_err(new_client);
				} else {
					/* The client is good */
					send_confirmation(new_client, sizeof(shm_t));
				}
				break;
			}
			case SHM_CMD_DESTROY_SERVER:
				shm_disconnect((shm_t*)get_packet_ptr(shm_cmd));
				shm_ack(NULL, 0);
				break;
			case SHM_CMD_DESTROY_CLIENT:
				shm_disconnect((shm_t*)get_packet_ptr(shm_cmd));
				shm_ack(NULL, 0);
				break;
			case SHM_CMD_SEND:
				/* Send packet directly from client/server to device (server or client): */
				shm_send_to_device((shm_packet_t*)get_packet_ptr(shm_cmd));
				break;
			case 0: /* No requests being done */
			default:
				/* Clear out cmd flag */
				shm_ack(NULL, 0);
		}
		thread_sleep();
	}

	shm_network_stopall();
	return 0; /* The shared memory manager should never return */
}
Ejemplo n.º 8
0
Archivo: netget.c Proyecto: AlexLov/nut
void net_get(nut_ctype_t *client, int numarg, const char **arg)
{
	if (numarg < 2) {
		send_err(client, NUT_ERR_INVALID_ARGUMENT);
		return;
	}

	/* GET NUMLOGINS UPS */
	if (!strcasecmp(arg[0], "NUMLOGINS")) {
		get_numlogins(client, arg[1]);
		return;
	}

	/* GET UPSDESC UPS */
	if (!strcasecmp(arg[0], "UPSDESC")) {
		get_upsdesc(client, arg[1]);
		return;
	}

	if (numarg < 3) {
		send_err(client, NUT_ERR_INVALID_ARGUMENT);
		return;
	}

	/* GET VAR UPS VARNAME */
	if (!strcasecmp(arg[0], "VAR")) {
		get_var(client, arg[1], arg[2]);
		return;
	}

	/* GET TYPE UPS VARNAME */
	if (!strcasecmp(arg[0], "TYPE")) {
		get_type(client, arg[1], arg[2]);
		return;
	}

	/* GET DESC UPS VARNAME */
	if (!strcasecmp(arg[0], "DESC")) {
		get_desc(client, arg[1], arg[2]);
		return;
	}

	/* GET CMDDESC UPS CMDNAME */
	if (!strcasecmp(arg[0], "CMDDESC")) {
		get_cmddesc(client, arg[1], arg[2]);
		return;
	}

	send_err(client, NUT_ERR_INVALID_ARGUMENT);
	return;
}
Ejemplo n.º 9
0
Archivo: port.c Proyecto: migadu/gmimex
int main(void) {
    int bytes_read;
    gchar buffer[MAX_BUFFER_SIZE];
    JSON_Value *root_value;
    JSON_Object *root_object;
    gchar *json_str;
    gchar *func_name;
    gchar *path;

    while((bytes_read = read_msg(buffer)) > 0) {
    	json_str = g_strndup((const gchar *)buffer, bytes_read);
    	root_value = json_parse_string(json_str);
    	root_object = json_value_get_object(root_value);
    	func_name = (gchar *)json_object_get_string(root_object, "exec");
    	path = (gchar *)json_object_get_string(root_object, "path");
			GString *json_message = NULL;

    	if (!g_ascii_strcasecmp(func_name, "get_preview_json")) {
				json_message = gmimex_get_json(path, JSON_NO_MESSAGE_CONTENT);
  			if (!json_message) {
  				send_err();
  			} else {
					send_msg((gchar *)json_message->str, json_message->len);
			  	g_string_free(json_message, TRUE);
			  }
    	} else if (!g_ascii_strcasecmp(func_name, "get_json")) {
  			gboolean raw = json_object_get_boolean(root_object, "raw");
  			json_message = gmimex_get_json(path, (raw ? JSON_RAW_MESSAGE_CONTENT : JSON_PREPARED_MESSAGE_CONTENT));
  			if (!json_message) {
  				send_err();
  			} else {
					send_msg((gchar *)json_message->str, json_message->len);
			  	g_string_free(json_message, TRUE);
			  }
    	} else if (!g_ascii_strcasecmp(func_name, "get_part")) {
    		int part_id = json_object_get_number(root_object, "partId");
			  GByteArray *part_content = gmimex_get_part(path, part_id);
			  if (!part_content) {
			  	send_err();
			  } else {
    			send_msg((gchar *)part_content->data, part_content->len);
    			g_byte_array_free(part_content, TRUE);
    		}
    	}
    	json_value_free(root_value);
    	g_free(json_str);
    }
    return 0;
}
Ejemplo n.º 10
0
void handle_request(char *buf, int nread, int clifd, uid_t uid)
{
    char *errmsg = NULL;
    errmsg = malloc(MAXLENLINE * sizeof(char));
    memset(errmsg, 0, MAXLENLINE);

    int     newfd;
    if (buf[nread-1] != 0)
    {
        snprintf(errmsg, MAXLENLINE-1,
                "request from uid %d not null terminated: %*.*s\n",
                uid, nread, nread, buf);
        send_err(clifd, -1, errmsg);
        return;
    }
    //log_msg("request: %s, from uid %d", buf,uid);

    client_args *cli_args = NULL;
    if (parse_args(buf, &cli_args) < 0)
    {
        send_err(clifd, -1, errmsg);
        //log_msg(errmsg);
        return;
    }

    open_fd *op_fd = NULL;
    if (get_cli_args(cli_args, &op_fd) < 0)
    {
        send_err(clifd, -1, errmsg);
        //log_msg(errmsg);
        return;
    }

    if ((newfd = open(op_fd->path, op_fd->oflag)) < 0)
    {
        snprintf(errmsg, MAXLENLINE-1, "can't open %s: %s\n", op_fd->path,strerror(errno));
        send_err(clifd, -1, errmsg);
        //log_msg(errmsg);
        return;
    }

    if (send_fd(clifd, newfd) < 0)
    {
        //log_sys("send_fd error");
    }
    //log_msg("send fd %d over fd %d for %s", newfd, clifd, op_fd->path);
    close(newfd);
}
Ejemplo n.º 11
0
Archivo: netget.c Proyecto: AlexLov/nut
static void get_type(nut_ctype_t *client, const char *upsname, const char *var)
{
	char	buf[SMALLBUF];
	const	upstype_t	*ups;
	const	st_tree_t	*node;

	ups = get_ups_ptr(upsname);

	if (!ups) {
		send_err(client, NUT_ERR_UNKNOWN_UPS);
		return;
	}

	if (!ups_available(ups, client))
		return;

	node = sstate_getnode(ups, var);

	if (!node) {
		send_err(client, NUT_ERR_VAR_NOT_SUPPORTED);
		return;
	}

	snprintf(buf, sizeof(buf), "TYPE %s %s", upsname, var);

	if (node->flags & ST_FLAG_RW)
		snprintfcat(buf, sizeof(buf), " RW");

	if (node->enum_list) {
		sendback(client, "%s ENUM\n", buf);
		return;
	}

	if (node->range_list) {
		sendback(client, "%s RANGE\n", buf);
		return;
	}

	if (node->flags & ST_FLAG_STRING) {
		sendback(client, "%s STRING:%d\n", buf, node->aux);
		return;
	}

	/* hmm... */

	sendback(client, "TYPE %s %s UNKNOWN\n", upsname, var);
}		
Ejemplo n.º 12
0
/* While this is invalid, we may still get it in this state from a
 * well-behaved client if we send a SERVRELEASE at about the same
 * time the client sends an EDIT. So we reject it and continue. */
int
Open_EDIT(client_t *client, textbuf *buf, CTP_head_t head)
{
    CTP_EDIT_t mesg;
    int rv = recv_mesg(client->sockfd, &mesg, head);
    if (rv < 1)
        return rv;

    rv = send_err(client, REJECT_EDIT);
    free_mesg(mesg);
    return rv;
}
Ejemplo n.º 13
0
int
Connected_OPEN(client_t *client, textbuf *buf, CTP_head_t head)
{
    CTP_OPEN_t mesg;
    int rv = recv_mesg(client->sockfd, &mesg, head);
    if (rv < 1)
        return rv;

    /* check for correct client id */
    if (mesg.client_id != client->id) {
        free_mesg(mesg);
        return -1;
    }

    /* check file id
     * this server only supports a "default" file */
    if (mesg.file_id != 0) {
        free_mesg(mesg);
        send_err(client, BAD_FILE_ID);
        return 1;
    }

    free_mesg(mesg);

    /* transient... */
    client->state = Opening;

    /* build ACKOPEN response */
    CTP_ACKOPEN_t response;
    response.options = new_options();

    /* send response */
    rv = send_ACKOPEN(client->sockfd, response);
    free_options(response.options);
    client->state = Open;
    if (rv < 1)
        return rv;

    /* send STATUS message to all clients */
    CTP_STATUS_t status = get_status(buf);
    client_t *c;
    for (c = clients; c <= max_active_client; ++c) {
        if (c->active)
            send_STATUS(c->sockfd, status);
    }
    free_options(status.options);

    return 1;
}
Ejemplo n.º 14
0
int
Locked_EDIT(client_t *client, textbuf *buf, CTP_head_t head)
{
    CTP_EDIT_t mesg;
    int rv = recv_mesg(client->sockfd, &mesg, head);
    if (rv < 1)
        return rv;

    /* check for correct client id */
    if (mesg.client_id != client->id) {
        free_mesg(mesg);
        return -1;
    }

    switch (mesg.edit_action) {
        case INS:
            rv = tboverwrite(buf, mesg.pos, 0, mesg.data, mesg.datalen);
            break;
        case OVR:
            rv = tboverwrite(buf, mesg.pos, mesg.len, mesg.data, mesg.datalen);
            break;
        case DEL:
            rv = tboverwrite(buf, mesg.pos, mesg.len, NULL, 0);
            break;
    }

    if (rv < 0) {
        /* reject the edit */
        free_mesg(mesg);
        rv = send_err(client, REJECT_EDIT);
    } else {

        /* prepare and send ACKEDIT */
        CTP_ACKEDIT_t response;
        response.options = new_options();
        rv = send_ACKEDIT(client->sockfd, response);
        free_options(response.options);

        /* relay EDIT to other clients */
        client_t *c;
        for (c = clients; c <= max_active_client; ++c) {
            if (c != client && c->active)
                send_EDIT(c->sockfd, mesg);
        }
    }

    free_mesg(mesg);
    return rv;
}
Ejemplo n.º 15
0
static void get_numlogins(nut_ctype_t *client, const char *upsname)
{
	const	upstype_t	*ups;

	ups = get_ups_ptr(upsname);

	if (!ups) {
		send_err(client, NUT_ERR_UNKNOWN_UPS);
		return;
	}

	if (!ups_available(ups, client))
		return;

	sendback(client, "NUMLOGINS %s %d\n", upsname, ups->numlogins);
}
Ejemplo n.º 16
0
static void get_var_server(nut_ctype_t *client, const char *upsname, const char *var)
{
	if (!strcasecmp(var, "server.info")) {
		sendback(client, "VAR %s server.info "
			"\"Network UPS Tools upsd %s - "
			"http://www.networkupstools.org/\"\n", 
			upsname, UPS_VERSION);
		return;
	}

	if (!strcasecmp(var, "server.version")) {
		sendback(client, "VAR %s server.version \"%s\"\n", 
			upsname, UPS_VERSION);
		return;
	}

	send_err(client, NUT_ERR_VAR_NOT_SUPPORTED);
}
Ejemplo n.º 17
0
static void get_upsdesc(nut_ctype_t *client, const char *upsname)
{
	const	upstype_t	*ups;
	char	esc[SMALLBUF];

	ups = get_ups_ptr(upsname);

	if (!ups) {
		send_err(client, NUT_ERR_UNKNOWN_UPS);
		return;
	}

	if (ups->desc) {
		pconf_encode(ups->desc, esc, sizeof(esc));
		sendback(client, "UPSDESC %s \"%s\"\n", upsname, esc);

	} else {

		sendback(client, "UPSDESC %s \"Unavailable\"\n", upsname);
	}
}
Ejemplo n.º 18
0
static void get_desc(nut_ctype_t *client, const char *upsname, const char *var)
{
	const	upstype_t	*ups;
	const	char	*desc;

	ups = get_ups_ptr(upsname);

	if (!ups) {
		send_err(client, NUT_ERR_UNKNOWN_UPS);
		return;
	}

	if (!ups_available(ups, client))
		return;

	desc = desc_get_var(var);

	if (desc)
		sendback(client, "DESC %s %s \"%s\"\n", upsname, var, desc);
	else
		sendback(client, "DESC %s %s \"Description unavailable\"\n", upsname, var);
}
Ejemplo n.º 19
0
int
Open_REQLOCK(client_t *client, textbuf *buf, CTP_head_t head)
{
    CTP_OPEN_t mesg;
    int rv = recv_mesg(client->sockfd, &mesg, head);
    if (rv < 1)
        return rv;

    /* check for correct client id */
    if (mesg.client_id != client->id) {
        free_mesg(mesg);
        return -1;
    }

    /* only one client may lock at a time */
    if (locking_client != NULL) {
        free_mesg(mesg);
        send_err(client, CANT_LOCK);
        return 1;
    }

    free_mesg(mesg);

    /* transient... */
    client->state = WaitLock;

    /* build ACKLOCK response */
    CTP_ACKLOCK_t response;
    response.options = new_options();

    /* send response */
    rv = send_ACKOPEN(client->sockfd, response);
    free_options(response.options);
    client->state = Locked;
    locking_client = client;
    return rv;
}
Ejemplo n.º 20
0
void net_get(nut_ctype_t *client, int numarg, const char **arg)
{
	if (numarg < 1) {
		send_err(client, NUT_ERR_INVALID_ARGUMENT);
		return;
	}

	/* GET TRACKING [ID] */
	if (!strcasecmp(arg[0], "TRACKING")) {
		if (numarg < 2) {
			sendback(client, "%s\n", (client->tracking) ? "ON" : "OFF");
		}
		else {
			if (client->tracking)
				sendback(client, "%s\n", tracking_get(arg[1]));
			else
				send_err(client, NUT_ERR_FEATURE_NOT_CONFIGURED);
		}
		return;
	}

	if (numarg < 2) {
		send_err(client, NUT_ERR_INVALID_ARGUMENT);
		return;
	}

	/* GET NUMLOGINS UPS */
	if (!strcasecmp(arg[0], "NUMLOGINS")) {
		get_numlogins(client, arg[1]);
		return;
	}

	/* GET UPSDESC UPS */
	if (!strcasecmp(arg[0], "UPSDESC")) {
		get_upsdesc(client, arg[1]);
		return;
	}

	if (numarg < 3) {
		send_err(client, NUT_ERR_INVALID_ARGUMENT);
		return;
	}

	/* GET VAR UPS VARNAME */
	if (!strcasecmp(arg[0], "VAR")) {
		get_var(client, arg[1], arg[2]);
		return;
	}

	/* GET TYPE UPS VARNAME */
	if (!strcasecmp(arg[0], "TYPE")) {
		get_type(client, arg[1], arg[2]);
		return;
	}

	/* GET DESC UPS VARNAME */
	if (!strcasecmp(arg[0], "DESC")) {
		get_desc(client, arg[1], arg[2]);
		return;
	}

	/* GET CMDDESC UPS CMDNAME */
	if (!strcasecmp(arg[0], "CMDDESC")) {
		get_cmddesc(client, arg[1], arg[2]);
		return;
	}

	send_err(client, NUT_ERR_INVALID_ARGUMENT);
	return;
}
Ejemplo n.º 21
0
void remote_mainloop(void) {

  int r;
  pthread_t th;
  Status s;
  char fname[MAXBUF+1];

  /* Need to output line by line! */
  setlinebuf(stdout);

  /* Send a greeting */
  send_msg("R ogg123 from " PACKAGE " " VERSION);

  /* Initialize the thread controlling variables */
  pthread_mutex_init(&main_lock, NULL);
  sem_init(&sem_command, 0, 0);
  sem_init(&sem_processed, 0, 0);

  /* Start the thread */
  r = pthread_create(&th, NULL, remotethread, (void*)fname);
  if (r != 0) {
    send_err("E Could not create a thread (code %d)", r);
    return;
  }

  send_log("Start");

  /* The thread may already have processed some input,
     get the current status
   */
  pthread_mutex_lock(&main_lock);
  s = getstatus();
  pthread_mutex_unlock(&main_lock);

  while (s != QUIT) {

    /* wait for a new command */
    if (s != NEXT) {

      /* Wait until a new status is available,
         This puts the main tread asleep and
         saves resources
       */
       
      sem_wait(&sem_command);

      pthread_mutex_lock(&main_lock);
      s = getstatus();
      pthread_mutex_unlock(&main_lock);
    }

    send_log("Status: %d", s);

    if (s == NEXT) {

      /* The status is to play a new song. Set
         the status to PLAY and signal the thread
         that the status has been processed.
       */
       
      send_msg("I %s", fname);
      send_msg("S 0.0 0 00000 xxxxxx 0 0 0 0 0 0 0 0");
      send_msg("P 2");
      pthread_mutex_lock(&main_lock);
      setstatus(PLAY);
      s = getstatus();
      send_log("mainloop s=%d", s);
      sem_post(&sem_processed);
      s = getstatus();
      send_log("mainloop s=%d", s);
      pthread_mutex_unlock(&main_lock);

      /* Start the player. The player calls the playloop
         frequently to check for a new status (e.g. NEXT,
         STOP or PAUSE.
       */

      pthread_mutex_lock(&main_lock);
      s = getstatus();
      pthread_mutex_unlock(&main_lock);
      send_log("mainloop s=%d", s);
      play(fname);
      
      /* Retrieve the new status */
      pthread_mutex_lock(&main_lock);
      s = getstatus();
      pthread_mutex_unlock(&main_lock);

/* don't know why this was here, sending "play stoped" on NEXT wasn't good idea... */
//      if (s == NEXT) {
	  
	    /* Send "play stopped" */
//        send_msg("P 0");
//        send_log("P 0");
//      } else {
	  
	    /* Send "play stopped at eof" */
//        send_msg("P 0 EOF");
//        send_log("P 0 EOF");
//      }
      
    }
    else {

      /* Irrelevent status, notice the thread that
         it has been processed.
       */
       
      sem_post(&sem_processed);
    }    
  }

  /* Send "Quit" */
  send_msg("Q");
  send_log("Quit");

  /* Cleanup the semaphores */
  sem_destroy(&sem_command);
  sem_destroy(&sem_processed);

  return;
}
Ejemplo n.º 22
0
void *process_request(void *sock_id){

  char *host;
  char *serv_port;
  void *buf = malloc(BUF_START_SIZE+1);
  size_t bufsize = BUF_START_SIZE;
  int new_s_client =  (int) (intptr_t) sock_id;
  int s_server, proxy_port;
  int length=0, i, recieved, recieved_s, sent;
  struct addrinfo hints, *servinfo, *p;

/*declare for getpeername*/
  struct sockaddr_in sin;
  socklen_t sockLen = sizeof(struct sockaddr);
  int src_port;
  char ipstr[INET6_ADDRSTRLEN];
  static char dstbuf[INET6_ADDRSTRLEN];
  char eth0_IP[INET6_ADDRSTRLEN];

/*declare for bind*/
  char SNAT[100];
  struct sockaddr_in serv_add;
  socklen_t serv_len = sizeof( struct sockaddr);
  bzero((char *)&serv_add, sizeof(serv_add));
  serv_add.sin_family = AF_INET;
  serv_add.sin_port = htons(0); 

/*declare for log*/
  int bytes_recv=0;
  int bytes_sent=0;

  pthread_detach(pthread_self());

  bzero(buf, bufsize);

  /* update number of threads currently operating */
  pthread_mutex_lock(&count_lock);
  num_threads++;
  printf("Increasing:%d\n",num_threads);
  pthread_mutex_unlock(&count_lock);

		/* recieve from client*/
		recieved = read(new_s_client, buf, bufsize);
		if(recieved < 0){
		printf("recieved error\n");
		free(host);
		free(buf);
		kill_thread();
		pthread_cancel(pthread_self());
		return NULL;
		}else if(recieved == 0){
		close(new_s_client);
		close(s_server);
		return NULL;
		}
		printf("recv from client:%s\n",buf);

	/*getpeername -- client IP*/
	getpeername(new_s_client, (struct sockaddr*)&sin, &sockLen);
    struct sockaddr_in *s = (struct sockaddr_in *)&sin;
    src_port = ntohs(s->sin_port);
    inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);


	/*Get the server ip*/
	struct sockaddr_in dstaddr;
	socklen_t len = sizeof(dstaddr);

	if (getsockopt(new_s_client, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr *) &dstaddr, &len) == -1) {
		perror("getsockopt");
		close(new_s_client);
	}

	inet_ntop(dstaddr.sin_family, &dstaddr.sin_addr, dstbuf, sizeof(dstbuf));
	printf("original destination %s:%u\n", dstbuf, ntohs(dstaddr.sin_port));

	host = malloc(strlen(dstbuf));
	sprintf(host, "%s", dstbuf);

	serv_port = malloc(sizeof (ntohs(dstaddr.sin_port)));
	sprintf(serv_port, "%u", ntohs(dstaddr.sin_port));

	getInterfaceIP("eth0", eth0_IP);
/*
	printf("client address: %s\n", ipstr);
//	printf("proxy port of server side: %d\n", proxy_port);
	printf("port of client: %d\n", src_port);
	printf("serverside_ip: %s\n", eth0_IP);
	printf("dst port:%s\n",serv_port);
	//addto_iptables (proxy_port, ipstr, dstbuf, eth0_IP, src_port, serv_port);
*/
	/* send request to the specified host */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

	if ( (getaddrinfo(host, serv_port, &hints, &servinfo)) != 0) 
	{
		send_err(new_s_client, HTTP_ERR_502);
		free(host);
		free(buf);
		kill_thread();
		pthread_cancel(pthread_self());
		return NULL;
	}

	for(p = servinfo; p != NULL; p = p->ai_next) 
	{
		if ((s_server = socket(p->ai_family, p->ai_socktype,
						p->ai_protocol)) < 0){
			kill_thread();
			pthread_cancel(pthread_self()); 
			return NULL;
		}

		if ( (bind(s_server, (struct sockaddr *)&serv_add, sizeof(serv_add))) < 0){
			perror("cannot bind to socket");
			exit(1);
		}

		/*getsockname -- source port*/
		getsockname(s_server, (struct sockaddr*)&serv_add, &serv_len);
		proxy_port = ntohs(serv_add.sin_port);

		sprintf(SNAT, "iptables -t nat -A POSTROUTING --protocol tcp -d %s -j SNAT --sport %d --to-source %s", dstbuf, proxy_port, ipstr);
		system(SNAT);

		if (connect(s_server, p->ai_addr, p->ai_addrlen) < 0) 
		{
			close(s_server);
			continue;
		}
		break;
	}
    freeaddrinfo(servinfo);


	if (p == NULL){
		send_err(new_s_client, HTTP_ERR_500);
		free(host);
		free(buf);
		kill_thread();
		pthread_cancel(pthread_self());
		return NULL;
	}

		/*Send req to server*/
		if( ( sent = write(s_server, buf, recieved)) == -1 ){
			printf("Send error\n");
			free(host);
			free(buf);
			kill_thread();
			pthread_cancel(pthread_self());
			return NULL;
		}
		//printf("sent:%d\n", sent);
		bytes_sent += recieved;
		bzero(buf, bufsize);

	pthread_mutex_lock(&cache_write_lock);
	for (i = 0; i < MAX_NUM_THREADS; i++)
		sem_wait(&cache_read_sem);

//echo
	bytes_recv = echo(s_server, new_s_client, buf, bufsize);
	//printf("bytes recieved:%d\n",bytes_recv);

	for (i = 0; i < MAX_NUM_THREADS; i++)
		sem_post(&cache_read_sem);
	pthread_mutex_unlock(&cache_write_lock);

/*logging*/
	logEvent("%s %d %s %s %d %d\n", ipstr, src_port, host, serv_port, bytes_sent, bytes_recv );

	sprintf(SNAT, "iptables -t nat -D POSTROUTING --protocol tcp -d %s -j SNAT --sport %d --to-source %s", dstbuf, proxy_port, ipstr);
	system(SNAT);

	pthread_mutex_lock(&count_lock);
	num_threads--;
	printf("Decreasing:%d\n",num_threads);
	pthread_mutex_unlock(&count_lock);

	free(host);
	pthread_cancel(pthread_self());
	return NULL;
}
Ejemplo n.º 23
0
int main(int argc, char * argv[]){

	int MULTITHREADED = TRUE;
	void (*ret)(int);
	int s_client;
	int new_s_client;
	struct sockaddr_in sin;
	socklen_t sockLen = sizeof(struct sockaddr);
	uint16_t portnum;

	/*DNAT system call*/
	char DNAT[100];
	char eth1_IP[INET6_ADDRSTRLEN];
	char ip[INET6_ADDRSTRLEN];

	pthread_t thread;	  
	pthread_attr_t thread_attr;

	pthread_attr_init(&thread_attr);
	pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

	if(geteuid() != 0){
		printf("This program must be run as root\n");
		exit(1);
	}
 
	ret = signal(SIGPIPE, SIG_IGN);
	if (ret == SIG_ERR){
		perror(argv[0]);
		exit(1);
	}

	if (argc == 2)	  
		portnum = (uint16_t)atoi(argv[1]);
	else{
		fprintf(stderr, "usage: proxy [-t] <portnum>\n");
		exit(1);
	}
  
	bzero((char *)&sin, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(portnum); 

	/*  open a socket and attempt to bind to the given port */
	if ( (s_client = socket(PF_INET, SOCK_STREAM, 0)) < 0){
		perror("error requesting socket");
		exit (1);
	}

	setsockopt(s_client, SOL_SOCKET, SO_REUSEADDR, NULL, 0);

	if ( (bind(s_client, (struct sockaddr *)&sin, sizeof(sin))) < 0){
		perror("cannot bind to socket");
		exit(1);
	}

/*DNAT - System call*/
	getInterfaceIP("eth1", eth1_IP);
	//printf("proxy ip:%s\nproxy port num:%d\n", eth1_IP, sin.sin_port);
	sprintf(DNAT, "iptables -t nat -A PREROUTING --protocol tcp -i eth1 -j DNAT --to %s:%d", eth1_IP, portnum);
	system(DNAT);

	listen(s_client, MAX_QUEUE);
  
	pthread_mutex_init(&count_lock, NULL);
	pthread_mutex_init(&cache_write_lock, NULL);
	sem_init(&cache_read_sem, PTHREAD_PROCESS_PRIVATE, MAX_NUM_THREADS);

	while (1){
	 if (num_threads < MAX_NUM_THREADS){

		 if ( (new_s_client = accept(s_client, (struct sockaddr *)&sin, &sockLen)) < 0)
			continue;
			inet_ntop(sin.sin_family, &sin.sin_addr, ip, sizeof(ip));
			printf("connection from %s:%u\n", ip, ntohs(sin.sin_port));

		/*Implement multi-thread*/
		 if (MULTITHREADED)
		 {
		     if (pthread_create(&thread, &thread_attr, process_request, (void *) (long) new_s_client) != 0)
		     {
			     send_err(new_s_client, HTTP_ERR_500);
			     close(new_s_client);
		     }
		 }else{
			 process_request((void *) (long) new_s_client);
		  }
	 }else{
		sleep(1);
	 }
  }
  return 1;
}
Ejemplo n.º 24
0
int send_copy(char*ip, u64_t blocknum) {
	struct sbpfs_head head;
	char* head_data;
	int head_data_len;
	char* data = (char*) malloc(1024 * 1024 * 16);
	if (data == NULL) {
		printf("malloc data failed\n");
		return -1;
	}
	int succeed = readblock(blocknum, 0, 1024 * 1024 * 16, data);
	printf("succeed: %d\n", succeed);
	int skt = sbp_connect(ip, DNODE_SERVICE_PORT);
	printf("%d", skt);
	if (succeed < 0)
		send_err(skt, "copy_block", "cannot read block");
	else {
		printf("send start\n");
		head.data = NULL;
		head.entry_num = 0;
		head.title = REQUEST_OK;
		mkent(head,METHOD,"Copy");
		mkent(head,ARGC,"3");
		char blocknum_s[32];
		sprintf(blocknum_s, "%lld", blocknum);
		mkent(head,"Arg0",blocknum_s);
		mkent(head,"Arg1","0");
		char data_len_s[32];
		sprintf(data_len_s, "%d", 1024 * 1024 * 16);
		mkent(head,"Arg2",data_len_s);
		char data_length_s[32];
		sprintf(data_length_s, "%d", 1024 * 1024 * 16);
		mkent(head,CONTENT_LEN,data_length_s);

		if (make_head(&head_data, &head_data_len, &head) == -1) {
			printf("mkhead failed\n");
			free(data);
			free(head_data);
			return -1;
		}
		if (sbp_send(skt, head_data, head_data_len) < 0) {
			printf("send head err failed\n");
			sbp_perror("a");
			perror("a");
			free(data);
			free(head_data);
			return -1;
		}

		if (sbp_send(skt, data, 1024 * 1024 * 16) < 0) {
			printf("send data err failed\n");
			sbp_perror("a");
			perror("a");
			free(data);
			free(head_data);
			return -1;
		}
		printf("send succeed\n");
		free(data);
		free(head_data);
		return 0;
	}
	return 0;
}
Ejemplo n.º 25
0
void process_req(struct list_entry * ent) {
	char* head_data;
	int head_data_len;
	struct sbpfs_head head;
	if (ent->req == 1) {
		char* data = (char*) malloc(ent->length);
		if (data == NULL) {
			printf("malloc data failed\n");
			return;
		}
		int succeed = readblock(ent->block_num, ent->offset, ent->length, data);
		printf("succeed: %d\n", succeed);
		if (succeed < 0)
			send_err(ent->skt, "read_block", "cannot read block");
		else {
			head.data = NULL;
			head.title = REQUEST_OK;
			head.entry_num = 0;
			char data_length_s[32];
			sprintf(data_length_s, "%d", ent->length);
			mkent(head,CONTENT_LEN,data_length_s);
			if (make_head(&head_data, &head_data_len, &head) == -1) {
				printf("mkhead failed\n");
				free(head_data);
				free(data);
				return;
			}
			if (sbp_send(ent->skt, head_data, head_data_len) < 0) {
				printf("send head err failed\n");
				sbp_perror("a");
				perror("a");
				free(data);
				free(head_data);
				return;
			}
			if (sbp_send(ent->skt, data, ent->length) < 0) {
				printf("send data err failed\n");
				sbp_perror("a");
				perror("a");
				free(data);
				free(head_data);

				return;
			}
			free(data);
			free(head_data);
			return;
		}
	}
	if (ent->req == 2) {
		int succeed = writeblock(ent->block_num, ent->offset, ent->length,
				ent->data);
		printf("succeed in write : %d\n", succeed);
		if (succeed < 0) {
			send_err(ent->skt, "write_block", "cannot write block");
		} else {
			head.data = NULL;
			head.title = REQUEST_OK;
			head.entry_num = 0;
			mkent(head,CONTENT_LEN,"0");
		}
		if (make_head(&head_data, &head_data_len, &head) == -1) {
			printf("mkhead failed\n");
			free(head_data);
			return;
		}
		if (sbp_send(ent->skt, head_data, head_data_len) < 0) {
			printf("send head err failed\n");
			sbp_perror("a");
			perror("a");
			free(head_data);
			return;
		}
		char*ip = "59.78.15.46";
		//send_success(ip,ent->block_num);
	}
	if (ent->req == 3) {
		int succeed = writeblock(ent->block_num, ent->offset, ent->length,
				ent->data);
		printf("succeed in copy : %d\n", succeed);

	}
}
Ejemplo n.º 26
0
int main(int argc, char **argv) {
  int sockfd; /* socket */
  int portno; /* port to listen on */
  int clientlen; /* byte size of client's address */
  struct sockaddr_in serveraddr; /* server's addr */
  struct sockaddr_in clientaddr; /* client addr */
  struct hostent *hostp; /* client host info */
  char buf[BUFSIZE]; /* message buf */
  char *hostaddrp; /* dotted decimal host addr string */
  int optval; /* flag value for setsockopt */
  int n; /* message byte size */

  /* 
   * check command line arguments 
   */
  if (argc != 2) {
    fprintf(stderr, "usage: %s <port>\n", argv[0]);
    exit(1);
  }
  portno = atoi(argv[1]);

  /* 
   * socket: create the parent socket 
   */
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd < 0) 
    error("ERROR opening socket");

  /* setsockopt: Handy debugging trick that lets 
   * us rerun the server immediately after we kill it; 
   * otherwise we have to wait about 20 secs. 
   * Eliminates "ERROR on binding: Address already in use" error. 
   */
  optval = 1;
  setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, 
         (const void *)&optval , sizeof(int));

  /*
   * build the server's Internet address
   */
  bzero((char *) &serveraddr, sizeof(serveraddr));
  serveraddr.sin_family = AF_INET;
  serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
  serveraddr.sin_port = htons((unsigned short)portno);

  /* 
   * bind: associate the parent socket with a port 
   */
  if (bind(sockfd, (struct sockaddr *) &serveraddr, 
       sizeof(serveraddr)) < 0) 
    error("ERROR on binding");

  /* 
   * main loop: wait for a datagram, then echo it
   */
  clientlen = sizeof(clientaddr);
  while (1) {
    // recvfrom: receive a UDP datagram from a client
    Request *req = malloc(sizeof (Request));
    bzero(req->filename, FILENAMESIZE);
    n = recvfrom(sockfd, (char *) req, REQSIZE, 0,
         (struct sockaddr *) &clientaddr, &clientlen);
    if (n < 0)
      error("ERROR in recvfrom");

    if (access(req->filename, F_OK) == -1){
      send_err(sockfd, &clientlen, &clientaddr);
      free(req);
      continue;
    }

    // printf("got request for %s\n", req->filename);
    send_file(sockfd, &clientlen, &clientaddr, req); 
    free(req);
  }
}
Ejemplo n.º 27
0
static void * remotethread(void * arg) {

  int done = 0;
  int error = 0;
  int ignore = 0;
  char buf[MAXBUF+1];
  char *b;

#if HAVE_SELECT
  fd_set fd;
#endif
  
  buf[MAXBUF]=0;

  while(!done) {
    /* Read a line */
    buf[0] = 0;
    send_log("Waiting for input: ...");

#if HAVE_SELECT
    FD_ZERO(&fd);
    FD_SET(0,&fd);
    select (1, &fd, NULL, NULL, NULL);
#endif

    fgets(buf, MAXBUF, stdin);
    buf[strlen(buf)-1] = 0;

    /* Lock on */
    pthread_mutex_lock (&main_lock);

    send_log("Input: %s", buf);
    error = 0;

    if (!strncasecmp(buf,"l",1)) {
	/* prepare to load */
      if ((b=strchr(buf,' ')) != NULL) {
        /* Prepare to load a new song */
        strcpy((char*)arg, b+1);
        setstatus(NEXT);
      } 
      else {
        /* Invalid load command */
        error = 1;
      }
    }
    else
    if (!strncasecmp(buf,"p",1)) {
      /* Prepare to (un)pause */
      invertpause();
    }
	else
    if (!strncasecmp(buf,"j",1)) {
      /* Prepare to seek */
      if ((b=strchr(buf,' ')) != NULL) {
        set_seek_opt(&options, b+1);
	  }
      ignore = 1;
    }
    else
    if (!strncasecmp(buf,"s",1)) {
      /* Prepare to stop */
      setstatus(STOP);
    }
	else
    if (!strncasecmp(buf,"r",1)) {
      /* Prepare to reload */
      setstatus(NEXT);
    }
    else
    if (!strncasecmp(buf,"h",1)) {
      /* Send help */
	  send_msg("H +----------------------------------------------------+");
	  send_msg("H | Ogg123 remote interface                            |");
	  send_msg("H |----------------------------------------------------|");
	  send_msg("H | Load <file>     -  load a file and starts playing  |");
	  send_msg("H | Pause           -  pause or unpause playing        |");
	  send_msg("H | Jump [+|-]<f>   -  jump <f> seconds forth or back  |");
	  send_msg("H | Stop            -  stop playing                    |");
	  send_msg("H | Reload          -  reload last song                |");
	  send_msg("H | Quit            -  quit ogg123                     |");
	  send_msg("H |----------------------------------------------------|");
	  send_msg("H | refer to README.remote for documentation           |");
	  send_msg("H +----------------------------------------------------+");
	  ignore = 1;
    }
    else
    if (!strncasecmp(buf,"q",1)) {
      /* Prepare to quit */
      setstatus(QUIT);
      done = 1;
    }
    else {
      /* Unknown input received */
      error = 1;
    }

    if (ignore) {
      /* Unlock */
      pthread_mutex_unlock (&main_lock);
      ignore = 0;
    } else {
      if (error) {
    	/* Send the error and unlock */
    	send_err("E Unknown command '%s'", buf);
    	send_log("Unknown command '%s'", buf);
		/* Unlock */
    	pthread_mutex_unlock (&main_lock);
      } 
      else {
    	/* Signal the main thread */
    	sem_post(&sem_command);
    	/* Unlock */
    	pthread_mutex_unlock (&main_lock);
    	/* Wait until the change has been noticed */
    	sem_wait(&sem_processed);
      }
    }
  }

  return NULL;
}