Example #1
0
int main(int argc, char **argv)
{
	int listenfd, connfd;
	printf("Controld  $Id: controld.cpp,v 1.76.2.1 2002/10/24 20:34:32 thegoodguy Exp $\n\n");
	
	switch (fork())
	{
	case -1:
		perror("[controld] fork");
		return -1;
	case 0:
		break;
	default:
		return 0;
	}
	
	if (setsid() == -1)
	{
		perror("[controld] setsid");
		return -1;
	}

	eventServer = new CEventServer;

	struct sockaddr_un servaddr;
	int clilen;
	memset(&servaddr, 0, sizeof(struct sockaddr_un));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, CONTROLD_UDS_NAME);
	clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
	unlink(CONTROLD_UDS_NAME);

	//network-setup
	if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
	}

	if ( bind(listenfd, (struct sockaddr*) &servaddr, clilen) <0 )
	{
		perror("[controld] bind failed...\n");
		exit(-1);
	}


	if (listen(listenfd, 5) !=0)
	{
		perror("[controld] listen failed...\n");
		exit( -1 );
	}

	//busyBox
	signal(SIGHUP,sig_catch);
	signal(SIGINT,sig_catch);
	signal(SIGQUIT,sig_catch);
	signal(SIGTERM,sig_catch);

	/* load configuration */
	config = new CConfigFile(',');

	if (!config->loadConfig(CONF_FILE))
	{
		/* set defaults if no configuration file exists */
		printf("[controld] %s not found\n", CONF_FILE);
	}


	settings.volume      = config->getInt32("volume", 100);
	settings.volume_avs  = config->getInt32("volume_avs", 100);
	settings.mute        = config->getBool("mute", false);
	settings.mute_avs    = config->getBool("mute_avs", false);
	settings.videooutput = config->getInt32("videooutput", 1); // fblk1 - rgb
	settings.videoformat = config->getInt32("videoformat", 2); // fnc2 - 4:3

	setBoxType(); // dummy set - liest den aktuellen Wert aus!

	watchDog = new CEventWatchDog();
	aspectRatioNotifier = new CControldAspectRatioNotifier();
	watchDog->registerNotifier(WDE_VIDEOMODE, aspectRatioNotifier);

	//init
	audioControl::setVolume(map_volume(settings.volume_avs, true));
	zapit.setVolume(map_volume(settings.volume, false), map_volume(settings.volume, false));
	lcdd.setVolume(settings.volume_avs);    // we could also display settings.volume at startup

	audioControl::setMute(settings.mute_avs);
	zapit.muteAudio(settings.mute);
	lcdd.setMute(settings.mute || settings.mute_avs);

	setvideooutput(settings.videooutput);
	setVideoFormat(settings.videoformat, false);


	try
	{
		struct CControld::Header rmessage;
		while(true)
		{
			connfd = accept(listenfd, (struct sockaddr*) &servaddr, (socklen_t*) &clilen);
			memset(&rmessage, 0, sizeof(rmessage));
			read(connfd,&rmessage,sizeof(rmessage));

			parse_command(connfd, &rmessage);
			close(connfd);
		}
	}
	catch (std::exception& e)
	{
		printf("[controld] caught std-exception in main-thread %s!\n", e.what());
	}
	catch (...)
	{
	    printf("[controld] caught exception in main-thread!\n");
  	}
}
Example #2
0
/******************************************************************************
 *                                                                            *
 * Function: send_list_of_active_checks_json                                  *
 *                                                                            *
 * Purpose: send list of active checks to the host                            *
 *                                                                            *
 * Parameters: sock - open socket of server-agent connection                  *
 *             json - request buffer                                          *
 *                                                                            *
 * Return value:  SUCCEED - list of active checks sent succesfully            *
 *                FAIL - an error occured                                     *
 *                                                                            *
 * Author: Aleksander Vladishev                                               *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
int	send_list_of_active_checks_json(zbx_sock_t *sock, struct zbx_json_parse *jp)
{
	char		host[HOST_HOST_LEN_MAX], *name_esc, params[MAX_STRING_LEN],
			pattern[MAX_STRING_LEN], tmp[32];
	DB_RESULT	result;
	DB_ROW		row;
	DB_ITEM		item;
	struct zbx_json	json;
	int		res = FAIL;
	zbx_uint64_t	hostid;
	char		error[MAX_STRING_LEN];

	char		**regexp = NULL;
	int		regexp_alloc = 32;
	int		regexp_num = 0, n;

	char		*sql = NULL;
	int		sql_alloc = 2048;
	int		sql_offset;

	zabbix_log(LOG_LEVEL_DEBUG, "In send_list_of_active_checks_json()");

	if (FAIL == zbx_json_value_by_name(jp, ZBX_PROTO_TAG_HOST, host, sizeof(host)))
	{
		zbx_snprintf(error, MAX_STRING_LEN, "%s", zbx_json_strerror());
		goto out;
	}

	if (FAIL == get_hostid_by_host(host, &hostid, error))
		goto out;

	regexp = zbx_malloc(regexp, regexp_alloc);
	sql = zbx_malloc(sql, sql_alloc);

	name_esc = DBdyn_escape_string(host);

	sql_offset = 0;
	zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 1024,
			"select %s where i.hostid=h.hostid and h.status=%d and i.type=%d and h.hostid=" ZBX_FS_UI64
			" and h.proxy_hostid=0",
			ZBX_SQL_ITEM_SELECT,
			HOST_STATUS_MONITORED,
			ITEM_TYPE_ZABBIX_ACTIVE,
			hostid);

	if (0 != CONFIG_REFRESH_UNSUPPORTED)
		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 256, " and (i.status=%d or (i.status=%d and i.nextcheck<=%d))",
				ITEM_STATUS_ACTIVE, ITEM_STATUS_NOTSUPPORTED, time(NULL));
	else
		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 256, " and i.status=%d",
				ITEM_STATUS_ACTIVE);

	zbx_free(name_esc);

	zbx_json_init(&json, ZBX_JSON_STAT_BUF_LEN);
	zbx_json_addstring(&json, ZBX_PROTO_TAG_RESPONSE, ZBX_PROTO_VALUE_SUCCESS, ZBX_JSON_TYPE_STRING);
	zbx_json_addarray(&json, ZBX_PROTO_TAG_DATA);

	result = DBselect("%s", sql);

	while (NULL != (row = DBfetch(result)))
	{
		DBget_item_from_db(&item, row);

		zbx_json_addobject(&json, NULL);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_KEY, item.key, ZBX_JSON_TYPE_STRING);
		if (0 != strcmp(item.key, item.key_orig))
			zbx_json_addstring(&json, ZBX_PROTO_TAG_KEY_ORIG, item.key_orig, ZBX_JSON_TYPE_STRING);
		zbx_snprintf(tmp, sizeof(tmp), "%d", item.delay);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_DELAY, tmp, ZBX_JSON_TYPE_STRING);
		zbx_snprintf(tmp, sizeof(tmp), "%d", item.lastlogsize);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_LOGLASTSIZE, tmp, ZBX_JSON_TYPE_STRING);
		zbx_json_close(&json);

		/* Special processing for log[] and eventlog[] items */
		do {	/* simple try realization */
			if (0 != strncmp(item.key, "log[", 4) && 0 != strncmp(item.key, "eventlog[", 9))
				break;

			if (2 != parse_command(item.key, NULL, 0, params, MAX_STRING_LEN))
				break;;
				
			if (0 != get_param(params, 2, pattern, sizeof(pattern)))
				break;

			if (*pattern != '@')
				break;

			for (n = 0; n < regexp_num; n++)
				if (0 == strcmp(regexp[n], pattern + 1))
					break;

			if (n != regexp_num)
				break;

			if (regexp_num == regexp_alloc)
			{
				regexp_alloc += 32;
				regexp = zbx_realloc(regexp, regexp_alloc);
			}

			regexp[regexp_num++] = strdup(pattern + 1);
		} while (0);	/* simple try realization */
	}
	zbx_json_close(&json);

	DBfree_result(result);

	if (0 != regexp_num)
	{
		zbx_json_addarray(&json, ZBX_PROTO_TAG_REGEXP);

		sql_offset = 0;
		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 512,
				"select r.name,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive"
				" from regexps r,expressions e where r.regexpid=e.regexpid and r.name in (");

		for (n = 0; n < regexp_num; n++)
		{
			name_esc = DBdyn_escape_string(regexp[n]);
			zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 512, "%s'%s'",
					n == 0 ? "" : ",",
					name_esc);
			zbx_free(name_esc);
			zbx_free(regexp[n]);
		}
		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, 8, ")");

		result = DBselect("%s", sql);
		while (NULL != (row = DBfetch(result)))
		{
			zbx_json_addobject(&json, NULL);
			zbx_json_addstring(&json, "name", row[0], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "expression", row[1], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "expression_type", row[2], ZBX_JSON_TYPE_INT);
			zbx_json_addstring(&json, "exp_delimiter", row[3], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "case_sensitive", row[4], ZBX_JSON_TYPE_INT);
			zbx_json_close(&json);
		}
		DBfree_result(result);
	}
	zbx_free(regexp);

	zabbix_log(LOG_LEVEL_DEBUG, "Sending [%s]",
			json.buffer);

	if (SUCCEED != zbx_tcp_send_raw(sock, json.buffer))
		zbx_snprintf(error, MAX_STRING_LEN, "%s", zbx_tcp_strerror());
	else
		res = SUCCEED;

	zbx_json_free(&json);
	zbx_free(sql);

out:
	if (FAIL == res)
		zabbix_log(LOG_LEVEL_WARNING, "Send list of active checks to [%s] failed: %s",
				get_ip_by_socket(sock), error);

	return res;
}
void client() {

	int consock, registerfd, server_sockfd, client_sockfd;
	int server_len, client_len;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;
	int result;
	char option[1024];

	// consock=connect_client(2);
	server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);
	server_address.sin_port = htons(PORTNO);
	server_len = sizeof(server_address);
	bind(server_sockfd, (struct sockaddr *) &server_address, server_len);
	listen(server_sockfd, 5);

	//initializing readfds to sockfd.
	FD_ZERO(&readfds);

	FD_SET(server_sockfd, &readfds);

	FD_SET(0, &readfds);

	while (1) // waiting for client requests
	{

		int fd;

		int nread;
		char ch[1024];

		testfds = readfds;

		result = select(FD_SETSIZE, &testfds, (fd_set *) 0, (fd_set *) 0,
				(struct timeval *) 0);
		if (result <= 0) {
			perror("Error");
			exit(1);
		}

		if (FD_ISSET(0, &testfds)) {
			memset(option, '\0', 1024);
			fgets(option, 1024, stdin);
			option[strlen(option) - 1] = '\0';
			parse_command(option);

		}

		else {

			for (fd = 0; fd < FD_SETSIZE; fd++) {
				if (FD_ISSET(fd, &testfds)) {
					if (fd == server_sockfd)

					{
						client_sockfd = accept(server_sockfd,
								(struct sockaddr *) &client_address,
								&client_len);

						FD_SET(client_sockfd, &readfds);

					} else {
						memset(ch, 0, 100);
						ioctl(fd, FIONREAD, &nread);
						if (nread == 0 && fd != 0)

						{
							close(fd);
							int j;
							////finding the fd in client connection////
							for (j = 1; j < 4; j++) {

								if (mycon[j].confd == fd) {
									break;
								}
							}

							////terminate the connection
							terminate_con(mycon[j].con_id);
							FD_CLR(fd, &readfds);

							display_con();

						} else {
							char temp1[1024];
							memset(ch, 0, 1024);
							memset(temp1, 0, 1024);
							read(fd, &ch, sizeof(ch));
							strcpy(temp1, ch);
							char *reader;
							reader = strtok(temp1, " ");

							if (reader != NULL) {

								if (strcmp(reader, "send") == 0) {
									read_table(fd, ch);
									memset(ch, 0, 1024);

								}

								else if (strcmp(reader, "connect") == 0) {

									update_conn(ch, fd);
									memset(ch, 0, 1024);

								} else if (strcmp(reader, "ERROR") == 0) {

									fprintf(stderr, "\n%s\n", ch);
									memset(ch, 0, 1024);

								} else if (strcmp(reader, "upload") == 0) {
									char filenm[256];
									bzero(filenm, 256);
									char* tk;
									long long files;
									tk = strtok(NULL, " ");

									strcpy(filenm, tk);

									tk = strtok(NULL, " ");
									files = atoll(tk);

									int val = file_receive(fd, files, filenm);
									if (val == -1)
										fprintf(stderr,
												"\n\nERROR IN FILE TRANSFER\n\n");
									memset(ch, 0, 1024);

								} else if (strcmp(reader, "terminate") == 0) {

									char* temp2;
									char ht[50];
									int pt, i;
									temp2 = strtok(NULL, " ");
									strcpy(ht, temp2);
									temp2 = strtok(NULL, " ");
									pt = atoi(temp2);
									for (i = 1; i < 4; i++) {
										if (((strcmp(mycon[i].hostn, ht) == 0))
												&& (mycon[i].port == pt))
											break;

									}

									mycon[i].con_id = -1;
									close(mycon[i].confd);
									FD_CLR(mycon[i].confd, &readfds);
									display_con();
									memset(ch, 0, 1024);

								} else if (strcmp(reader, "download") == 0) {
									char dfile[256], conip[16];
									bzero(dfile, 256);
									char* toknize;
									int dfd, port;
									toknize = strtok(NULL, " ");
									strcpy(dfile, toknize);
									toknize = strtok(NULL, " ");
									strcpy(conip, toknize);
									toknize = strtok(NULL, " ");
									port = atoi(toknize);
									int j;
									for (j = 1; j < 4; j++) {

										if ((strcmp(mycon[j].ip, conip) == 0)
												&& (mycon[j].port == port))
											break;
									}
									int val = file_transfer(mycon[j].confd,
											dfile);
									if (val == -1) {
										fprintf(stderr,
												"\n\nERROR IN FILE TRANSFER\n\n");
										write(mycon[j].confd, "ERROR IN FILE",
												30);
									}
									memset(ch, 0, 1024);

								}
							} else {

								memset(ch, '\0', 1024);
								memset(temp1, '\0', 1024);
								reader = NULL;

							}
						}
					}

				}
			}
		}
	}
}
Example #4
0
StompFrames StompCodec::loads(std::string& rxbuf)
{
    const char* p;
    char ch;
    std::string name, value;
    size_t n;
    StompFrames frames;

    const char *start = rxbuf.c_str();
    const char *end = rxbuf.c_str() + rxbuf.size();
    for (p = start; p != end; ++p) {
        ch = *p;
        switch (state_) {
        case State::SW_COMMAND_BEGIN:
            if (ch == CR || ch == LF) // heartbeat
                break;
            start = p;
            frame_ = std::make_shared<StompFrame>();
            state_ = State::SW_COMMAND;
            break;
        case State::SW_COMMAND:
            if (ch == LF) {
                n = p - start;
                if (*(p - 1) == CR) --n;
                frame_->cmd_ = parse_command(start, n);
                state_ = State::SW_HEADER_BEGIN;
            }
            break;
        case State::SW_HEADER_BEGIN:
            if (ch == CR) {
                if (*(p + 1) != LF)
                    goto dump_finish;
            } else if (ch == LF) {
                state_ = State::SW_BODY_BEGIN;
            } else {
                start = p;
                state_ = State::SW_HEADER_NAME;
            }
            break;
        case State::SW_HEADER_NAME:
            if (ch == ':') {
                n = p - start;
                if (n == 0)
                    goto dump_finish;
                else {
                    name.assign(start, n);
                    start = p + 1;
                    state_ = State::SW_HEADER_VALUE;
                }
            }
            break;
        case State::SW_HEADER_VALUE:
            if (ch == LF) {
                n = p - start;
                if (*(p - 1) == CR) --n;
                value.assign(start, n);
                frame_->set_header(name, value);
                state_ = State::SW_HEADER_BEGIN;
            }
            break;
        case State::SW_BODY_BEGIN:
            if (frame_->have_body()) {
                if (expect_body_len_ == 0)
                    expect_body_len_ = frame_->get_content_length();
                if (expect_body_len_ > 0) {
                    size_t remain = end - p;
                    if (remain > expect_body_len_) {
                        frame_->append_body(p, expect_body_len_);
                        frames.push_back(frame_);
                        state_ = State::SW_COMMAND_BEGIN;
                    } else {
                        frame_->append_body(p, remain);
                        expect_body_len_ -= remain;
                    }
                } else {
                    start = p;
                    state_ = State::SW_BODY;
                }
            } else 
                state_ = State::SW_COMMAND_BEGIN;
            break;
        case State::SW_BODY:
            if (ch == '\0') {
                n = p - start;
                frame_->append_body(start, n);
                frames.push_back(frame_);
                state_ = State::SW_COMMAND_BEGIN;
            }
            break;
        }
    }

    if (state_ == State::SW_BODY) {
        frame_->append_body(start, end - start);
        rxbuf.clear();
    } else
        rxbuf.erase(0, start - rxbuf.c_str());

dump_finish:
    return frames;
}
Example #5
0
/* try to display help for current comand line
 */
static int help_command_line(tinysh_cmd_t *cmd, uchar *_str)
{
  uchar *str=_str;

  while(1)
    {
      int ret;
      ret=parse_command(&cmd,&str);
      if(ret==MATCH && *str==0) /* found unique match or empty line */
        {
          tinysh_cmd_t *cm;
          int len=0;

          if(cmd->child) /* display sub-commands help */
            {
              display_child_help(cmd->child);
              return 0;
            }
          else  /* no sub-command, show single help */
            {
              if(*(str-1)!=' ')
                putchar(' ');
              if(cmd->usage)
                puts(cmd->usage);
              puts(": ");
              if(cmd->help)
                puts(cmd->help);
              else
                puts("no help available");
              putchar('\n');
            }
          return 0;
        }
      else if(ret==MATCH && *str)
        { /* continue processing the line */
          cmd=cmd->child;
        }
      else if(ret==AMBIG)
        {
          puts("\nambiguity: ");
          puts(str);
          putchar('\n');
          return 0;
        }
      else if(ret==UNMATCH)
        {
          puts("\nno match: ");
          puts(str);
          putchar('\n');
          return 0;
        }
      else /* NULLMATCH */
        {
          if(cur_cmd_ctx)
            display_child_help(cur_cmd_ctx->child);
          else
            display_child_help(root_cmd);
          return 0;
        }
    }
}
Example #6
0
File: get_raw.c Project: goTJ/tj
//}}}
int main(int argc, char *argv[]){
	int init_port;
	int data_port;
	int ctrl_socket;
	int init_socket;
	pid_t p;
	int shmid_ctrl, shmid_mask, shmid_masklist; 

	int fd_s;
	struct sockaddr_in cli;
	char buffer[MAX_LENG];
	socklen_t cli_len = sizeof(cli);
	if(argc < 3){
		fprintf(stderr, "get_raw hostname, port");
		exit(1);
	}
	sscanf(argv[2],"%d", &init_port);

	shmid_ctrl = shmget(SHMKEY_CTRL, SHLEN_CTRL, PERMS|IPC_CREAT);  //share memory
	shmid_mask = shmget(SHMKEY_MASK, SHLEN_MASK, PERMS|IPC_CREAT);  //share memory
	shmid_masklist = shmget(SHMKEY_MASKLIST, SHLEN_MASKLIST, PERMS|IPC_CREAT);  //share memory

	ctrl = (char *) shmat(shmid_ctrl, NULL, 0);	
	mask = (char *) shmat(shmid_mask, NULL, 0);	
	masklist = (char *) shmat(shmid_masklist, NULL, 0);	

	init();
	data_port = get_data_socket_port(argv[1], init_port);
	ctrl_socket = tcp_server(CTRL_PORT);
	p = fork();

	if(p <0){
		fprintf(stderr, "fork error");
		exit(1);
	}
	if(p == 0){
		char buffer[MAX_LENG];	
		nice(3);
		read_raw(argv[1], data_port);
		exit(0);
	}
	nice(-1);
	while(1){
		if((fd_s = accept(ctrl_socket, (struct sockaddr*)&cli, &cli_len))<0){perror("ACCEPT error"); exit(1);}
		if (!fork()){
			read(fd_s, buffer, MAX_LENG);
			if(parse_command(buffer, fd_s) ==1){
				write(fd_s, "ok\r\n",4);
			}
			else
				write(fd_s, "error\r\n",7);
			exit(0);
			close(fd_s);	
		}
		close(fd_s);
		while(waitpid(-1,NULL, WNOHANG)>0);
	}
	close(ctrl_socket);


}
Example #7
0
/**
* Process two commands in parallel, by creating two children.
*/
static bool do_in_parallel(command_t *cmd1, command_t *cmd2, int level, command_t *father)
{
  /* TODO execute cmd1 and cmd2 simultaneously */
  BOOL ret_1, ret_2;
  char* cmd;
  SECURITY_ATTRIBUTES sa_1;
  STARTUPINFO siStartupInfo_1;
  PROCESS_INFORMATION piProcessInfo_1;
  HANDLE hOutFile_1 = INVALID_HANDLE_VALUE;
  HANDLE hInFile_1 = INVALID_HANDLE_VALUE;
  HANDLE hErrFile_1 = INVALID_HANDLE_VALUE;

  SECURITY_ATTRIBUTES sa_2;
  STARTUPINFO siStartupInfo_2;
  PROCESS_INFORMATION piProcessInfo_2;
  HANDLE hOutFile_2 = INVALID_HANDLE_VALUE;
  HANDLE hInFile_2 = INVALID_HANDLE_VALUE;
  HANDLE hErrFile_2 = INVALID_HANDLE_VALUE;
  BOOL changed = FALSE;
  char buffer[100];
  int x;
  ZeroMemory(&sa_1, sizeof(SECURITY_ATTRIBUTES));
  sa_1.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa_1.bInheritHandle = TRUE;

  ZeroMemory(&siStartupInfo_1, sizeof(siStartupInfo_1));
  ZeroMemory(&piProcessInfo_1, sizeof(piProcessInfo_1));

  siStartupInfo_1.cb = sizeof(siStartupInfo_1); 

  ZeroMemory(&sa_2, sizeof(SECURITY_ATTRIBUTES));
  sa_2.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa_2.bInheritHandle = TRUE;

  ZeroMemory(&siStartupInfo_2, sizeof(siStartupInfo_2));
  ZeroMemory(&piProcessInfo_2, sizeof(piProcessInfo_2));

  siStartupInfo_2.cb = sizeof(siStartupInfo_2);

  if(cmd2->up != NULL){
    if(cmd2->up->op != OP_PARALLEL){
      return parse_command(cmd2->up, level, father, (void*)(0)) == 0;
    }
  }

  if(cmd1->scmd){
    redirrect_command(cmd1->scmd, &siStartupInfo_1, &hInFile_1, &hOutFile_1, &hErrFile_1);
    cmd = get_argv(cmd1->scmd);
    ret_1 = CreateProcess(NULL,
      (LPSTR)cmd,
      (LPSECURITY_ATTRIBUTES)&sa_1,
      NULL,
      TRUE,
      NORMAL_PRIORITY_CLASS,
      NULL,
      NULL,
      &siStartupInfo_1,
      &piProcessInfo_1);
    free(cmd);
  }

  if(cmd2->scmd){
    redirrect_command(cmd2->scmd, &siStartupInfo_2, &hInFile_2, &hOutFile_2, &hErrFile_2);
    cmd = get_argv(cmd2->scmd);
    ret_2 = CreateProcess(NULL,
      (LPSTR)cmd,
      (LPSECURITY_ATTRIBUTES)&sa_2,
      NULL,
      TRUE,
      NORMAL_PRIORITY_CLASS,
      NULL,
      NULL,
      &siStartupInfo_2,
      &piProcessInfo_2);
    free(cmd);
  }

  if(cmd1->scmd){
    if(ret_1 == FALSE){
      sprintf(buffer, "%s: No such file or directory\n", cmd);
      WriteFile(hErrFile_1, buffer, strlen(buffer), &x, NULL);
    }
    else{
      WaitForSingleObject(piProcessInfo_1.hProcess, INFINITE);
      GetExitCodeProcess(piProcessInfo_1.hProcess, &ret_1);

      CloseHandle(piProcessInfo_1.hProcess);
      CloseHandle(piProcessInfo_1.hThread);
    }
    close_handles(hInFile_1, hOutFile_1, hErrFile_1);
  }

  if(cmd2->scmd){
    if(ret_2 == FALSE){
      sprintf(buffer, "%s: No such file or directory\n", cmd);
      WriteFile(hErrFile_2, buffer, strlen(buffer), &x, NULL);
    }
    else{
      WaitForSingleObject(piProcessInfo_2.hProcess, INFINITE);
      GetExitCodeProcess(piProcessInfo_2.hProcess, &ret_2);
      CloseHandle(piProcessInfo_2.hProcess);
      CloseHandle(piProcessInfo_2.hThread);
    }
    close_handles(hInFile_2, hOutFile_2, hErrFile_2);
  }
  if(cmd1->scmd && cmd2->scmd){
    return (ret_2 == 0 &&  ret_1 == 0);
  }

  if(!cmd1->scmd){
    do_in_parallel(cmd1->cmd1, cmd1->cmd2, level, cmd1);
  }

  if(!cmd2->scmd){
    do_in_parallel(cmd2->cmd1, cmd2->cmd2, level, cmd2);
  }

  return (ret_1 && ret_2); /* TODO replace with actual exit status */
}
Example #8
0
int main(void) {
    
    bst_node_type *head;
    data_item_type *item;
    bst_stats_type stats;
    long value;
    char buffer[2048];  
    size_t size;
    char **args;
    int arg_count;
    int i;



    // loop forever receiving command strings from STDIN.
    while (1) {

        size=getline(buffer, sizeof(buffer));

        // ignore that a blank line was entered
        if (size==0)
            continue;

        // break the command into an array 
        arg_count=parse_command(buffer, '/', &args);

        if (arg_count == -1)
            continue;
        
        // add a new element to the database
        if (args[0][0]=='a' && arg_count==2 ) {

            // if the string to add is less than 10 chars, ignore the add command
            if (cgc_strlen(args[1]) < 10) {

                free(args);
                continue;
            }

            item=calloc(1, sizeof(data_item_type));

            if (!item) {

                printf("Unable to allocate memory\n");
                return(-1);
            }

            strncpy(item->name, args[1], sizeof(item->name)-1);
            item->next = 0;

            insert_node(&head, item, make_key_from_name);

        }
        // search for elements of the database
        else if (args[0][0]=='f' && arg_count==2) {

            find_matches(head, arg_count, args);

        }
        // delete an element from the database
        else if (args[0][0]=='d' && arg_count==2) {

            delete_matches(&head, arg_count, args);

        }
        // time to cgc_exit
        else if (args[0][0]=='x') {

            return(0);
        }
        // walk the database and show all entries
        else if (args[0][0]=='w' ) {

            walk_tree(head);
        }
        else if (args[0][0]=='s' ) {

            // clear the stats
            bzero(&stats, sizeof(stats));

            count_bst_stats(head, &stats);

            printf("# of Nodes: @d\n", stats.node_count);
            printf("\% left nodes: @d\n", stats.percent_left);
            printf("\% right nodes: @d\n", stats.percent_right);

        }
        
        free(args);
    }
Example #9
0
File: main.c Project: saeidw/Agros
int main (){
    int pid = 0;
    command_t cmd = {NULL, 0, {NULL}};
    char *commandline = (char *)NULL;
    char* username = NULL;
    config_t ag_config;
    int bg_cmd = AG_FALSE;
    char prompt[MAX_LINE_LEN];

    /* Sets the username */
    set_username (&username);

    /* Opens the syslog file */
    openlog (username, LOG_PID, LOG_USER);

    /* Parses the config files for data */
    parse_config (&ag_config, username);

    /* Initializes GNU Readline */
    initialize_readline(&ag_config);

    /*
     *   Main loop:
     *   - print prompt
     *   - read input and parse it
     *   - either a built-in command ("cd", "?" or "exit)
     *   - or a system command, in which case the program forks and executes it with execvp()
     */

    if (ag_config.welcome_message != NULL && strlen (ag_config.welcome_message) > 0) {
        fprintf (stdout, "\n%s\n\n", ag_config.welcome_message);
    }

    while (AG_TRUE){
	/* Set the prompt */
	get_prompt(prompt, MAX_LINE_LEN, username);

	/* 
	 * Read a line of input 
	 * commandline should be deallocated with free() 
	 */
	commandline = read_input (prompt);

        parse_command (commandline, &cmd);

        switch (get_cmd_code (cmd.name)){
            case EMPTY_CMD:
   	            break;

            case CD_CMD:
                change_directory (cmd.argv[1], ag_config.loglevel);
   	            break;

            case HELP_CMD:
                print_help(&ag_config);
   	            break;

            case ENV_CMD:
   	            print_env (cmd.argv[1]);
   	            break;

            case EXIT_CMD:
		free (commandline);
		commandline = (char *)NULL;
                closelog ();
   	            return 0;

            case OTHER_CMD:

                /* Determines whether the command should run in the bg or not */
                bg_cmd = runs_in_background (&cmd);
                pid = vfork();

   	            if (pid == 0){
                if (!check_validity (cmd, ag_config)){
                    if (ag_config.loglevel == 3)    syslog (LOG_NOTICE, "Using command: %s.", cmd.name);
                    execvp (cmd.argv[0], cmd.argv);
   	        	    fprintf (stderr, "%s: Could not execute command!\nType '?' for help.\n", cmd.name);
                    if (ag_config.loglevel >= 2)    syslog (LOG_NOTICE, "Could not execute: %s.", cmd.name);
                }else {
   	        	    fprintf (stdout, "Not allowed! \n");
                    if (ag_config.warnings >= 0)    decrease_warnings (&ag_config);
                    if (ag_config.loglevel >= 1)    syslog (LOG_ERR, "Trying to use forbidden command: %s.", cmd.name);
                }

                _exit(EXIT_FAILURE);
   	            }else if (pid < 0){
                    fprintf (stderr, "Error! ... Negative PID. God knows what that means ...\n");
                    if (ag_config.loglevel >= 1) syslog (LOG_ERR, "Negative PID. Using command: %s.", cmd.name);
   	            }else {
                    if (!bg_cmd)
                        wait (0);
   	            }
   	            break;
        }

	free (commandline);
	commandline = (char *)NULL;
    }

    if (commandline)
	free (commandline);
    closelog();
    return 0;
}
Example #10
0
parse_info *parse (char *cmdline) {
  parse_info *result;
  int i = 0;
  int pos;
  int end = 0;
  char command[MAXLINE];
  int com_pos;
  int is_comm_proper = 0;

  if (cmdline[i] == '\n' && cmdline[i] == '\0')
    return NULL;

  result = malloc(sizeof(parse_info));
  if (result == NULL) {
    return NULL;
  }
  init_info(result);
  com_pos = 0;
  while (cmdline[i] != '\n' && cmdline[i] != '\0') {
    if (cmdline[i] == '&') {
      result->bool_background = 1;
      if (cmdline[i+1] != '\n' && cmdline[i+1] != '\0')
	fprintf(stderr, "Ignore anything beyond &.\n");
      break;
    }
    else if (cmdline[i] == '<') {
      result->bool_infile = 1;
      while (isspace(cmdline[++i]));
      pos = 0;
      while (cmdline[i] != '\0' && !isspace(cmdline[i])) {
	if (pos==FILE_MAX_SIZE) {
	  fprintf(stderr, "Error.The input redirection file name exceeds the size limit 40\n");
	  free_info(result);
	  return NULL;
	}
	result->in_file[pos++] = cmdline[i++];
      }
      result->in_file[pos]='\0';
      end =1;
      while (isspace(cmdline[i])) {
	if (cmdline[i] == '\n')
	  break;
	i++;
      }
    }
    else if (cmdline[i] == '>') {
      result->bool_outfile = 1;
      while (isspace(cmdline[++i]));
      pos = 0;
      while (cmdline[i] != '\0' && !isspace(cmdline[i])) {
	if (pos==FILE_MAX_SIZE) {
	  fprintf(stderr, "Error.The output redirection file name exceeds the size limit 40\n");
	  free_info(result);
	  return NULL;
	}
	result->out_file[pos++] = cmdline[i++];
      }
      result->out_file[pos]='\0';
      end =1;
      while (isspace(cmdline[i])) {
	if (cmdline[i] == '\n') 
	  break;
	i++;
      } 
    }
    else if (cmdline[i] == '|') {
      command[com_pos]='\0';
      is_comm_proper = parse_command(command, &result->com_array[result->pipe_num]);
      if (!is_comm_proper) {
	free_info(result);
	return NULL;
      }
      com_pos = 0;
      end = 0;
      result->pipe_num++;
      i++;
    }
    else {
      if (end == 1) {
		fprintf(stderr, "Error.Wrong format of input\n");
		free_info(result);
		return NULL;
      }
      if (com_pos == MAXLINE-1) {
		fprintf(stderr, "Error. The command length exceeds the limit 80\n");
		free_info(result);
		return NULL;
      }
      command[com_pos++] = cmdline[i++];
    }
  }
  command[com_pos]='\0';
  is_comm_proper = parse_command(command, &result->com_array[result->pipe_num]);
  if (!is_comm_proper) {
    free_info(result);
    return NULL;
  }
  //Result->pipeNum++;
  return result;
}
Example #11
0
/******************************************************************************
 *                                                                            *
 * Function: send_list_of_active_checks_json                                  *
 *                                                                            *
 * Purpose: send list of active checks to the host                            *
 *                                                                            *
 * Parameters: sock - open socket of server-agent connection                  *
 *             json - request buffer                                          *
 *                                                                            *
 * Return value:  SUCCEED - list of active checks sent successfully           *
 *                FAIL - an error occurred                                    *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
int	send_list_of_active_checks_json(zbx_sock_t *sock, struct zbx_json_parse *jp)
{
	const char	*__function_name = "send_list_of_active_checks_json";
	char		host[HOST_HOST_LEN_MAX], *name_esc, params[MAX_STRING_LEN],
			pattern[MAX_STRING_LEN], tmp[32],
			key_severity[MAX_STRING_LEN], key_logeventid[MAX_STRING_LEN],
			ip[INTERFACE_IP_LEN_MAX];
	DB_RESULT	result;
	DB_ROW		row;
	struct zbx_json	json;
	int		res = FAIL, refresh_unsupported, now;
	zbx_uint64_t	hostid;
	char		error[MAX_STRING_LEN], *key = NULL;
	DC_ITEM		dc_item;
	unsigned short	port;

	char		**regexp = NULL;
	int		regexp_alloc = 0;
	int		regexp_num = 0, n;

	char		*sql = NULL;
	size_t		sql_alloc = 2 * ZBX_KIBIBYTE, sql_offset = 0;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	if (FAIL == zbx_json_value_by_name(jp, ZBX_PROTO_TAG_HOST, host, sizeof(host)))
	{
		zbx_snprintf(error, MAX_STRING_LEN, "%s", zbx_json_strerror());
		goto error;
	}

	if (FAIL == zbx_json_value_by_name(jp, ZBX_PROTO_TAG_IP, ip, sizeof(ip)))
		strscpy(ip, get_ip_by_socket(sock));

	if (FAIL == zbx_json_value_by_name(jp, ZBX_PROTO_TAG_PORT, tmp, sizeof(tmp)))
		*tmp = '\0';

	if (FAIL == is_ushort(tmp, &port))
		port = ZBX_DEFAULT_AGENT_PORT;

	if (FAIL == get_hostid_by_host(host, ip, port, &hostid, error))
		goto error;

	DCconfig_get_config_data(&refresh_unsupported, CONFIG_REFRESH_UNSUPPORTED);

	now = time(NULL);

	sql = zbx_malloc(sql, sql_alloc);

	name_esc = DBdyn_escape_string(host);

	zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset,
			"select i.key_,i.delay,i.lastlogsize,i.mtime"
			" from items i,hosts h"
			" where i.hostid=h.hostid"
				" and h.status=%d"
				" and i.type=%d"
				" and i.flags<>%d"
				" and h.hostid=" ZBX_FS_UI64
				" and h.proxy_hostid is null",
			HOST_STATUS_MONITORED,
			ITEM_TYPE_ZABBIX_ACTIVE,
			ZBX_FLAG_DISCOVERY_CHILD,
			hostid);

	zbx_free(name_esc);

	zbx_json_init(&json, ZBX_JSON_STAT_BUF_LEN);
	zbx_json_addstring(&json, ZBX_PROTO_TAG_RESPONSE, ZBX_PROTO_VALUE_SUCCESS, ZBX_JSON_TYPE_STRING);
	zbx_json_addarray(&json, ZBX_PROTO_TAG_DATA);

	result = DBselect("%s", sql);

	while (NULL != (row = DBfetch(result)))
	{
		if (FAIL == DCconfig_get_item_by_key(&dc_item, (zbx_uint64_t)0, host, row[0]))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "%s() Item '%s' was not found in the server cache. Not sending now.", __function_name, row[0]);
			continue;
		}

		if (ITEM_STATUS_NOTSUPPORTED == dc_item.status)
		{
			if (0 == refresh_unsupported || dc_item.lastclock + refresh_unsupported > now)
			{
				DCconfig_clean_items(&dc_item, NULL, 1);
				continue;
			}
		}

		zabbix_log(LOG_LEVEL_DEBUG, "%s() Item '%s' was successfully found in the server cache. Sending.", __function_name, row[0]);

		ZBX_STRDUP(key, row[0]);
		substitute_key_macros(&key, NULL, &dc_item, NULL, MACRO_TYPE_ITEM_KEY, NULL, 0);

		DCconfig_clean_items(&dc_item, NULL, 1);

		zbx_json_addobject(&json, NULL);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_KEY, key, ZBX_JSON_TYPE_STRING);
		if (0 != strcmp(key, row[0]))
			zbx_json_addstring(&json, ZBX_PROTO_TAG_KEY_ORIG, row[0], ZBX_JSON_TYPE_STRING);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_DELAY, row[1], ZBX_JSON_TYPE_INT);
		/* The agent expects ALWAYS to have lastlogsize and mtime tags. Removing those would cause older agents to fail. */
		zbx_json_addstring(&json, ZBX_PROTO_TAG_LOGLASTSIZE, row[2], ZBX_JSON_TYPE_INT);
		zbx_json_addstring(&json, ZBX_PROTO_TAG_MTIME, row[3], ZBX_JSON_TYPE_INT);
		zbx_json_close(&json);

		/* special processing for log[] and logrt[] items */
		do {	/* simple try realization */

			/* log[filename,pattern,encoding,maxlinespersec] */
			/* logrt[filename_format,pattern,encoding,maxlinespersec] */

			if (0 != strncmp(key, "log[", 4) && 0 != strncmp(key, "logrt[", 6))
				break;

			if (2 != parse_command(key, NULL, 0, params, sizeof(params)))
				break;

			/* dealing with `pattern' parameter */
			if (0 == get_param(params, 2, pattern, sizeof(pattern)) &&
				*pattern == '@')
					add_regexp_name(&regexp, &regexp_alloc, &regexp_num, pattern + 1);
		} while (0);	/* simple try realization */

		/* special processing for eventlog[] items */
		do {	/* simple try realization */

			/* eventlog[filename,pattern,severity,source,logeventid,maxlinespersec] */

			if (0 != strncmp(key, "eventlog[", 9))
				break;

			if (2 != parse_command(key, NULL, 0, params, sizeof(params)))
				break;

			/* dealing with `pattern' parameter */
			if (0 == get_param(params, 2, pattern, sizeof(pattern)) &&
				*pattern == '@')
					add_regexp_name(&regexp, &regexp_alloc, &regexp_num, pattern + 1);

			/* dealing with `severity' parameter */
			if (0 == get_param(params, 3, key_severity, sizeof(key_severity)) &&
				*key_severity == '@')
					add_regexp_name(&regexp, &regexp_alloc, &regexp_num, key_severity + 1);

			/* dealing with `logeventid' parameter */
			if (0 == get_param(params, 5, key_logeventid, sizeof(key_logeventid)) &&
				*key_logeventid == '@')
					add_regexp_name(&regexp, &regexp_alloc, &regexp_num, key_logeventid + 1);
		} while (0);	/* simple try realization */

		zbx_free(key);
	}
	zbx_json_close(&json);

	DBfree_result(result);

	if (0 != regexp_num)
	{
		zbx_json_addarray(&json, ZBX_PROTO_TAG_REGEXP);

		sql_offset = 0;
		zbx_strcpy_alloc(&sql, &sql_alloc, &sql_offset,
				"select r.name,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive"
				" from regexps r,expressions e"
				" where r.regexpid=e.regexpid"
					" and r.name in (");

		for (n = 0; n < regexp_num; n++)
		{
			name_esc = DBdyn_escape_string(regexp[n]);
			zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "%s'%s'",
					n == 0 ? "" : ",",
					name_esc);
			zbx_free(name_esc);
			zbx_free(regexp[n]);
		}
		zbx_chrcpy_alloc(&sql, &sql_alloc, &sql_offset, ')');

		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, DB_NODE, DBnode_local("r.regexpid"));

		result = DBselect("%s", sql);
		while (NULL != (row = DBfetch(result)))
		{
			zbx_json_addobject(&json, NULL);
			zbx_json_addstring(&json, "name", row[0], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "expression", row[1], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "expression_type", row[2], ZBX_JSON_TYPE_INT);
			zbx_json_addstring(&json, "exp_delimiter", row[3], ZBX_JSON_TYPE_STRING);
			zbx_json_addstring(&json, "case_sensitive", row[4], ZBX_JSON_TYPE_INT);
			zbx_json_close(&json);
		}
		DBfree_result(result);
	}
	zbx_free(regexp);

	zabbix_log(LOG_LEVEL_DEBUG, "%s() sending [%s]", __function_name, json.buffer);

	alarm(CONFIG_TIMEOUT);
	if (SUCCEED != zbx_tcp_send(sock, json.buffer))
		strscpy(error, zbx_tcp_strerror());
	else
		res = SUCCEED;
	alarm(0);

	zbx_json_free(&json);
	zbx_free(sql);

	goto out;
error:
	zabbix_log(LOG_LEVEL_WARNING, "cannot send list of active checks to [%s]: %s", get_ip_by_socket(sock), error);

	zbx_json_init(&json, ZBX_JSON_STAT_BUF_LEN);
	zbx_json_addstring(&json, ZBX_PROTO_TAG_RESPONSE, ZBX_PROTO_VALUE_FAILED, ZBX_JSON_TYPE_STRING);
	zbx_json_addstring(&json, ZBX_PROTO_TAG_INFO, error, ZBX_JSON_TYPE_STRING);

	zabbix_log(LOG_LEVEL_DEBUG, "%s() sending [%s]", __function_name, json.buffer);

	res = zbx_tcp_send(sock, json.buffer);

	zbx_json_free(&json);
out:
	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(res));

	return res;
}
Example #12
0
int main(int argc, char **argv)
{
	int listenfd, connfd;
	struct sockaddr_un servaddr;
	int clilen;
	bool do_fork = true;
	bool no_wait = false;
	doLoop=true;

	dprintf("startup!!!\n\n");
	if(argc > 1)
	{
		for(int i = 1; i < argc; i++)
		{

			if(strncmp(argv[i], "-f", 2) == 0)
			{
				do_fork = false;
			}
			else if(strncmp(argv[i], "-w", 2) == 0)
			{
				no_wait=true;
			}
		}
	}

	if(do_fork)
	{
		switch(fork())
		{
			case -1:
				perror("[timerd] fork");
				return -1;
			case 0:
				break;
			default:
				return 0;
		}
		if(setsid() == -1)
		{
			perror("[timerd] setsid");
			return -1;
		}
	}

	memset(&servaddr, 0, sizeof(struct sockaddr_un));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, TIMERD_UDS_NAME);
	clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
	unlink(TIMERD_UDS_NAME);

	//network-setup
	if((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
	{
		dperror("error while socket create");
	}

	if( bind(listenfd, (struct sockaddr*) &servaddr, clilen) <0 )
	{
		dperror("bind failed...");
		exit(-1);
	}

	if(listen(listenfd, 15) !=0)
	{
		perror("listen failed...");
		exit( -1 );
	}

	if(!no_wait)
	{
		// wait for correct date to be set...
		CSectionsdClient sectionsd;
		while(!sectionsd.getIsTimeSet())
			sleep(1);
	}
	loadTimersFromConfig();

	//startup Timer
	try
	{
		CBasicMessage::Header rmessage;
		while(doLoop)							  // wait for incomming messages
		{
			connfd = accept(listenfd, (struct sockaddr*) &servaddr, (socklen_t*) &clilen);
			memset(&rmessage, 0, sizeof(rmessage));
			read(connfd,&rmessage,sizeof(rmessage));
			parse_command(connfd, &rmessage);
			close(connfd);
		}
	}
	catch(std::exception& e)
	{
		dprintf("caught std-exception in main-thread %s!\n", e.what());
	}
	catch(...)
	{
		dprintf("caught exception in main-thread!\n");
	}
}
Example #13
0
/******************************************************************************
 *                                                                            *
 * Function: process_trap_for_interface                                       *
 *                                                                            *
 * Purpose: add trap to all matching items for the specified interface        *
 *                                                                            *
 * Return value: SUCCEED - a matching item was found                          *
 *               FAIL - no matching item was found (including fallback items) *
 *                                                                            *
 * Author: Rudolfs Kreicbergs                                                 *
 *                                                                            *
 ******************************************************************************/
static int	process_trap_for_interface(zbx_uint64_t interfaceid, char *trap, zbx_timespec_t *ts)
{
    DC_ITEM			*items = NULL;
    char			cmd[MAX_STRING_LEN], params[MAX_STRING_LEN], regex[MAX_STRING_LEN],
                    error[ITEM_ERROR_LEN_MAX];
    size_t			num, i;
    int			ret = FAIL, fb = -1, *lastclocks = NULL, *errcodes = NULL;
    zbx_uint64_t		*itemids = NULL;
    unsigned char		*states = NULL;
    AGENT_RESULT		*results = NULL;
    zbx_vector_ptr_t	regexps;

    zbx_vector_ptr_create(&regexps);

    num = DCconfig_get_snmp_items_by_interfaceid(interfaceid, &items);

    itemids = zbx_malloc(itemids, sizeof(zbx_uint64_t) * num);
    states = zbx_malloc(states, sizeof(unsigned char) * num);
    lastclocks = zbx_malloc(lastclocks, sizeof(int) * num);
    errcodes = zbx_malloc(errcodes, sizeof(int) * num);
    results = zbx_malloc(results, sizeof(AGENT_RESULT) * num);

    for (i = 0; i < num; i++)
    {
        init_result(&results[i]);
        errcodes[i] = FAIL;

        items[i].key = zbx_strdup(items[i].key, items[i].key_orig);
        if (SUCCEED != substitute_key_macros(&items[i].key, NULL, &items[i], NULL,
                                             MACRO_TYPE_ITEM_KEY, error, sizeof(error)))
        {
            SET_MSG_RESULT(&results[i], zbx_strdup(NULL, error));
            errcodes[i] = NOTSUPPORTED;
            continue;
        }

        if (0 == strcmp(items[i].key, "snmptrap.fallback"))
        {
            fb = i;
            continue;
        }

        if (ZBX_COMMAND_ERROR == parse_command(items[i].key, cmd, sizeof(cmd), params, sizeof(params)))
            continue;

        if (0 != strcmp(cmd, "snmptrap"))
            continue;

        if (1 < num_param(params))
            continue;

        if (0 != get_param(params, 1, regex, sizeof(regex)))
            continue;

        if ('@' == *regex)
            DCget_expressions_by_name(&regexps, regex + 1);

        if (SUCCEED != regexp_match_ex(&regexps, trap, regex, ZBX_CASE_SENSITIVE))
            continue;

        if (SUCCEED == set_result_type(&results[i], items[i].value_type, items[i].data_type, trap))
            errcodes[i] = SUCCEED;
        else
            errcodes[i] = NOTSUPPORTED;
        ret = SUCCEED;
    }

    if (FAIL == ret && -1 != fb)
    {
        if (SUCCEED == set_result_type(&results[fb], items[fb].value_type, items[fb].data_type, trap))
            errcodes[fb] = SUCCEED;
        else
            errcodes[fb] = NOTSUPPORTED;
        ret = SUCCEED;
    }

    for (i = 0; i < num; i++)
    {
        switch (errcodes[i])
        {
        case SUCCEED:
            if (ITEM_VALUE_TYPE_LOG == items[i].value_type)
            {
                calc_timestamp(results[i].logs[0]->value, &results[i].logs[0]->timestamp,
                               items[i].logtimefmt);
            }

            items[i].state = ITEM_STATE_NORMAL;
            dc_add_history(items[i].itemid, items[i].value_type, items[i].flags, &results[i],
                           ts, items[i].state, NULL);

            itemids[i] = items[i].itemid;
            states[i] = items[i].state;
            lastclocks[i] = ts->sec;
            break;
        case NOTSUPPORTED:
            items[i].state = ITEM_STATE_NOTSUPPORTED;
            dc_add_history(items[i].itemid, items[i].value_type, items[i].flags, NULL,
                           ts, items[i].state, results[i].msg);

            itemids[i] = items[i].itemid;
            states[i] = items[i].state;
            lastclocks[i] = ts->sec;
            break;
        }

        zbx_free(items[i].key);
        free_result(&results[i]);
    }

    zbx_free(results);

    DCrequeue_items(itemids, states, lastclocks, NULL, NULL, errcodes, num);

    zbx_free(errcodes);
    zbx_free(lastclocks);
    zbx_free(states);
    zbx_free(itemids);

    DCconfig_clean_items(items, NULL, num);
    zbx_free(items);

    zbx_regexp_clean_expressions(&regexps);
    zbx_vector_ptr_destroy(&regexps);

    dc_flush_history();

    return ret;
}
Example #14
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct GParams *params;

    int i, ret;
    int red, grn, blu;
    float size;
    double vp_height, z_exag;	/* calculated viewpoint height, z-exag */
    int width, height;		/* output image size */
    char *output_name;

    nv_data data;
    struct render_window *offscreen;

    /* initialize GRASS */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("visualization"));
    G_add_keyword(_("graphics"));
    G_add_keyword(_("raster"));
    G_add_keyword(_("vector"));
    G_add_keyword(_("raster3d"));
    module->label = _("Creates a 3D rendering of GIS data.");
    module->description = _("Renders surfaces (raster data), "
			    "2D/3D vector data, and "
			    "volumes (3D raster data) in 3D.");

    params = (struct GParams *)G_malloc(sizeof(struct GParams));

    /* define options, call G_parser() */
    parse_command(argc, argv, params);

    /* check parameters consistency */
    check_parameters(params);

    width = atoi(params->size->answers[0]);
    height = atoi(params->size->answers[1]);
    G_asprintf(&output_name, "%s.%s", params->output->answer,
	       params->format->answer);

    GS_libinit();
    GVL_libinit();

    GS_set_swap_func(swap_gl);

    /* define render window */
    offscreen = Nviz_new_render_window();
    Nviz_init_render_window(offscreen);
    if (Nviz_create_render_window(offscreen, NULL, width, height) == -1)
	G_fatal_error(_("Unable to render data"));
    Nviz_make_current_render_window(offscreen);

    /* initialize nviz data */
    Nviz_init_data(&data);

    /* define default attributes for map objects */
    Nviz_set_surface_attr_default();

    /* set background color */
    Nviz_set_bgcolor(&data, Nviz_color_from_str(params->bgcolor->answer));

    /* init view, lights */
    Nviz_init_view(&data);

    /* load raster maps (surface topography) & set attributes (map/constant) */
    load_rasters(params, &data);

    /* set draw mode of loaded surfaces */
    surface_set_draw_mode(params);

    /* load line vector maps */
    if (params->vlines->answer) {
	load_vlines(params, &data);
	/* set attributes of 2d lines */
	vlines_set_attrb(params);
    }

    /* load point vector maps */
    if (params->vpoints->answer) {
	load_vpoints(params, &data);
	/* set attributes for points */
	vpoints_set_attrb(params);
    }

    /* load volumes */
    if (params->volume->answer) {
	load_rasters3d(params, &data);
    }

    /* define isosurfaces for displaying volumes */
    if (params->isosurf_level->answer) {
	add_isosurfs(params, &data);
    }

    /* define slices for displaying volumes */
    if (params->slice->answer) {
	add_slices(params, &data);
    }

    /* focus on loaded data */
    Nviz_set_focus_map(MAP_OBJ_UNDEFINED, -1);

    /* define view point */
    if (params->exag->answer) {
	z_exag = atof(params->exag->answer);
    }
    else {
	z_exag = Nviz_get_exag();
	G_verbose_message(_("Vertical exaggeration not given, using calculated "
			   "value %.0f"), z_exag);
    }
    Nviz_change_exag(&data, z_exag);

    if (params->height->answer) {
	vp_height = atof(params->height->answer);
    }
    else {
	double min, max;

	Nviz_get_exag_height(&vp_height, &min, &max);
	G_verbose_message(_("Viewpoint height not given, using calculated "
			    "value %.0f"), vp_height);
    }
    Nviz_set_viewpoint_height(vp_height);

    Nviz_set_viewpoint_position(atof(params->pos->answers[0]),
				atof(params->pos->answers[1]));
    Nviz_set_viewpoint_twist(atoi(params->twist->answer));
    Nviz_set_viewpoint_persp(atoi(params->persp->answer));

    if (params->focus->answer) {
	Nviz_set_focus(&data, atof(params->focus->answers[0]),
		       atof(params->focus->answers[1]),
		       atof(params->focus->answers[2]));
    }

    /* set lights */
    Nviz_set_light_position(&data, 1,
			    atof(params->light_pos->answers[0]),
			    atof(params->light_pos->answers[1]),
			    atof(params->light_pos->answers[2]), 0.0);
    Nviz_set_light_bright(&data, 1,
			  atoi(params->light_bright->answer) / 100.0);
    if (G_str_to_color(params->light_color->answer, &red, &grn, &blu) != 1) {
	red = grn = blu = 255;
    }
    Nviz_set_light_color(&data, 1, red, grn, blu);
    Nviz_set_light_ambient(&data, 1,
			   atof(params->light_ambient->answer) / 100.0);

    /* define fringes */
    if (params->fringe->answer) {
	int nw, ne, sw, se;

	i = 0;
	nw = ne = sw = se = 0;
	while (params->fringe->answers[i]) {
	    const char *edge = params->fringe->answers[i++];

	    if (strcmp(edge, "nw") == 0)
		nw = 1;
	    else if (strcmp(edge, "ne") == 0)
		ne = 1;
	    else if (strcmp(edge, "sw") == 0)
		sw = 1;
	    else if (strcmp(edge, "se") == 0)
		se = 1;
	}
	Nviz_new_fringe(&data, -1,
			Nviz_color_from_str(params->fringe_color->answer),
			atof(params->fringe_elev->answer), nw, ne, sw, se);
    }

    /* draw north arrow */
    if (params->north_arrow->answer) {

	if (!params->north_arrow_size->answer)
	    size = Nviz_get_longdim(&data) / 8.;
	else
	    size = atof(params->north_arrow_size->answer);

	Nviz_set_arrow(&data, atoi(params->north_arrow->answers[0]),
		       atoi(params->north_arrow->answers[1]),
		       size,
		       Nviz_color_from_str(params->north_arrow_color->
					   answer));
	Nviz_draw_arrow(&data);
    }

    GS_clear(data.bgcolor);

    /* cutting planes */
    if (params->cplane->answer)
	draw_cplane(params, &data);

    /* draw */
    Nviz_draw_all(&data);

    /* write to image */
    ret = 0;
    if (strcmp(params->format->answer, "ppm") == 0)
	ret = write_img(output_name, FORMAT_PPM);
    if (strcmp(params->format->answer, "tif") == 0)
	ret = write_img(output_name, FORMAT_TIF);

    if (!ret)
	G_fatal_error(_("Unsupported output format"));

    G_done_msg(_("File <%s> created."), output_name);

    Nviz_destroy_data(&data);
    Nviz_destroy_render_window(offscreen);

    G_free((void *)output_name);
    G_free((void *)params);

    exit(EXIT_SUCCESS);
}
Example #15
0
int main(int argc, char *argv[])
{
    struct server_settings settings = {30000, 0, 1};
    handle_arguments(argc, argv, &settings);

    struct player_character hero;
    init_player_character(&hero);

    char stat_buffer[256];

    randomize_player_character_stats(&hero);
    snprintf(stat_buffer, 255, "STR - %i\r\nDEX - %i\r\nCON - %i\r\n", hero.strength, hero.dexterity, hero.constitution);

    if (catch_signal(SIGINT, handle_shutdown) == -1) {
        error("Can't set the interrupt handler");
    } else if (settings.verbose) {
        puts("Interrupt handler set");
    }

    listener_d = open_listener_socket();
    bind_to_port(listener_d, settings.port_number);

    if (listen(listener_d, 10) == -1) {
        error("Can't listen");
    } else if (settings.verbose) {
        printf("Listening on port %i", settings.port_number);
    }

    struct sockaddr_storage client_addr;
    unsigned int address_size = sizeof(client_addr);
    if (settings.verbose) {
        puts("Waiting for connection");
    }

    while(1) {
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &address_size);
        if (connect_d == -1) {
            error("Can't open secondary socket");
        } else if (settings.verbose) {
            puts("New connection started");
        }

        if (!fork()) {
            close(listener_d); char input_buffer[512];
            char output_buffer[512];
            char send_buffer[512];
            char action_buffer[3];
            

            send_version(connect_d);

            while (1) {
                get_command(connect_d, action_buffer);
                puts(action_buffer);
                if (action_buffer[0] == 's') {
                    puts("opening chat buffer");
                    listen_to_client(connect_d, input_buffer);
                    parse_command(input_buffer, output_buffer);
                    sprintf(send_buffer, "You said: \"%s\"\r\n", output_buffer);
                    puts(send_buffer);
                    send_to_client(connect_d, send_buffer);
                } else {
                    handle_user_command(connect_d, action_buffer);
                }
            }

            close(connect_d);
            exit(0);
        }
        close(connect_d);
    }

    return 0;
}
Example #16
0
parseInfo *parse (char *cmdline) {
  parseInfo *Result;
  int i=0;
  int pos;
  int end=0;
  char command[MAXLINE];
  int com_pos;

  if (cmdline[i] == '\n' && cmdline[i] == '\0')
    return NULL;

  Result = malloc(sizeof(parseInfo));
  if (Result == NULL){
    return NULL;
  }
  init_info(Result);
  com_pos=0;
  while (cmdline[i] != '\n' && cmdline[i] != '\0') {
    if (cmdline[i] == '&') {
      Result->boolBackground=1;
      if (cmdline[i+1] != '\n' && cmdline[i+1] != '\0') {
	fprintf(stderr, "Ignore anything beyond &.\n");
      }
      break;
    }
    else if (cmdline[i] == '<') {
      Result->boolInfile=1;
      while (isspace(cmdline[++i]));
      pos=0;
      while (cmdline[i] != '\0' && !isspace(cmdline[i])) {
	if (pos==FILE_MAX_SIZE) {
	  fprintf(stderr, "Error.The input redirection file name exceeds the size limit 40\n");
	  free_info(Result);
	  return NULL;
	}
	Result->inFile[pos++] = cmdline[i++];
      }
      Result->inFile[pos]='\0';
      end =1;
      while (isspace(cmdline[i])) {
	if (cmdline[i] == '\n') 
	  break;
	i++;
      }
    }
    else if (cmdline[i] == '>') {
      Result->boolOutfile=1;
      while (isspace(cmdline[++i]));
      pos=0;
      while (cmdline[i] != '\0' && !isspace(cmdline[i])) {
	if (pos==FILE_MAX_SIZE) {
	  fprintf(stderr, "Error.The output redirection file name exceeds the size limit 40\n");
	  free_info(Result);
	  return NULL;
	}
	Result->outFile[pos++] = cmdline[i++];
      }
      Result->outFile[pos]='\0';
      end =1;
      while (isspace(cmdline[i])) {
	if (cmdline[i] == '\n') 
	  break;
	i++;
      } 
    }
    else if (cmdline[i] == '|') {
      command[com_pos]='\0';
      parse_command(command, &Result->CommArray[Result->pipeNum]);
      com_pos=0;
      end =0;
      Result->pipeNum++;
      i++;
    }
    else {
      if (end == 1) {
	 fprintf(stderr, "Error.Wrong format of input\n");
	 free_info(Result);
	 return NULL;
      }
      if (com_pos == MAXLINE-1) {
	fprintf(stderr, "Error. The command length exceeds the limit 80\n");
	free_info(Result);
	return NULL;
      }
      command[com_pos++] = cmdline[i++];
    }
  }
  command[com_pos]='\0';
  parse_command(command, &Result->CommArray[Result->pipeNum]);
  /*Result->pipeNum++;*/
  return Result;
}
Example #17
0
void 
psplash_main (PSplashFB *fb, int pipe_fd, int timeout) 
{
  int            err;
  ssize_t        length = 0;
  fd_set         descriptors;
  struct timeval tv;
  char          *end;
  char           command[2048];

  tv.tv_sec = timeout;
  tv.tv_usec = 0;

  FD_ZERO(&descriptors);
  FD_SET(pipe_fd, &descriptors);

  end = command;

  while (1) 
    {
      if (timeout != 0) 
	err = select(pipe_fd+1, &descriptors, NULL, NULL, &tv);
      else
	err = select(pipe_fd+1, &descriptors, NULL, NULL, NULL);
      
      if (err <= 0) 
	{
	  /*
	  if (errno == EINTR)
	    continue;
	  */
	  return;
	}
      
      length += read (pipe_fd, end, sizeof(command) - (end - command));

      if (length == 0) 
	{
	  /* Reopen to see if there's anything more for us */
	  close(pipe_fd);
	  pipe_fd = open(PSPLASH_FIFO,O_RDONLY|O_NONBLOCK);
	  goto out;
	}
      
      if (command[length-1] == '\0') 
	{
	  if (parse_command(fb, command, strlen(command))) 
	    return;
	  length = 0;
	} 
      else if (command[length-1] == '\n') 
	{
	  command[length-1] = '\0';
	  if (parse_command(fb, command, strlen(command))) 
	    return;
	  length = 0;
	} 


    out:
      end = &command[length];
    
      tv.tv_sec = timeout;
      tv.tv_usec = 0;
      
      FD_ZERO(&descriptors);
      FD_SET(pipe_fd,&descriptors);
    }

  return;
}
Example #18
0
static const char* parse_dispatch_cmd(client_conn_t *conn, struct fd_buf *buf, size_t *ppos, int *error, const struct optstruct *opts, int readtimeout)
{
    const char *cmd = NULL;
    int rc;
    size_t cmdlen;
    char term;
    int oldstyle;
    size_t pos = *ppos;
    /* Parse & dispatch commands */
    while ((conn->mode == MODE_COMMAND) &&
	   (cmd = get_cmd(buf, pos, &cmdlen, &term, &oldstyle)) != NULL) {
	const char *argument;
	enum commands cmdtype;
	if (conn->group && oldstyle) {
	    logg("$Received oldstyle command inside IDSESSION: %s\n", cmd);
	    conn_reply_error(conn, "Only nCMDS\\n and zCMDS\\0 are accepted inside IDSESSION.");
	    *error = 1;
	    break;
	}
	cmdtype = parse_command(cmd, &argument, oldstyle);
	logg("$got command %s (%u, %u), argument: %s\n",
	     cmd, (unsigned)cmdlen, (unsigned)cmdtype, argument ? argument : "");
	if (cmdtype == COMMAND_FILDES) {
	    if (buf->buffer + buf->off <= cmd + strlen("FILDES\n")) {
		/* we need the extra byte from recvmsg */
		conn->mode = MODE_WAITANCILL;
		buf->mode = MODE_WAITANCILL;
		/* put term back */
		buf->buffer[pos + cmdlen] = term;
		cmdlen = 0;
		logg("$RECVTH: mode -> MODE_WAITANCILL\n");
		break;
	    }
	    /* eat extra \0 for controlmsg */
	    cmdlen++;
	    logg("$RECVTH: FILDES command complete\n");
	}
	conn->term = term;
	buf->term = term;

	if ((rc = execute_or_dispatch_command(conn, cmdtype, argument)) < 0) {
	    logg("!Command dispatch failed\n");
	    if(rc == -1 && optget(opts, "ExitOnOOM")->enabled) {
		pthread_mutex_lock(&exit_mutex);
		progexit = 1;
		pthread_mutex_unlock(&exit_mutex);
	    }
	    *error = 1;
	}
	if (thrmgr_group_need_terminate(conn->group)) {
	    logg("$Receive thread: have to terminate group\n");
	    *error = CL_ETIMEOUT;
	    break;
	}
	if (*error || !conn->group || rc) {
	    if (rc && thrmgr_group_finished(conn->group, EXIT_OK)) {
		logg("$Receive thread: closing conn (FD %d), group finished\n", conn->sd);
		/* if there are no more active jobs */
		shutdown(conn->sd, 2);
		closesocket(conn->sd);
		buf->fd = -1;
		conn->group = NULL;
	    } else if (conn->mode != MODE_STREAM) {
		logg("$mode -> MODE_WAITREPLY\n");
		/* no more commands are accepted */
		conn->mode = MODE_WAITREPLY;
		/* Stop monitoring this FD, it will be closed either
		 * by us, or by the scanner thread. 
		 * Never close a file descriptor that is being
		 * monitored by poll()/select() from another thread,
		 * because this can lead to subtle bugs such as:
		 * Other thread closes file descriptor -> POLLHUP is
		 * set, but the poller thread doesn't wake up yet.
		 * Another client opens a connection and sends some
		 * data. If the socket reuses the previous file descriptor,
		 * then POLLIN is set on the file descriptor too.
		 * When poll() wakes up it sees POLLIN | POLLHUP
		 * and thinks that the client has sent some data,
		 * and closed the connection, so clamd closes the
		 * connection in turn resulting in a bug.
		 *
		 * If we wouldn't have poll()-ed the file descriptor
		 * we closed in another thread, but rather made sure
		 * that we don't put a FD that we're about to close
		 * into poll()'s list of watched fds; then POLLHUP
		 * would be set, but the file descriptor would stay
		 * open, until we wake up from poll() and close it.
		 * Thus a new connection won't be able to reuse the
		 * same FD, and there is no bug.
		 * */
		buf->fd = -1;
	    }
	}
	/* we received a command, set readtimeout */
	time(&buf->timeout_at);
	buf->timeout_at += readtimeout;
	pos += cmdlen+1;
	if (conn->mode == MODE_STREAM) {
	    /* TODO: this doesn't belong here */
	    buf->dumpname = conn->filename;
	    buf->dumpfd = conn->scanfd;
	    logg("$Receive thread: INSTREAM: %s fd %u\n", buf->dumpname, buf->dumpfd);
	}
	if (conn->mode != MODE_COMMAND) {
	    logg("$Breaking command loop, mode is no longer MODE_COMMAND\n");
	    break;
	}
	conn->id++;
    }
    *ppos = pos;
    buf->mode = conn->mode;
    buf->id = conn->id;
    buf->group = conn->group;
    buf->quota = conn->quota;
    if (conn->scanfd != -1 && conn->scanfd != buf->dumpfd) {
	logg("$Unclaimed file descriptor received, closing: %d\n", conn->scanfd);
	close(conn->scanfd);
	/* protocol error */
	conn_reply_error(conn, "PROTOCOL ERROR: ancillary data sent without FILDES.");
	*error = 1;
	return NULL;
    }
    if (!*error) {
	/* move partial command to beginning of buffer */
	if (pos < buf->off) {
	    memmove (buf->buffer, &buf->buffer[pos], buf->off - pos);
	    buf->off -= pos;
	} else
	    buf->off = 0;
	if (buf->off)
	    logg("$Moved partial command: %lu\n", (unsigned long)buf->off);
	else
	    logg("$Consumed entire command\n");
	/* adjust pos to account for the buffer shuffle */
	pos = 0;
    }
    *ppos = pos;
    return cmd;
}
Example #19
0
/**
 * @brief  Run command described by string stored in buffer
 *
 * @param buffer command to be executed
 *
 * @return   true on success
 */
static
void * run_command(void * p) {
	UNUSED(p);
	char ** cmd = NULL;
	int ret;
	int i = 0;
	struct parse_list_t cmd_list;
	struct parse_litem_t * it;


	pthread_mutex_lock(&buffer_mutex_exec);
	pthread_cond_wait(&buffer_cond_exec, &buffer_mutex_exec);
	while (! g_exit) {
		parse_list_init(&cmd_list);

		if (! parse_command(&cmd_list, buffer)) {
			print_error(ERR_PARSE_FAILED);
			goto signalize;
		}

		if (cmd_list.length == 1 && ! strcmp(cmd_list.head->token, CMD_EXIT)) {
			g_exit = true;
			goto signalize;
		}
		//write(1, MSG_COMMAND, strlen(MSG_COMMAND));

		if (cmd_list.length == 0) {
			goto signalize; // nothing to do
		}

		cmd = (char **) malloc((cmd_list.length + 1) * sizeof(char *));
		if (! cmd) { parse_free(&cmd_list); goto signalize; }

		for (it = cmd_list.head, i = 0; it; it = it->next, ++i) {
			//printf("cmd[%d] == %s\n", i, it->token);
			cmd[i] = it->token;
		}
		cmd[cmd_list.length] = (char *) 0;

		ret = vfork();

		if (ret < 0) {
			perror("fork failed");
		} else if (ret == 0) { // child
			// open input
			if (cmd_list.input) {
				ret = open(cmd_list.input, O_RDONLY);
				if (ret < 0) {
					perror(cmd_list.input);
					exit(EXIT_FAILURE);
				}

				if (dup2(ret, STDIN_FILENO) < 0) {
					perror("dup2 STDIN_FILENO");
					exit(EXIT_FAILURE);
				}
			} else if (cmd_list.background) {
				close(STDIN_FILENO);
			}

			// open output
			if (cmd_list.output) {
				ret = open(cmd_list.output, O_WRONLY | O_CREAT | O_TRUNC, 0666);
				if (ret < 0) {
					perror(cmd_list.output);
					exit(EXIT_FAILURE);
				}

				if (dup2(ret, STDOUT_FILENO) < 0) {
					perror("dup2 STDOUT_FILENO");
					exit(EXIT_FAILURE);
				}
			}

			/*
			 * Restore signal handlers
			 */
			signal_handler_restore();

			if (cmd_list.background) {
				pidlist_insert(&pidlist, getpid());
				fprintf(stderr, "\r>>> child %d is running in background\n", getpid());
			} else {
				// run in foreground, unblock SIGINT
				sigint_unblock();
			}

			// run it! :-*
			ret = execvp(cmd_list.head->token, cmd);
			if (ret < 0) {
				perror(cmd_list.head->token);
				exit(EXIT_FAILURE);
			}
		} else { // parent
			if (! cmd_list.background)
				waitpid(ret, NULL, 0);
		}
signalize:
		if (cmd) {
			free(cmd); cmd = NULL;
		}
		parse_free(&cmd_list);
		buffer[0] = '\0'; // mark buffer as empty
		pthread_cond_signal(&buffer_cond_read);
		if (! g_exit) // wait only if no exit signaled
			pthread_cond_wait(&buffer_cond_exec, &buffer_mutex_exec);
	} // g_exit

	pthread_mutex_unlock(&buffer_mutex_exec);

	return NULL;
}
Example #20
0
bool ScanDataBuilder::Parse(char*& buffer, size_t& size) {

    char* prev_buf = NULL;
    bool success;
    while (method_index <= 25) {
//        std::cout << "method index: " << method_index <<std::endl;
        prev_buf = buffer;
        switch (method_index) {
        case -1:
            success = parse_byte(buffer, size, lms100_cola::STX_BYTE);
            break;
        case 0:
            success = parse_command_type(buffer, size, data);
            break;
        case 1:
            success = parse_command(buffer, size, data);
            break;
        case 2:
            success = parse_version_number(buffer, size, data);
            break;
        case 3:
            success = parse_device_number(buffer, size, data);
            break;
        case 4:
            success = parse_serial_number(buffer, size, data);
            break;
        case 5:
            success = parse_device_status(buffer, size, data);
            break;
        case 6:
            success = parse_telegram_counter(buffer, size, data);
            break;
        case 7:
            success = parse_scan_counter(buffer, size, data);
            break;
        case 8:
            success = parse_time_since_startup(buffer, size, data);
            break;
        case 9:
            success = parse_time_of_transmission(buffer, size, data);
            break;
        case 10:
            success = parse_status_of_digital_inputs(buffer, size, data);
            break;
        case 11:
            success = parse_status_of_digital_outputs(buffer, size, data);
            break;
        case 12:
            success = parse_reserved_byte(buffer, size, data);
            break;
        case 13:
            success = parse_scan_frequency(buffer, size, data);
            break;
        case 14:
            success = parse_measurement_frequency(buffer, size, data);
            break;
        case 15:
            success = parse_encoders(buffer, size, data);
            break;
        case 16:
            success = parse_amount_of_16_bit_channels(buffer, size, data);
            break;
        case 17:
            success = parse_content(buffer, size, data);
            break;
        case 18:
            success = parse_scale_factor(buffer, size, data);
            break;
        case 19:
            success = parse_scale_factor_offset(buffer, size, data);
            break;
        case 20:
            success = parse_start_angle(buffer, size, data);
            break;
        case 21:
            success = parse_steps(buffer, size, data);
            break;
        case 22:
            success = parse_amount_of_data(buffer, size, data);
            break;
        case 23:
            success = parse_data(buffer, size, data);
            break;
        case 24:
            success = parse_irrelevant_data(buffer, size);
            break;
        case 25:
            success = parse_byte(buffer, size, lms100_cola::ETX_BYTE);
            break;
        default:
            return false;
        }

        // method didn't have enough data to parse
        if (!success) {
            return false;
        }

        method_index += 1;
    }

    return true;
}
Example #21
0
/**
* Parse and execute a command.
*/
int parse_command(command_t *c, int level, command_t *father, void *h)
{
  /* TODO sanity checks */

  if (c->op == OP_NONE) {
    /* TODO execute a simple command */

    /* TODO replace with actual exit code of command */
    return parse_simple(c->scmd, level, father, (HANDLE*)h);
  }

  switch (c->op) {
  case OP_SEQUENTIAL:
    /* TODO execute the commands one after the other */
    parse_command(c->cmd1, level+1, c, (HANDLE*)h);
    return parse_command(c->cmd2, level+1, c, (HANDLE*)h);
    break;

  case OP_PARALLEL:
    /* TODO execute the commands simultaneously */
    if(do_in_parallel(c->cmd1, c->cmd2, level, father)){
      return 0;
    }
    return -1;
    break;

  case OP_CONDITIONAL_NZERO:
    /* TODO execute the second command only if the first one
    * returns non zero */
    if(parse_command(c->cmd1, level+1, c, (HANDLE*)h)){
      return parse_command(c->cmd2, level+1, c, (HANDLE*)h);
    }
    break;

  case OP_CONDITIONAL_ZERO:
    /* TODO execute the second command only if the first one
    * returns zero */
    if(parse_command(c->cmd1, level+1, c, (HANDLE*)h) == FALSE){
      return parse_command(c->cmd2, level+1, c, (HANDLE*)h);
    }
    break;

  case OP_PIPE:{
    /* TODO redirect the output of the first command to the
    * input of the second */
    struct simple_command_t *cmds[100];
    unsigned int x = 0;
    if (do_on_pipe(c, level, father, cmds, &x)){
      return 0;
    }
    else{
      return -1;
    }
    break;
               }
  default:
    return SHELL_EXIT;
  }

  return 0; /* TODO replace with actual exit code of command */
}
Example #22
0
File: uzbl.c Project: dusanx/uzbl
static gboolean
key_press_cb (WebKitWebView* page, GdkEventKey* event)
{
    //TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

    (void) page;
    Action *action;

    if (event->type != GDK_KEY_PRESS || event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down
        || event->keyval == GDK_Up || event->keyval == GDK_Down || event->keyval == GDK_Left || event->keyval == GDK_Right)
        return FALSE;

    /* turn off insert mode (if always_insert_mode is not used) */
    if (insert_mode && (event->keyval == GDK_Escape)) {
        insert_mode = always_insert_mode;
        update_title();
        return TRUE;
    }

    if (insert_mode && ((event->state & modmask) != modmask))
        return FALSE;

    if (event->keyval == GDK_Escape) {
        g_string_truncate(keycmd, 0);
        update_title();
        return TRUE;
    }

    //Insert without shift - insert from clipboard; Insert with shift - insert from primary
    if (event->keyval == GDK_Insert) {
        gchar * str;
        if ((event->state & GDK_SHIFT_MASK) == GDK_SHIFT_MASK) {
            str = gtk_clipboard_wait_for_text (gtk_clipboard_get (GDK_SELECTION_PRIMARY));
        } else {
            str = gtk_clipboard_wait_for_text (gtk_clipboard_get (GDK_SELECTION_CLIPBOARD)); 
        }
        if (str) {
            g_string_append_printf (keycmd, "%s",  str);
            update_title ();
            free (str);
        }
        return TRUE;
    }

    if ((event->keyval == GDK_BackSpace) && (keycmd->len > 0)) {
        g_string_truncate(keycmd, keycmd->len - 1);
        update_title();
        return TRUE;
    }

    if ((event->keyval == GDK_Return) || (event->keyval == GDK_KP_Enter)) {
        GString* short_keys = g_string_new ("");
        unsigned int i;
        for (i=0; i<(keycmd->len); i++) {
            g_string_append_c(short_keys, keycmd->str[i]);
            g_string_append_c(short_keys, '_');
            
            //printf("\nTesting string: @%[email protected]\n", short_keys->str);
            if ((action = g_hash_table_lookup(bindings, short_keys->str))) {
                GString* parampart = g_string_new (keycmd->str);
                g_string_erase (parampart, 0, i+1);
                //printf("\nParameter: @%[email protected]\n", parampart->str);
                GString* actionname = g_string_new ("");
                if (action->name)
                    g_string_printf (actionname, action->name, parampart->str);
                GString* actionparam = g_string_new ("");
                if (action->param)
                    g_string_printf (actionparam, action->param, parampart->str);
                parse_command(actionname->str, actionparam->str);
                g_string_free (actionname, TRUE);
                g_string_free (actionparam, TRUE);
                g_string_free (parampart, TRUE);
                g_string_truncate(keycmd, 0);
                update_title();
            }          

            g_string_truncate(short_keys, short_keys->len - 1);
        }
        g_string_free (short_keys, TRUE);
        return (!insert_mode);
    }

    g_string_append(keycmd, event->string);
    if ((action = g_hash_table_lookup(bindings, keycmd->str))) {
        g_string_truncate(keycmd, 0);
        parse_command(action->name, action->param);
    }

    update_title();

    return TRUE;
}
Example #23
0
static void	process_active_checks(char *server, unsigned short port)
{
	register int	i, s_count, p_count;
	char		**pvalue;
	int		now, send_err = SUCCEED, ret;
	unsigned long	timestamp;
	char		*source = NULL;
	char		*value = NULL;
	unsigned short	severity;
	long		lastlogsize;
	char		params[MAX_STRING_LEN];
	char		filename[MAX_STRING_LEN];
	char		pattern[MAX_STRING_LEN];

	AGENT_RESULT	result;

	zabbix_log( LOG_LEVEL_DEBUG, "In process_active_checks('%s',%u)",server, port);

	init_result(&result);

	now = (int)time(NULL);

	for(i=0; NULL != active_metrics[i].key && SUCCEED == send_err; i++)
	{
		if(active_metrics[i].nextcheck > now)			continue;
		if(active_metrics[i].status != ITEM_STATUS_ACTIVE)	continue;

		/* Special processing for log files */
		if(strncmp(active_metrics[i].key,"log[",4) == 0)
		{
			do{ /* simple try realization */
				if (parse_command(active_metrics[i].key, NULL, 0, params, MAX_STRING_LEN) != 2)
					break;
				
				if (num_param(params) > 2)
					break;

				if (get_param(params, 1, filename, sizeof(filename)) != 0)
					break;

				if (get_param(params, 2, pattern, sizeof(pattern)) != 0)
					*pattern = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;
				while (SUCCEED == (ret = process_log(filename, &lastlogsize, &value))) {
					if (!value) /* EOF */
						break;

					if (SUCCEED == regexp_match_ex(regexps, regexps_num, value, pattern, ZBX_CASE_SENSITIVE)) {
						send_err = process_value(
									server,
									port,
									CONFIG_HOSTNAME,
									active_metrics[i].key_orig,
									value,
									&lastlogsize,
									NULL,
									NULL,
									NULL
								);
						s_count++;
					}
					p_count++;

					zbx_free(value);

					if (SUCCEED == send_err)
						active_metrics[i].lastlogsize = lastlogsize;
					else
						lastlogsize = active_metrics[i].lastlogsize;

					/* Do not flood ZABBIX server if file grows too fast */
					if(s_count >= (MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;

					/* Do not flood local system if file grows too fast */
					if(p_count >= (4 * MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;
				}

				if( FAIL == ret )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.",
						active_metrics[i].key);

					send_err = process_value(
								server,
								port,
								CONFIG_HOSTNAME,
								active_metrics[i].key_orig,
								"ZBX_NOTSUPPORTED",
								&active_metrics[i].lastlogsize,
								NULL,
								NULL,
								NULL
							);
				}

			}while(0); /* simple try realization */
		}
		/* Special processing for eventlog */
		else if(strncmp(active_metrics[i].key,"eventlog[",9) == 0)
		{
			do{ /* simple try realization */
				if (parse_command(active_metrics[i].key, NULL, 0, params, MAX_STRING_LEN) != 2)
					break;
				
				if (num_param(params) > 2)
					break;

				if (get_param(params, 1, filename, sizeof(filename)) != 0)
					break;

				if (get_param(params, 2, pattern, sizeof(pattern)) != 0)
					*pattern = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;
				while (SUCCEED == (ret = process_eventlog(filename, &lastlogsize,
					&timestamp, &source, &severity, &value)))
				{
					if (!value) /* EOF */
						break;

					if (SUCCEED == regexp_match_ex(regexps, regexps_num, value, pattern, ZBX_CASE_SENSITIVE)) {
						send_err = process_value(
									server,
									port,
									CONFIG_HOSTNAME,
									active_metrics[i].key_orig,
									value,
									&lastlogsize,
									&timestamp,
									source,
									&severity
								);
						s_count++;
					}
					p_count++;

					zbx_free(source);
					zbx_free(value);

					if (SUCCEED == send_err)
						active_metrics[i].lastlogsize = lastlogsize;
					else
						lastlogsize = active_metrics[i].lastlogsize;

					/* Do not flood ZABBIX server if file grows too fast */
					if(s_count >= (MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;

					/* Do not flood local system if file grows too fast */
					if(p_count >= (4 * MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;
				}

				if( FAIL == ret )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.",
						active_metrics[i].key);

					send_err = process_value(
								server,
								port,
								CONFIG_HOSTNAME,
								active_metrics[i].key_orig,
								"ZBX_NOTSUPPORTED",
								&active_metrics[i].lastlogsize,
								NULL,
								NULL,
								NULL
							);
				}
			}while(0); /* simple try realization NOTE: never loop */
		}
		else
		{
			
			process(active_metrics[i].key, 0, &result);

			if( NULL == (pvalue = GET_TEXT_RESULT(&result)) )
				pvalue = GET_MSG_RESULT(&result);

			if(pvalue)
			{
				zabbix_log( LOG_LEVEL_DEBUG, "For key [%s] received value [%s]", active_metrics[i].key, *pvalue);

				send_err = process_value(
						server,
						port,
						CONFIG_HOSTNAME,
						active_metrics[i].key_orig,
						*pvalue,
						NULL,
						NULL,
						NULL,
						NULL
					);
				
				if( 0 == strcmp(*pvalue,"ZBX_NOTSUPPORTED") )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.", active_metrics[i].key);
				}
			}

			free_result(&result);
		}
		active_metrics[i].nextcheck = (int)time(NULL)+active_metrics[i].refresh;
	}
}
Example #24
0
int parse_data_module( DATAModule *module ) {
  int data_count;
  bool fatalError = TRUE; // if true, catch leads to exit(-1)
  try {
    data_count = module->datas_count;
    for ( int i = 0; i < module->datas_count; i++ ) {
      DataContext ctx; data_context = &ctx;

      const char *tagName = module->datas[i]->tag->image;
      const int tagId = find_tag( tagName );
      if ( DATA_VERBOSE > 4 ) {
	printf("tagName: %s  tagId: %d\n\r", tagName, tagId );
      }
      switch ( tagId ) {
      case TAG_Prereq: parse_prerequisite( module->datas[i] ); break;
      case TAG_BrewFormula: 
	create_brew_formula_table( module->datas_count ); 
	parse_brew_formula( module->datas[i] ); 
	break;
      case TAG_Ban: parse_ban( module->datas[i] ); break;
      case TAG_Command:
	create_command_table( module->datas_count );
	parse_command( module->datas[i] );
	break;
      case TAG_Unique: parse_unique( module->datas[i] ); break;
      case TAG_Disable: parse_disabled( module->datas[i] ); break;
      case TAG_Material: 
	create_material_table( module->datas_count );
	parse_material( module->datas[i] );
	break;
      case TAG_Liquid:
	create_liquid_table( module->datas_count );
	parse_liquid( module->datas[i] );
	break;
      case TAG_God:
	create_god_table( module->datas_count );
	parse_god( module->datas[i] );
	break;
      case TAG_Clan: parse_clan( module->datas[i] ); break;
      case TAG_Faction:
	create_faction_table( module->datas_count, module );
	parse_faction( module->datas[i] );
	break;
      case TAG_Race:
	create_races_table( module->datas_count );
	parse_race( module->datas[i] );
	break;
      case TAG_PCRace:
	create_pcraces_table( module->datas_count );
	parse_pcrace( module->datas[i] );
	break;
      case TAG_Sphere:
	create_spheres_table( module->datas_count );
	parse_sphere( module->datas[i] );
	break;
      case TAG_Group:
	create_groups_table( module->datas_count );
	parse_groups( module->datas[i] );
	break;
      case TAG_Ability: parse_abilities( module->datas[i] ); break;
      case TAG_Class: 
	create_classes_table( module->datas_count );
	parse_classes( module->datas[i] );
	break;
      case TAG_Player: 
	fatalError = FALSE;
	parse_player( module->datas[i] );
	fatalError = TRUE;
	break;
      case TAG_Area: parse_area( module->datas[i] ); break;
      case TAG_Config:
	if ( parse_config( module->datas[i] ) )  // once we have found the right config: skip others
	  return data_count;
	break;
      case TAG_AreaState: parse_area_state( module->datas[i] ); break;
      case TAG_Time: parse_time( module->datas[i] ); break;
      case TAG_Hometown:
	create_hometown_table( module->datas_count );
	parse_hometown( module->datas[i] );
	break;
      case TAG_School:
	create_school_table( module->datas_count );
	parse_school( module->datas[i] );
	break;
      case TAG_Super_Race:
	create_super_race_table( module->datas_count );
	parse_super_race( module->datas[i] );
	break;

      default: p_error("Invalid Tag: %s", tagName ); break;
      }

    }
  } catch (ScriptException e) {
    bug("Error while parsing datas. %s", e.msg );
    if ( fatalError ) {
      bug("FATAL error. Bye!");
      exit(-1);
    }
    else
      return -1;
  }

  dump_GC_info();

  return data_count;
}
Example #25
0
/* try to complete current command line
 */
static int complete_command_line(tinysh_cmd_t *cmd, uchar *_str)
{
  uchar *str=_str;

  while(1)
    {
      int ret;
      int common_len=BUFFER_SIZE;
      int _str_len;
      int i;
      uchar *__str=str;

      tinysh_cmd_t *_cmd=cmd;
      ret=parse_command(&cmd,&str);
      for(_str_len=0;__str[_str_len]&&__str[_str_len]!=' ';_str_len++);
      if(ret==MATCH && *str)
        {
          cmd=cmd->child;
        }
      else if(ret==AMBIG || ret==MATCH || ret==NULLMATCH)
        {
          tinysh_cmd_t *cm;
          tinysh_cmd_t *matched_cmd=0;
          int nb_match=0;

          for(cm=cmd;cm;cm=cm->next)
            {
              int r=strstart(cm->name,__str);
              if(r==FULLMATCH)
                {
                  for(i=_str_len;cmd->name[i];i++)
                    tinysh_char_in(cmd->name[i]);
                  if(*(str-1)!=' ')
                    tinysh_char_in(' ');
                  if(!cmd->child)
                    {
                      if(cmd->usage)
                        {
                          puts(cmd->usage);
                          putchar('\n');
                          return 1;
                        }
                      else
                        return 0;
                    }
                  else
                    {
                      cmd=cmd->child;
                      break;
                    }
                }
              else if(r==PARTMATCH)
                {
                  nb_match++;
                  if(!matched_cmd)
                    {
                      matched_cmd=cm;
                      common_len=strlen(cm->name);
                    }
                  else
                    {
                      for(i=_str_len;cm->name[i] && i<common_len &&
                            cm->name[i]==matched_cmd->name[i];i++);
                      if(i<common_len)
                        common_len=i;
                    }
                }
            }
          if(cm)
            continue;
          if(matched_cmd)
            {
              if(_str_len==common_len)
                {
                  putchar('\n');
                  for(cm=cmd;cm;cm=cm->next)
                    {
                      int r=strstart(cm->name,__str);
                      if(r==FULLMATCH || r==PARTMATCH)
                        {
                          puts(cm->name);
                          putchar('\n');
                        }
                    }
                  return 1;
                }
              else
                {
                  for(i=_str_len;i<common_len;i++)
                    tinysh_char_in(matched_cmd->name[i]);
                  if(nb_match==1)
                    tinysh_char_in(' ');
                }
            }
          return 0;
        }
      else /* UNMATCH */
        {
          return 0;
        }
    }
}
Example #26
0
int CLCDD::main(int argc, char **argv)
{
	debugoutput = true;
	printf("Network LCD-Driver $Id: lcdd.cpp,v 1.57 2002/10/17 10:16:35 thegoodguy Exp $\n\n");

	InitNewClock();

	loadConfig();

	if(!lcdPainter.init())
	{
		//fehler beim lcd-init aufgetreten
		return -1;
	}

	//network-setup
	int listenfd, connfd;
	struct sockaddr_un servaddr;
	int clilen;

	std::string filename = LCDD_UDS_NAME;

	memset(&servaddr, 0, sizeof(struct sockaddr_un));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, filename.c_str());
	clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
	unlink(filename.c_str());

	//network-setup
	if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		return -1;
	}

	if ( bind(listenfd, (struct sockaddr*) &servaddr, clilen) <0 )
	{
		perror("[lcdd] bind failed...\n");
		return -1;
	}

	if (listen(listenfd, 5) !=0)
	{
		perror("[lcdd] listen failed...\n");
		return -1;
	}

	switch (fork())
	{
		case -1: /* can't fork */
			perror("[lcdd] fork");
			return -1;

		case 0: /* child, process becomes a daemon */
			if (setsid() == -1)
			{
				perror("[lcdd] setsid");
				return -1;
			}
			break;

		default: /* parent returns to calling process */
			return 0;
	}

	signal(SIGHUP,sig_catch);
	signal(SIGINT,sig_catch);
	signal(SIGQUIT,sig_catch);
	signal(SIGTERM, sig_catch);

	/* Thread erst nach dem forken erstellen, da sonst Abbruch */
	if (pthread_create (&thrTime, NULL, TimeThread, NULL) != 0 )
	{
		perror("[lcdd]: pthread_create(TimeThread)");
		return -1;
	}

	shall_exit = false;
	while(!shall_exit)
	{
		connfd = accept(listenfd, (struct sockaddr*) &servaddr, (socklen_t*) &clilen);
		CLcddMsg::Header rmsg;
		read(connfd,&rmsg,sizeof(rmsg));
		parse_command(connfd, rmsg);
		close(connfd);
	}
	close(listenfd);
	saveConfig();
	return 0;
}
Example #27
0
void puerto_interp(CHAR_DATA *ch, char *cmd)
{
    char buf[CMD_LEN];
    char *p = cmd; // + sizeof(pmsg_len);
    char out_buf[MAX_STRING_LENGTH];
    char *c;
    char name[NAME_LEN];
    unsigned short gnum;

// used in CMD_GAME_VIEW
    char gov[NAME_LEN], cur[NAME_LEN];
    struct game_data gdata;
    int i;
    bool first_found = FALSE;


#if defined(PRDEBUG)
    bug("Processing %d.", *p);
#endif

    switch (*p++)
    {
	case CMD_MSG:
	{
	    char msg;
	    char *c;

	    if (!(c = parse_command(p, "%c", &msg)))
		break;

	    switch (msg)
	    {
/*
	        case MSG_LOGIN_SUCCESS:
		    send_to_char("Puerto Rico connection successful!\n\r", ch);
		    break;
*/
		case PR_MSG_GAME_CREATED:
		{
		    parse_command(c, "%h", &gnum);
		    sprintf(out_buf, "New game (#{W%d{w) created.\n\r", gnum);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_MSG_JOIN:
		{
		    parse_command(c, "%h", &gnum);
		    sprintf(out_buf, "You have joined Puerto Rico game #{W%d{w!\n\r", gnum);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_MSG_HAS_JOINED:
		{
		    parse_command(c, "%h%s", &gnum, name);
		    sprintf(out_buf, "%s has joined Puerto Rico game #{W%d{w!\n\r", name, gnum);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_MSG_GAME_START:
		{
		    parse_command(c, "%h%s", &gnum, name);
		    sprintf(out_buf, "Puerto Rico game #{W%d{w has started!  {W%s{w is governor, and goes first.\n\r", gnum, name);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_MSG_ROLE_CHOSEN:
		{
		    char role, gold;

		    parse_command(c, "%h%s%c%c", &gnum, name, &role, &gold);
		    sprintf(out_buf, "%s has chosen the role of {W%s{w (%d gold).\n\r", name, role_names[role], gold);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_PLANT_CHOSEN:
		{
		    char ptype;

		    parse_command(c, "%h%s%c", &gnum, name, &ptype);
		    if (ptype == PLANT_QUARRY)
		        sprintf(out_buf, "%s takes a quarry.\n\r", name);
		    else
			sprintf(out_buf, "%s takes a%s %s plantation.\n\r",
				name, ptype == PLANT_INDIGO ? "n" : "", cgood_names[ptype]);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_NEXT_PHASE:
		{
		    char action;

		    parse_command(c, "%h%s%c", &gnum, name, &action);
		    
		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "It is now {Gyour{w turn to act ({W%s{w).\n\r", role_names[action]);
		    else
			sprintf(out_buf, "It is now %s'%s turn to act ({W%s{w).\n\r", name, LOWER(name[strlen(name) - 1]) == 's' ? "" : "s", role_names[action]);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_NEXT_TURN:
		{
		    char action;
		    char new_cols;
	    
		    c = parse_command(c, "%h%s%c", &gnum, name, &action);

		    if (action == ROLE_MAYOR)
		    {
			parse_command(c, "%c", &new_cols);

			sprintf(out_buf, "The %s round is over, and the ship is repopulated with %d colonists.\n\r", role_names[action], new_cols);
			puerto_message(gnum, out_buf, ch);

		    }
		    else
		    {
			sprintf(out_buf, "The %s round is over%s.\n\r", role_names[action],
			    (action == ROLE_SETTLER) ? ", and new plantations are revealed" : "");
			puerto_message(gnum, out_buf, ch);

		    }

		    if (!str_cmp(name, ch->name))
		        puerto_message(gnum, "It is now {Gyour{w turn to select a role.\n\r", ch);
		    else
		    {
			sprintf(out_buf, "It is %s'%s turn to select a role.\n\r", name, LOWER(name[strlen(name) - 1]) == 's' ? "" : "s");
			puerto_message(gnum, out_buf, ch);
		    }
		}
		break;

		case PR_MSG_PASS:
		{
		    parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			puerto_message(gnum, "You pass.\n\r", ch);
		    else
		    {
			sprintf(out_buf, "%s passes.\n\r", name);
			puerto_message(gnum, out_buf, ch);
		    }
		}
		break;

		case PR_MSG_NEXT_GOV:
		{
		    char turn;

		    parse_command(c, "%h%s%c", &gnum, name, &turn);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "It is turn #%d!  You are now the governor.\n\r", turn);
		    else
			sprintf(out_buf, "It is turn #%d!  %s is now the governor.\n\r", turn, name);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_GAMEEND_COL:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "The colonist supply has been exhausted; the game will end on this turn.\n\r", ch);
		}
		break;

		case PR_MSG_GAMEEND_VPS:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "The victory point supply has been exhausted; the game will end on this turn.\n\r", ch);
		}
		break;

		case PR_MSG_GAMEEND_BUILD:
		{
		    parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			strcpy(out_buf, "You have filled your building spaces; the game will end on this turn.\n\r");
		    else
			sprintf(out_buf, "%s has filled their building spaces; the game will end on this turn.\n\r", name);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_GET_COLS:
		{
		    char cols;

		    parse_command(c, "%h%s%c", &gnum, name, &cols);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You get %d colonist%s.\n\r", cols, cols == 1 ? "" : "s");
		    else
			sprintf(out_buf, "%s gets %d colonist%s.\n\r", name, cols, cols == 1 ? "" : "s");

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_MOVE:
		{
		    char move;

		    parse_command(c, "%h%c", &gnum, &move);

		    sprintf(out_buf, "You move a colonist from San Juan to %s %s%s.\n\r",
			(move == (PLANT_INDIGO * -1)) ? "an" : (move <= 0) ? "a" : "your",
			(move == (PLANT_QUARRY * -1)) ? "quarry" : (move <= 0) ? cgood_names[move * -1] : buildings[move - 1].name,
			((move > (PLANT_QUARRY * -1)) && (move <= 0)) ? " plantation" : "");
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_REMOVE:
		{
		    char move;

		    parse_command(c, "%h%c", &gnum, &move);

		    sprintf(out_buf, "You move a colonist from %s %s%s to San Juan.\n\r",
			(move == (PLANT_INDIGO * -1)) ? "an" : (move <= 0) ? "a" : "your",
			(move == (PLANT_QUARRY * -1)) ? "quarry" : (move <= 0) ? cgood_names[move * -1] : buildings[move - 1].name,
			((move > (PLANT_QUARRY * -1)) && (move <= 0)) ? " plantation" : "");
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_BUILD:
		{
		    char build_num, cost;

		    parse_command(c, "%h%s%c%c", &gnum, name, &build_num, &cost);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You build {W%s{w for %d doubloons.\n\r", buildings[build_num].name, cost);
		    else
			sprintf(out_buf, "%s builds {W%s{w for %d doubloons.\n\r", name, buildings[build_num].name, cost);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_CRAFTS:
		{
		    char g;
		    bool first = TRUE;
		    int i;

		    c = parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			strcpy(out_buf, "You craft");
		    else
			sprintf(out_buf, "%s crafts", name);

		    for (i = 0; i < 5; i++)
		    {
			c = parse_command(c, "%c", &g);
			
			if (g > 0)
			{
			    sprintf(buf, "%s {%c%d %s{w", first ? "" : ",",
				i == PLANT_CORN ? 'Y' :
				i == PLANT_INDIGO ? 'B' :
				i == PLANT_SUGAR ? 'W' :
				i == PLANT_TOBACCO ? 'R' : 'y',
				g, good_names[i]);
			    strcat(out_buf, buf);
			    first = FALSE;
			}
		    }

		    if (first)
			strcat(out_buf, " nothing");

		    strcat(out_buf, ".\n\r");
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_CRAFT_ADD:
		{
		    char good_num;

		    parse_command(c, "%h%s%c", &gnum, name, &good_num);
		
		    if (!str_cmp(name, ch->name))
		        sprintf(out_buf, "You craft an additional %s.\n\r", cgood_names[good_num]);
		    else
			sprintf(out_buf, "%s crafts an additional %s.\n\r", name, cgood_names[good_num]);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_TRADE:
		{
		    char good_num, value;

		    parse_command(c, "%h%s%c%c", &gnum, name, &good_num, &value);

		    if (!str_cmp(name, ch->name))
		        sprintf(out_buf, "You trade %s for %d doubloons.\n\r",
				cgood_names[good_num], value);
		    else
			sprintf(out_buf, "%s trades %s for %d doubloons.\n\r", name,
				cgood_names[good_num], value);
				
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_TRADE_CLEAR:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "The trading house is cleared of goods.\n\r", ch);
		}
		break;

		case PR_MSG_SHIP:
		{
		    char good_num, quantity, points;

		    parse_command(c, "%h%s%c%c%c", &gnum, name, &quantity, &good_num, &points);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You ship {%c%d %s{w for %d points.\n\r",
				good_num == PLANT_CORN ? 'Y' :
				good_num == PLANT_INDIGO ? 'B' :
				good_num == PLANT_SUGAR ? 'W' :
				good_num == PLANT_TOBACCO ? 'R' : 'y',
				quantity, good_names[good_num], points);
		    else
			sprintf(out_buf, "%s ships {%c%d %s{w for %d points.\n\r", name,
				good_num == PLANT_CORN ? 'Y' :
				good_num == PLANT_INDIGO ? 'B' :
				good_num == PLANT_SUGAR ? 'W' :
				good_num == PLANT_TOBACCO ? 'R' : 'y',
				quantity, good_names[good_num], points);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_DISCARD:
		{
		    char good_num, quantity;

		    parse_command(c, "%h%s%c%c", &gnum, name, &quantity, &good_num);
	    
		    if (!str_cmp(name, ch->name))
		        sprintf(out_buf, "You discard {%c%d %s{w.\n\r",
				good_num == PLANT_CORN ? 'Y' :
				good_num == PLANT_INDIGO ? 'B' :
				good_num == PLANT_SUGAR ? 'W' :
				good_num == PLANT_TOBACCO ? 'R' : 'y',
				quantity, good_names[good_num]);
		    else
			sprintf(out_buf, "%s discards {%c%d %s{w.\n\r", name,
				good_num == PLANT_CORN ? 'Y' :
				good_num == PLANT_INDIGO ? 'B' :
				good_num == PLANT_SUGAR ? 'W' :
				good_num == PLANT_TOBACCO ? 'R' : 'y',
				quantity, good_names[good_num]);

		    puerto_message(gnum, out_buf, ch);
		}
	        break;

		case PR_MSG_FACTORY:
		{
		    char earn;

		    parse_command(c, "%h%s%c", &gnum, name, &earn);

		    if (!str_cmp(name, ch->name))
		        sprintf(out_buf, "Your factory produces %d doubloons.\n\r", earn);
		    else
		        sprintf(out_buf, "%s'%s factory produces %d doubloons.\n\r", name, LOWER(name[strlen(name) - 1]) == 's' ? "" : "s", earn);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_PROSPECT:
		{
		    parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			strcpy(out_buf, "You prospect for 1 doubloon.\n\r");
		    else
			sprintf(out_buf, "%s prospects for 1 doubloon.\n\r", name);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_PHASE_DISCARD:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "Shipping is done, it is time to discard excess goods.\n\r", ch);
		}
		break;

		case PR_MSG_GAME_OVER:
		{
		    parse_command(c, "%h", &gnum);
		    sprintf(out_buf, "Puerto Rico game #{W%d{w is over!\n\r", gnum);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_POINTS:
		{
		    unsigned char points;

		    parse_command(c, "%h%s%c", &gnum, name, &points);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You finish the game with {W%d{w points.\n\r", points);
		    else
			sprintf(out_buf, "%s finishes the game with {W%d{w points.\n\r", name, points);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_GAME_WINNER:
		{
		    unsigned char points;

		    parse_command(c, "%h%s%c", &gnum, name, &points);

		    if (!str_cmp(name, ch->name))
			strcpy(out_buf, "{YYou have won the game!!\n\r");
		    else
			sprintf(out_buf, "{Y%s has won Puerto Rico game #%d!\n\r", name, gnum);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_GAME_TIED:
		{
		    unsigned char points;

		    parse_command(c, "%h%c", &gnum, &points);

		    sprintf(out_buf, "{YPuerto Rico game #%d has ended in a tie at %d points!\n\r", gnum, points);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_SPECTATE:
		{
		    parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You begin to spectate Puerto Rico game #{W%d{w.\n\r", gnum);
		    else
			sprintf(out_buf, "%s begins to spectate this game.\n\r", name);

		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_MSG_NOSPEC:
		{
		    parse_command(c, "%h%s", &gnum, name);

		    if (!str_cmp(name, ch->name))
			sprintf(out_buf, "You stop spectating Puerto Rico game #{W%d{w.\n\r", gnum);
		    else
			sprintf(out_buf, "%s stops spectating this game.\n\r", name);

		    puerto_message(gnum, out_buf, ch);
		}
		break;
		    
	    }
	}
	break;

	case CMD_ERR:
	{
	    char msg;
	    char *c;

	    if (!(c = parse_command(p, "%c", &msg)))
		break;

	    switch (msg)
	    {
		case PR_ERR_JOIN:
		{
		    parse_command(c, "%h", &gnum);
		    sprintf(out_buf, "Error joining Puerto Rico game #%d.\n\r", gnum);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_ERR_VIEW:
		{
		    parse_command(c, "%h%s", &gnum, name);
		    sprintf(out_buf, "'%s' is a not a player in this game.\n\r", name);
		    puerto_message(gnum, out_buf, ch);
		}   
		break;

		case PR_ERR_GAME_NOT_FOUND:
		{
		    parse_command(c, "%h", &gnum);
		    sprintf(out_buf, "Puerto Rico game #%d not found.\n\r", gnum);
		    send_to_char(out_buf, ch);
		}
		break;

		case PR_ERR_NOT_YOUR_TURN:
		{
		    parse_command(c, "%h", &gnum);
		    strcpy(out_buf, "It is not your turn in this game.\n\r");
		    puerto_message(gnum, out_buf, ch);
		}
		break;

//		case PR_ERR_INVALID_ROLE:

		case PR_ERR_ROLE_PICKED:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "That role has already been taken.  Please choose again.\n\r", ch);
		}
		break;

		case PR_ERR_NOT_PLAYER:
		{
		    parse_command(c, "%h", &gnum);
		    strcpy(out_buf, "You are not a player in this game.\n\r");
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_WRONG_PHASE:
		{
		    char phase;

		    parse_command(c, "%h%c", &gnum, &phase);
		    if (phase == -1)
			puerto_message(gnum, "It is not time to pick a role.\n\r", ch);
		    else
		    {
			sprintf(out_buf, "It is not currently the %s phase.\n\r", role_names[phase]);
			puerto_message(gnum, out_buf, ch);
		    }

		    return;
		}
		break;

		case PR_ERR_PLANT_UNAVAIL:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "That type of plantation is not available.\n\r", ch);
		}
		break;

		case PR_ERR_PLANTS_FULL:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "Your plantation lot is full.\n\r", ch);
		}
		break;

		case PR_ERR_CANT_QUARRY:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You are unable to select a quarry at this time.\n\r", ch);
		}
		break;

		case PR_ERR_NO_QUARRY:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "There are no quarries left available!  Please select again.\n\r", ch);
		}
		break;

		case PR_ERR_INVALID_MOVE:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "Invalid colonist move attempted.\n\r", ch);
		}
		break;

		case PR_ERR_FREE_SPACES:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You cannot end the mayor phase with free spaces remaining and colonists in San Juan.\n\r", ch);
		}
		break;

		case PR_ERR_BUILD_GONE:
		{
		    char build_num;

		    parse_command(c, "%h%c", &gnum, &build_num);
		    sprintf(out_buf, "There are no %s remaining.\n\r", buildings[build_num].name);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_BUILD_NOSPACE:
		{
		    char build_num;

		    parse_command(c, "%h%c", &gnum, &build_num);
		    sprintf(out_buf, "You don't have enough space to build %s.\n\r", buildings[build_num].name);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_BUILD_COST:
		{
		    char build_num, cost;

		    parse_command(c, "%h%c%c", &gnum, &build_num, &cost);
		    sprintf(out_buf, "You cannot afford to build %s (cost = %d).\n\r", buildings[build_num].name, cost);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_BUILD_DUPLICATE:
		{
		    char build_num;

		    parse_command(c, "%h%c", &gnum, &build_num);
		    sprintf(out_buf, "You already have %s.\n\r", buildings[build_num].name);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_CRAFT_INVALID:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "You are not allowed to take an additional %s.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_CRAFT_NONE:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "There are no %s available for crafting.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_TRADE_NONE:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "You have no %s to trade.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_TRADE_SAME:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "The trading house already contains %s.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_SHIP_DISCARD:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "It is currently time to discard goods.\n\r", ch);
		}
		break;

		case PR_ERR_SHIP_NONE:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "You don't have any %s to ship.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_SHIP_FULL:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "That ship is already full.\n\r", ch);
		}
		break;

		case PR_ERR_NO_WHARF:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You do not own a manned wharf.\n\r", ch);
		}
		break;

		case PR_ERR_CANT_WHARF:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You are not able to use your wharf at this time.\n\r", ch);
		}
		break;

		case PR_ERR_BOAT_TAKEN:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "That boat already contains another type of good.\n\r", ch);
		}
		break;

		case PR_ERR_MUST_SHIP:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You cannot pass at this time, you have goods to ship.\n\r", ch);
		}
		break;

		case PR_ERR_MUST_DISCARD:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You cannot pass at this time, you have goods to discard.\n\r", ch);
		}
		break;

		case PR_ERR_SHIP_MAIN:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "It is currently time to ship goods.\n\r", ch);
		}
		break;

		case PR_ERR_DISCARD_NONE:
		{
		    char good_num;

		    parse_command(c, "%h%c", &gnum, &good_num);
		    sprintf(out_buf, "You have no %s to discard.\n\r", good_names[good_num]);
		    puerto_message(gnum, out_buf, ch);
		}
		break;

		case PR_ERR_CHOOSE_ROLE:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You must choose a role at this time.\n\r", ch);
		}
		break;

		case PR_ERR_CANT_SPEC:
		{
		    parse_command(c, "%h", &gnum);
		    puerto_message(gnum, "You cannot spectate a game you're already involved in.\n\r", ch);
		}
		break;
	    }
	}
	break;
/*
	case CMD_DATA_PLIST:
	{
	    long list_size;
	    unsigned short i;

	    c = parse_command(p, "%l", &list_size);

	    sprintf(out_buf, "{BPlayers currently connected ({C%ld{B):\n\r", list_size);
	    send_to_char(out_buf, ch);

	    for (i = 0; i < list_size; i++)
	    {
		c = parse_command(c, "%s", buf);
		sprintf(out_buf, "{c%s{x\n\r", buf);
		send_to_char(out_buf, ch);
	    }
	}
	break;
*/
	case PR_CMD_DATA_GLIST:
	{
	    unsigned short list_size, i, j, gid;
	    char status, numplay, points;
  
	    c = parse_command(p, "%h", &list_size);

	    send_to_char("{wPuerto Rico --- Games Listing\n\r{c[{CGID{c] [{CStatus{c]      [{CPlayers{c]\n\r=============================\n\r", ch);

	    for (i = 0; i < list_size; i++)
	    {
		c = parse_command(c, "%h%c%c", &gid, &status, &numplay);
		sprintf(out_buf, "{W%5d %-16s  ", gid, status == -2 ? "{DCompleted{c" :
						    status == -1 ? "{WNeed players{c" :
								   "{CIn progress{c");
		send_to_char(out_buf, ch);

		for (j = 0; j < numplay; j++)
		{
		    c = parse_command(c, "%s", buf);

		    if (status == -2)
		        c = parse_command(c, "%c", &points);

		    if (buf[0] != '\0')
		    {
		        sprintf(out_buf, "%s%s%s", j > 0 ? ", " : "", buf, j == status ? "{M*{c" : "");
			send_to_char(out_buf, ch);

			if (status == -2)
			{
			    sprintf(out_buf, " ({C%d{c)", points);
			    send_to_char(out_buf, ch);
			}
		    }
		}

		if (status == -1)
		{
		    sprintf(out_buf, " (Max = {C%d{c)", numplay);
		    send_to_char(out_buf, ch);
		}

		send_to_char("\n\r", ch);
	    }
	}
	break;	    

	case PR_CMD_SELF_VIEW:
	{
	    struct player_data pdata;

	    memcpy(&pdata, p, sizeof(pdata));
	    puerto_viewp(ch, pdata, TRUE);

	}
	break;

	case PR_CMD_OTHER_VIEW:
	{
	    struct player_data pdata;

	    memcpy(&pdata, p, sizeof(pdata) - 1);
	    puerto_viewp(ch, pdata, FALSE);
	}
	break;

	case PR_CMD_BUILDS_VIEW:
	{
	    char bdata[23];
	    int i, j, k, cols = 4;

	    memcpy(bdata, p, sizeof(bdata));
	    
	    for (i = 0; i < 6; i++)
	    {
		if (i == 5)
		    cols = 3;

		for (j = 0; j < cols; j++)
		{
		    if (j == 0)
			strcpy(out_buf, "");
		    else
			strcat(out_buf, "   ");

		    sprintf(buf, "%2d.%-14s x%d", (i + 1) + (j * 6), buildings[i + (j * 6)].short_form, bdata[i + (j * 6)]);
		    strcat(out_buf, buf);
		}

		strcat(out_buf, "\n\r");
		send_to_char(out_buf, ch);
		strcpy(out_buf, "   ");

		for (j = 0; j < cols; j++)
		{
		    if (j != 0)
		        strcat(out_buf, "      ");
		
		    for (k = 0; k < 3; k++)
		        strcat(out_buf, buildings[i + (j * 6)].spaces >= (k + 1) ? "( )" : "   ");

		    sprintf(buf, " {Y%2dg{x", buildings[i + (j * 6)].cost);
		    strcat(out_buf, buf);
		}

	        strcat(out_buf, "\n\r");
		send_to_char(out_buf, ch);
	    }
	}
	break;

	case PR_CMD_GAME_VIEW:
	{
	    c = parse_command(p, "%s%s", gov, cur);

	    memcpy(&gdata, c, 39 + (8 * NAME_LEN));

	    sprintf(out_buf, "Puerto Rico Game #%d -- Status   Turn: %d   Governor: %s\n\r\n\r", gdata.gid, gdata.num_turns + 1, gov);
	    send_to_char(out_buf, ch);

	    for (i = 0; i < (3 + gdata.num_players); i++)
	    {
		if (gdata.roles[i] >= 0)
		    sprintf(out_buf, "%-10s %2d gold\n\r", role_names[i], gdata.roles[i]);
		else
		    sprintf(out_buf, "%-10s {Dunavail{w  -taken by %s-\n\r", role_names[i], gdata.role_taken[i]);

		send_to_char(out_buf, ch);
	    }

	    send_to_char("\n\rGoods Remaining -- ", ch);

	    for (i = 0; i < 5; i++)
	    {
		sprintf(out_buf, "%s%s: %d", (i > 0) ? ", " : "", good_names[i], gdata.goods[i]);
		send_to_char(out_buf, ch);
	    }

	    send_to_char("\n\r\n\rShip #1 carrying ", ch);

	    sprintf(out_buf, "%-11s (%d, %d free)     Victory points remaining: %d\n\r",
		gdata.boat_types[0] == -1 ? "{wnothing{w" : cgood_names[gdata.boat_types[0]],
		gdata.boat_goods[0], 1 + gdata.num_players - gdata.boat_goods[0], gdata.vps);
	    send_to_char(out_buf, ch);

	    sprintf(out_buf, "Ship #2 carrying %-11s (%d, %d free)     Quarries remaining: %d\n\r",
		gdata.boat_types[1] == -1 ? "{wnothing{w" : cgood_names[gdata.boat_types[1]],
		gdata.boat_goods[1], 2 + gdata.num_players - gdata.boat_goods[1], gdata.quarries);
	    send_to_char(out_buf, ch);

	    sprintf(out_buf, "Ship #3 carrying %-11s (%d, %d free)     Colonists -- supply: %d, ship: %d\n\r\n\rTrading House contains: ",
		gdata.boat_types[2] == -1 ? "{wnothing{w" : cgood_names[gdata.boat_types[2]],
		gdata.boat_goods[2], 3 + gdata.num_players - gdata.boat_goods[2], gdata.col_supply, gdata.col_ship);
	    send_to_char(out_buf, ch);

	    for (i = 0; i < 4; i++)
	    {
		if (gdata.thouse[i] >= 0)
		{
		    sprintf(out_buf, "%s%s", (i > 0) ? ", " : "", cgood_names[gdata.thouse[i]]);
		    send_to_char(out_buf, ch);
		}
		else
		{
		    sprintf(out_buf, "  (%d empty)", 4 - i);
		    send_to_char(out_buf, ch);
		    break;
		}
	    }

	    send_to_char("\n\rPlantations visible: ", ch);

	    if (gdata.turn == -1)
		send_to_char("none yet!", ch);
	    else
	    {
	        for (i = 0; i < gdata.num_players + 1; i++)
		    if (gdata.plants_display[i] >= 0)
		    {
		        sprintf(out_buf, "%s%s", first_found ? ", " : "", cgood_names[gdata.plants_display[i]]);
		        send_to_char(out_buf, ch);
			first_found = TRUE;
		    }
	    }

	    send_to_char("\n\r\n\r", ch);

	    if (gdata.turn == -1)
		strcpy(out_buf, "This game has not yet started.\n\r");
	    else if (gdata.action == -1)
		sprintf(out_buf, "Currently waiting for {W%s{w to choose a role.\n\r", cur);
	    else
		sprintf(out_buf, "Currently waiting for {W%s{w to participate in the %s phase.\n\r", cur, role_names[gdata.action]);

	    send_to_char(out_buf, ch);
	}
	break;

	case PR_CMD_PLIST_VIEW:
	{
	    char num_play, turn, curgov, i, j, g, dubs;

	    c = parse_command(p, "%h%c%c%c", &gnum, &num_play, &turn, &curgov);

	    send_to_char("{CT G {b[{CName{b]                     {CDub  {b[{COn Hand{b]            [{CProduction{b]\n\r", ch);
	    send_to_char("{c===========================================================================\n\r", ch);
	
	    for (i = 0; i < num_play; i++)
	    {
		if (turn == i)
		    send_to_char("{MT ", ch);
		else
		    send_to_char("  ", ch);

		if (curgov == i)
		    send_to_char("{RG ", ch);
		else
		    send_to_char("  ", ch);

		c = parse_command(c, "%s%c", name, &dubs);

		sprintf(out_buf, "{W%-25s  {w%2dg", name, dubs);
		send_to_char(out_buf, ch);

		for (j = 0; j < 5; j++)
		{
		    c = parse_command(c, "%c", &g);

		    sprintf(out_buf, " {%c%2d%c",
			j == 0 ? 'Y' : j == 1 ? 'B' : j == 2 ? 'W' : j == 3 ? 'R' : 'y', g,
			j == 0 ? 'c' : j == 1 ? 'i' : j == 2 ? 's' : j == 3 ? 't' : 'c');

		    send_to_char(out_buf, ch);
		}

		send_to_char(" ", ch);

		for (j = 0; j < 5; j++)
		{
		    c = parse_command(c, "%c", &g);

		    sprintf(out_buf, " {%c%2d%c",
			j == 0 ? 'Y' : j == 1 ? 'B' : j == 2 ? 'W' : j == 3 ? 'R' : 'y', g,
			j == 0 ? 'c' : j == 1 ? 'i' : j == 2 ? 's' : j == 3 ? 't' : 'c');

		    send_to_char(out_buf, ch);
		}

		send_to_char("\n\r", ch);
	    }
	}
	break;

    }
}
Example #28
0
/*------------------------------------------------------------------------
 * MAIN PROGRAM
 *------------------------------------------------------------------------*/
int main(int argc, const char *argv[])
{
    command_t        command;                           /* the current command being processed */
    //char             command_text[MAX_COMMAND_LENGTH];  /* the raw text of the command         */
    char *command_text;
    ttp_session_t   *session = NULL;
    ttp_parameter_t  parameter;
   
    int argc_curr       = 1;                            /* command line argument currently to be processed */
    char *ptr_command_text = &command_text[0];
   
    /* reset the client */
    memset(&parameter, 0, sizeof(parameter));
    reset_client(&parameter);

    /* show version / build information */
    #ifdef VSIB_REALTIME
    fprintf(stderr, "Tsunami Realtime Client for protocol rev %X\nRevision: %s\nCompiled: %s %s\n"
                    "   /dev/vsib VSIB accesses mode is %d, gigabit=%d, 1pps embed=%d, sample skip=%d\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__,
            vsib_mode, vsib_mode_gigabit, vsib_mode_embed_1pps_markers, vsib_mode_skip_samples);
    #else
    fprintf(stderr, "Tsunami Client for protocol rev %X\nRevision: %s\nCompiled: %s %s\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__);    
    #endif

    /* while the command loop is still running */   
    while (1) {

      /* retrieve the user's commands */
      if (argc<=1 || argc_curr>=argc) {
         
          /* present the prompt */
          fprintf(stdout, "tsunami> ");
         fflush(stdout);
	 
         /* read next command */
         
         if (fgets(command_text, MAX_COMMAND_LENGTH, stdin) == NULL) {
            error("Could not read command input");
         }
		



	
         
      } else {
         
         // severe TODO: check that command_text appends do not over flow MAX_COMMAND_LENGTH...
         
         /* assemble next command from command line arguments */
         for ( ; argc_curr<argc; argc_curr++) {
            // zero argument commands
            if (!strcasecmp(argv[argc_curr], "close") || !strcasecmp(argv[argc_curr], "quit") 
                || !strcasecmp(argv[argc_curr], "exit") || !strcasecmp(argv[argc_curr], "bye")
                || !strcasecmp(argv[argc_curr], "help") || !strcasecmp(argv[argc_curr], "dir")) { 
               strcpy(command_text, argv[argc_curr]);
               argc_curr += 1;
               break; 
            } 
            // single argument commands
            if (!strcasecmp(argv[argc_curr], "connect")) {
               if (argc_curr+1 < argc) {
                  strcpy(ptr_command_text, argv[argc_curr]);
                  strcat(command_text, " ");
                  strcat(command_text, argv[argc_curr+1]);
               } else {
                  fprintf(stderr, "Connect: no host specified\n"); 
                  exit(1);
               }
               argc_curr += 2;
               break;
            }
	   /*__FINAL_PROJECT_START__
            if (!strcasecmp(argv[argc_curr], "connect6")) {
               if (argc_curr+1 < argc) {
                  strcpy(ptr_command_text, argv[argc_curr]);
                  strcat(command_text, " ");
                  strcat(command_text, argv[argc_curr+1]);
               } else {
                  fprintf(stderr, "Connect: no host specified\n"); 
                  exit(1);
               }
               argc_curr += 2;
               break;
            }
 	    __FINAL_PROJECT_END __*/

            if (!strcasecmp(argv[argc_curr], "get")) {
               if (argc_curr+1 < argc) {
                  strcpy(ptr_command_text, argv[argc_curr]);
                  strcat(command_text, " ");
                  strcat(command_text, argv[argc_curr+1]);
               } else {
                  fprintf(stderr, "Get: no file specified\n"); 
                  exit(1);
               }
               argc_curr += 2;
               break;
            }
            // double argument commands
            if (!strcasecmp(argv[argc_curr], "set")) {
               if (argc_curr+2 < argc) {
                  strcpy(ptr_command_text, argv[argc_curr]);
                  strcat(command_text, " ");
                  strcat(command_text, argv[argc_curr+1]);
                  strcat(command_text, " ");
                  strcat(command_text, argv[argc_curr+2]);
               } else {
                  fprintf(stderr, "Connect: no host specified\n"); 
                  exit(1);
               }
               argc_curr += 3;
               break;
            }
            // unknown commands, skip
            fprintf(stderr, "Unsupported command console command: %s\n", argv[argc_curr]);
         }
         
      }

      /* parse the command */
      parse_command(&command, command_text);

      /* make sure we have at least one word */
      if (command.count == 0)
         continue;
         
      /* dispatch on the command type */
           if (!strcasecmp(command.text[0], "close"))             command_close  (&command, session);
      else if (!strcasecmp(command.text[0], "connect")) session = command_connect(&command, &parameter);
      //else if (!strcasecmp(command.text[0], "connect6")) session = command_connect6(&command, &parameter);
      else if (!strcasecmp(command.text[0], "get"))               command_get    (&command, session);
      else if (!strcasecmp(command.text[0], "dir"))               command_dir    (&command, session);
      else if (!strcasecmp(command.text[0], "help"))              command_help   (&command, session);
      else if (!strcasecmp(command.text[0], "quit"))              command_quit   (&command, session);
      else if (!strcasecmp(command.text[0], "exit"))              command_quit   (&command, session);
      else if (!strcasecmp(command.text[0], "bye"))               command_quit   (&command, session);
      else if (!strcasecmp(command.text[0], "set"))               command_set    (&command, &parameter);
      else
          fprintf(stderr, "Unrecognized command: '%s'.  Use 'HELP' for help.\n\n", command.text[0]);
    }

    /* if we're here, we shouldn't be */
    return 1;
}
Example #29
0
bool interface(char *line)
{
    
    // Bad practices ftw
    char infile[CSTRSIZE];
    char outfile[CSTRSIZE];
    bool continueExecute = false;
    char *cmd1[CMDSIZE];
    char *cmd2[CMDSIZE];
    int i;
    int k;
    cmd1[0] = NULL;
    cmd2[0] = NULL;
    infile[0] = '\0';
    outfile[0] = '\0';
    
    i = parse_command(line, cmd1, cmd2, infile, outfile);
    if(i == 0)
    {
        continueExecute = true;
    }
    switch(i)
    {
        case 1:
            exec_cmd(cmd1);
            break;
        case 2:
            exec_cmd_in(cmd1, infile);
            break;
        case 3:
            exec_cmd_opt_in_append(cmd1, infile, outfile);
            break;
        case 4:
            exec_cmd_opt_in_write(cmd1, infile, outfile);
            break;
        case 5:
            exec_pipe(cmd1, cmd2);
            break;
        case 6:
            exec_pipe_in(cmd1, cmd2,infile);
            break;
        case 7:
            exec_pipe_opt_in_append(cmd1, cmd2,infile,outfile);
            break;
        case 8:
            exec_pipe_opt_in_write(cmd1, cmd2,infile,outfile);
            break;
        default:
            break;
    }
    
    if (i > 9)
    {
        k = 0;
        while (cmd1[k] != NULL)
        {
            printf("cmd1[%d] = %s\n", k, cmd1[k]);
            k++;
        };
        k = 0;
        while (cmd2[k] != NULL)
        {
            printf("cmd2[%d] = %s\n", k, cmd2[k]);
            k++;
        };
        if (strlen(infile))
        {
            printf("input redirection file name: %s\n", infile);
        }
        if (strlen(outfile))
        {
            printf("output redirection file name: %s\n", outfile);
        }
    }
    printf("return code is %d\n", i);
    
    return continueExecute;
}
Example #30
0
void *
start_messenger(void *ptr)
{

    int s, s2, len, i;
    socklen_t t;
    struct sockaddr_un local, remote;
    char command[32];
    char mstatus[64];

    /* alloc for message status */
    //mstatus = malloc(sizeof(mstatus)

    /* create a unix stream socket */
    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
	perror("socket");
	exit(1);
    }

    /* assign the socket path */
    local.sun_family = AF_UNIX;
    strcpy(local.sun_path, SOCK_PATH);
    /* unlink if socket already exists */
    unlink(local.sun_path);
    len = strlen(local.sun_path) + sizeof(local.sun_family);
    if (bind(s, (struct sockaddr *)&local, len) == -1) {
	perror("bind");
	pthread_exit((void *)errno);
    }

    /* qeue up to 1 connections, then reject */
    if (listen(s, NUM_ClIENTS) == -1) {
	perror("listen");
	exit(1);
    }

    /* wait for the remote connection(s) */
    for(;;) {
	int done, n;
	printf("fclient: >> Waiting for a connection... <<\n");
	t = sizeof(remote);
	if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) {
	    perror("accept");
	    pthread_exit((void *)errno);
	}

	printf("fclient: >> Socket Connected <<\n");

	/* loop to receive data/commands */
	done = 0;
	do {
	    /* wait to receive a command */
	    n = recv(s2, command, sizeof(command), RX_FLAGS );

	    /* echo back the command */
	    if (command != '\0')
		printf("COMMAND> %s\n", command);

	    if (n <= 0) { 
		if (n < 0) {
		    perror("recv");
		}
		done = 1;
	    }
	    if (!done) {
		
		/*************************************
		 process the command 
		 *************************************/

		/* clear last status */
		strcpy(mstatus, "");

		/* parse the command */
		if (!parse_command(command, &ctrls, mstatus)) {
		    printf("command was parsed with status: %s\n", mstatus);

		    /* clean up old filter */
		    free(filter);

		    /* Compute new biquad (callback) */
		    filter = compute_biquad(ctrls->ftype, 
			    ctrls->dBgain, 
			    ctrls->fc, 
			    ctrls->fs, 
			    ctrls->bw); 

		    printf("printing control list\n");
		    printf("fc=%f, g=%f, bw=%f \n", ctrls->fc, ctrls->dBgain, ctrls->bw);
		    printf("printing new coefficients:\n");
		    printf("b0=%f, b1=%f, b2=%f, a1=%f, a2=%f \n\n", filter->b0, filter->b1, filter->b2, filter->a1, filter->a2);
		}

		/* transmit response */
		if (send(s2, mstatus, n, 0) < 0) {
		    perror("send");
		    done = 1;
		}

		/* clear the command */
		for (i = 0; i < n; i++) {
		    command[i] = '\0';
		}
	    }

	} while (!done);

	close(s2);
    }
    pthread_exit(NULL);
    //return 0;
}