예제 #1
0
파일: worker.c 프로젝트: 9612jhf/webdis
/**
 * Called when a client has finished reading input and can create a cmd
 */
void
worker_process_client(struct http_client *c) {

	/* check that the command can be executed */
	struct worker *w = c->w;
	cmd_response_t ret = CMD_PARAM_ERROR;
	switch(c->parser.method) {
		case HTTP_GET:
			if(c->path_sz == 16 && memcmp(c->path, "/crossdomain.xml", 16) == 0) {
				http_crossdomain(c);
				return;
			}
			slog(w->s, WEBDIS_DEBUG, c->path, c->path_sz);
			ret = cmd_run(c->w, c, 1+c->path, c->path_sz-1, NULL, 0);
			break;

		case HTTP_POST:
			slog(w->s, WEBDIS_DEBUG, c->path, c->path_sz);
			ret = cmd_run(c->w, c, c->body, c->body_sz, NULL, 0);
			break;

		case HTTP_PUT:
			slog(w->s, WEBDIS_DEBUG, c->path, c->path_sz);
			ret = cmd_run(c->w, c, 1+c->path, c->path_sz-1,
					c->body, c->body_sz);
			break;

		case HTTP_OPTIONS:
			http_send_options(c);
			return;

		default:
			slog(w->s, WEBDIS_DEBUG, "405", 3);
			http_send_error(c, 405, "Method Not Allowed");
			return;
	}

	switch(ret) {
		case CMD_ACL_FAIL:
		case CMD_PARAM_ERROR:
			slog(w->s, WEBDIS_DEBUG, "403", 3);
			http_send_error(c, 403, "Forbidden");
			break;

		case CMD_REDIS_UNAVAIL:
			slog(w->s, WEBDIS_DEBUG, "503", 3);
			http_send_error(c, 503, "Service Unavailable");
			break;
		default:
			break;
	}

}
예제 #2
0
파일: shell.c 프로젝트: denis4net/netdroid
/**
 * @brief Shell loop.
 * Wait for commands in command_queue, run it, report command run status via usart tty.
 */
void shell_run()
{
	char local_command[CMD_SIZE];
	queue_init(&command_queue);

	usart_send_str("************************************\r\n");
	usart_send_str("Welcome to Neuraxis shell\r\n");
	usart_send_str("************************************\r\n>");

	while(1) {
		if( !queue_is_empty(&command_queue) ) {
			strcpy(local_command, queue_dequeue(&command_queue));
			cmd_status_t status = cmd_run(local_command);
			if(status == CMD_SUCCESSFUL ) {
				usart_send_str("Command '");
				usart_send_str(local_command);
				usart_send_str("' successfully executed\r\n");
			}
			else
			{
				usart_send_str("Command '");
				usart_send_str(local_command);
				usart_send_str("' can't be executed\r\n");
			}

			usart_send_byte((uint8_t) '>');
		}
		else {
			__WFI();
		}
	}

}
예제 #3
0
파일: cmdline.c 프로젝트: jollywho/nav
void cmdline_req_run(Cmdstr *caller, Cmdline *cmdline)
{
  if (!cmdline->cmds || cmdline->err)
    return;

  if (utarray_len(cmdline->cmds) == 1) {
    Cmdstr *single = cmdline_getcmd(cmdline);
    single->caller = caller;
    return cmd_run(single, cmdline);
  }

  char *full_line = cmdline->line;
  int len = strlen(full_line);
  char *last = &full_line[len+1];

  bool waspipe = false;
  Cmdstr *cmd = NULL;
  while ((cmd = (Cmdstr*)utarray_next(cmdline->cmds, cmd))) {

    char *line = &full_line[cmd->st];
    if (line < last && waspipe)
      line++;
    if (cmd->bar)
      full_line[cmd->ed] = '\0';

    cmd_eval(NULL, line);
    waspipe = cmd->bar;
  }
}
예제 #4
0
/*****************************************************************************
 函 数 名  : inf_add_dft_route
 功能描述  : 添加缺省路由
 输入参数  : gate 网关
 输出参数  : 无
 返 回 值  : OK 成功 其他失败
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2008年9月10日
    
    修改内容   : 新生成函数

*****************************************************************************/
int inf_add_dft_route(const char * gate)
{
    char command[64+INTERFACE_NAME_MAX_LENGTH];
    FILE * fp = NULL;
    MEMBUFF * buff;

    /* 修改ip地址 */
    snprintf(command, 63+INTERFACE_NAME_MAX_LENGTH, "/sbin/route add default gw %s 2>&1",
            gate);
    command[63+INTERFACE_NAME_MAX_LENGTH] = '\0';

    fp = cmd_run(command);

    if(NULL == fp)
    {
        return ERROR;
    }

    buff = membuff_readfile(fp);
    cmd_closeio(fp);

    if(NULL == buff)
    {
        return ERROR;
    }

    if(buff->len == 0 || buff->array[0]->len == 0)
    {
        membuff_free(buff);
        return OK;
    }

    membuff_free(buff);
    return ERROR;
}
예제 #5
0
파일: shell.c 프로젝트: Rathcke/uni
int run_command(char* cmdline) {
  char* argv[BUFFER_SIZE];
  int argc = tokenize(cmdline, argv);
  if (argc == 0) {
    return 0;
  }
  if (strcmp(argv[0], "wait") == 0) {
    return cmd_wait(argc, argv);
  } else if (strcmp(argv[0], "ls") == 0) {
    return cmd_ls(argc, argv);
  } else if (strcmp(argv[0], "cp") == 0) {
    return cmd_cp(argc, argv);
  } else if (strcmp(argv[0], "show") == 0) {
    return cmd_show(argc, argv);
  } else if (strcmp(argv[0], "rm") == 0) {
    return cmd_rm(argc, argv);
  } else if (strcmp(argv[0], "cmp") == 0) {
    return cmd_cmp(argc, argv);
  } else if (strcmp(argv[0], "echo") == 0) {
    return cmd_echo(argc, argv);
  } else if (strcmp(argv[0], "exit") == 0) {
    syscall_exit(0); 
    return 1; // not reached
  } else {
    int k = strlen(argv[argc-1]);
    if (argv[argc-1][k-1] == '&') {
      argv[argc-1][k-1] = '\0';
      return background_run(cmdline);
    } else {
      return cmd_run(cmdline);
    }
  }
}
예제 #6
0
/* use common shell processing for all commands - this prevent static linking
   of EXTCMD or VDISK modules for shl_ramdisk/shl_mem functions. */
static void shell_cmd(const char *cmd, const char *args) {
   char   *cstr = strcat_dyn(sprintf_dyn(cmd), args);
   cmd_state cs = cmd_init(cstr, 0);
   cmd_run(cs, CMDR_ECHOOFF);
   cmd_close(cs);
   free(cstr);
}
예제 #7
0
static void cmd_run_buffered(uint32_t worker_id)
{
   uint32_t pos;
    for (pos = 0; pos < rdp_cmd_buf_pos; pos++) {
        cmd_run(&rdp_states[worker_id], rdp_cmd_buf[pos]);
    }
}
예제 #8
0
/*****************************************************************************
 * int bsdl_emit_ports( jtag_ctrl_t *jc )
 *
 * Adds the specified port name as a signal via shell command
 *   signal <pin>
 * The port name is taken from the port_desc structure that was filled in
 * previously by rule Scalar_or_Vector. This way, the function can build
 * vectored ports as well.
 * Keep in mind that multiple names can be defined by one port specification
 * (there's a names_list in port_desc).
 *
 * Parameters
 *   jc : jtag control structure
 *
 * Returns
 *   1 -> all ok
 *   0 -> error occured
 ****************************************************************************/
static int bsdl_emit_ports(jtag_ctrl_t *jc)
{
  port_desc_t *pd = jc->port_desc;
  struct string_elem *name;
  size_t str_len, name_len;
  char *port_string;
  int idx;
  int result = 0;
  char *cmd[] = {"signal",
                 NULL,
                 NULL};

  while (pd)
  {
    name = pd->names_list;
    while (name) {
      /* handle indexed port name:
         - names of scalar ports are simply copied from the port_desc structure
           to the final string that goes into ci
         - names of vectored ports are expanded with their decimal index as
           collected earlier in rule Scalar_or_Vector
      */
      name_len = strlen( name->string );
      str_len = name_len + 1 + 10 + 1 + 1;
      if ((port_string = (char *)malloc( str_len )) != NULL)
      {
        cmd[1] = port_string;

        for (idx = pd->low_idx; idx <= pd->high_idx; idx++)
        {
          if (pd->is_vector)
            snprintf( port_string, str_len-1, "%s(%d)", name->string, idx );
          else
            strncpy( port_string, name->string, str_len-1 );
          port_string[str_len-1] = '\0';

          if (jc->proc_mode & BSDL_MODE_INSTR_EXEC)
            cmd_run( jc->chain, cmd );
          if (jc->proc_mode & BSDL_MODE_INSTR_PRINT)
            print_cmd( cmd );
        }

        free( port_string );
        result = 1;
      }
      else
        bsdl_msg( jc->proc_mode,
                  BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );

      name = name->next;
    }

    pd = pd->next;
  }

  return result;
}
예제 #9
0
/*****************************************************************************
 函 数 名  : clear_all_stat
 功能描述  : 清空设备流量统计
 输入参数  : 
 输出参数  : 无
 返 回 值  : OK 成功 其他失败
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2012年11月29日
    
    修改内容   : 新生成函数

*****************************************************************************/
int clear_all_stat()
{
	char command[128];
	FILE * fp = NULL;

	snprintf(command, 128, "/bin/dev_cfg eth sw clear all");
	command[sizeof(command)-1]='\0';

	fp = cmd_run(command);

	if(NULL == fp)
	{
		return ERROR;
	}
	cmd_closeio(fp);

	return OK;
}
예제 #10
0
/*****************************************************************************
 函 数 名  : clear_stat_by_slot
 功能描述  : 按照槽号清空流量统计
 输入参数  : slot    槽号
 输出参数  : 无
 返 回 值  : OK 成功 其他失败
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2012年11月28日
    
    修改内容   : 新生成函数

*****************************************************************************/
int clear_stat_by_slot(int slot)
{
	char command[128];
	FILE * fp = NULL;

	snprintf(command, 128, "/bin/dev_cfg eth sw clear slot %d",slot);
	command[sizeof(command)-1]='\0';

	fp = cmd_run(command);

	if(NULL == fp)
	{
		return ERROR;
	}
	cmd_closeio(fp);

	return OK;
}
예제 #11
0
/*****************************************************************************
 * int bsdl_set_instruction_length( jtag_ctrl_t *jc )
 *
 * Sets the specified length of the instruction register via shell command
 *   instruction length <len>
 *
 * Parameters
 *   jc : jtag control structure
 *
 * Returns
 *   1 -> all ok
 *   0 -> error occured
 ****************************************************************************/
static int bsdl_set_instruction_length( jtag_ctrl_t *jc )
{
  char lenstring[6];
  char *cmd[] = {"instruction",
                 "length",
                 lenstring,
                 NULL};

  snprintf( lenstring, 6, "%i", jc->instr_len );
  lenstring[5] = '\0';

  if (jc->proc_mode & BSDL_MODE_INSTR_EXEC)
    cmd_run( jc->chain, cmd );
  if (jc->proc_mode & BSDL_MODE_INSTR_PRINT)
    print_cmd( cmd );

  return 1;
}
예제 #12
0
파일: jtag.c 프로젝트: tbnobody/usbprog
static int
jtag_parse_line( char *line )
{
    char *t;
    int l;
    int n;
    char **a;
    int r;

    if (!line || !(strlen( line ) > 0))
        return 1;

    t = get_token( line );
    if (!t)
        return 1;

    n = 0;
    l = 0;
    a = NULL;
    while (t) {
        if (n + 2 > l) {
            char **newa;
            l = (l < 16) ? 16 : (l * 2);
            newa = realloc( a, l * sizeof (char *) );
            if (!newa) {
                free( a );
                printf( _("Out of memory\n") );
                return 1;
            }
            a = newa;
        }
        a[n++] = t;
        a[n] = NULL;

        t = get_token( NULL );
    }

    r = cmd_run( a );
    free( a );
    return r;
}
예제 #13
0
/*****************************************************************************
 函 数 名  : clear_stat
 功能描述  : 清空流量统计
 输入参数  : if_name 接口 名字
 输出参数  : 无
 返 回 值  : OK 成功 其他失败
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2008年9月12日
    
    修改内容   : 新生成函数

*****************************************************************************/
int clear_stat(const char * if_name)
{
	char command[128];
	FILE * fp = NULL;
	char name[INTERFACE_NAME_MAX_LENGTH]={0};

	strcpy(name,if_name);

	snprintf(command, 128, "/bin/dev_cfg mac %s clr",name);
	command[sizeof(command)-1]='\0';

	fp = cmd_run(command);

	if(NULL == fp)
	{
		return ERROR;
	}
	cmd_closeio(fp);

	return OK;
}
예제 #14
0
/*****************************************************************************
 * int create_register( jtag_ctrl_t *jc, char *reg_name, size_t len )
 *
 * Generic function to create a jtag register via shell command
 *   register <reg_name> <len>
 *
 * Parameters
 *   jc       : jtag control structure
 *   reg_name : name of the new register
 *   len      : number of bits (= length) of new register
 *
 * Returns
 *   1 -> all ok
 *   0 -> error occured
 ****************************************************************************/
static int create_register( jtag_ctrl_t *jc, char *reg_name, size_t len)
{
  const size_t str_len = 10;
  char len_str[str_len+1];
  char *cmd[] = {"register",
                 reg_name,
                 len_str,
                 NULL};

  if (part_find_data_register( jc->part, reg_name ))
    return 1;

  /* convert length information to string */
  snprintf( len_str, str_len, "%zu", len );

  if (jc->proc_mode & BSDL_MODE_INSTR_EXEC)
    cmd_run( jc->chain, cmd );
  if (jc->proc_mode & BSDL_MODE_INSTR_PRINT)
    print_cmd( cmd );

  return 1;
}
예제 #15
0
파일: shell.c 프로젝트: Rotte/osm-k
int run_command(char* cmdline) {
  char* argv[BUFFER_SIZE];
  int argc = tokenize(cmdline, argv);
  if (argc == 0) {
    return 0;
  }
  if (strcmp(argv[0], "wait") == 0) {
    return cmd_wait(argc, argv);
  } else if (strcmp(argv[0], "ls") == 0) {
    return cmd_ls(argc, argv);
  } else if (strcmp(argv[0], "cp") == 0) {
    return cmd_cp(argc, argv);
  } else if (strcmp(argv[0], "show") == 0) {
    return cmd_show(argc, argv);
  } else if (strcmp(argv[0], "rm") == 0) {
    return cmd_rm(argc, argv);
  } else if (strcmp(argv[0], "pwd") == 0) {
    return cmd_pwd(argc, argv);
  } else if (strcmp(argv[0], "cd") == 0) {
    return cmd_cd(argc, argv);
  } else if (strcmp(argv[0], "cmp") == 0) {
    return cmd_cmp(argc, argv);
  } else if (strcmp(argv[0], "echo") == 0) {
    return cmd_echo(argc, argv);
  } else if (strcmp(argv[0], "mkdir") == 0) {
    return cmd_mkdir(argc, argv);
  } else if (strcmp(argv[0], "rmdir") == 0) {
    return cmd_rmdir(argc, argv);
  } else {
    int k = strlen(argv[argc-1]);
    if (argv[argc-1][k-1] == '&') {
      argv[argc-1][k-1] = '\0';
      return background_run(cmdline);
    } else {
      return cmd_run(cmdline);
    }
  }
}
예제 #16
0
파일: ssh.c 프로젝트: IIJ-NetBSD/netbsd-src
/*
 * Evaluate a command named as argv[0]
 * with arguments argv[1],argv[2]...
 * Returns exit status.
 */
int
cmd_eval(int argc, char *argv[])
{
	struct cmd *cp;

	/*
	 * Do linear search for a builtin command.
	 * Performance does not matter here.
	 */
	for (cp = cmd_table; cp->name; cp++) {
		if (!strcmp(cp->name, argv[0])) {
			/* Pass only args to builtin. */
			--argc; argv++;
			return cp->func(argc, argv);
		}
	}

	/*
	 * If no matching builtin, let "run ..."
	 * have a chance to try an external.
	 */
	return cmd_run(argc, argv);
}
예제 #17
0
파일: perl.c 프로젝트: svn2github/irssi
static void irssi_perl_autorun(void)
{
	DIR *dirp;
	struct dirent *dp;
	struct stat statbuf;
	char *path, *fname;

	path = g_strdup_printf("%s/.irssi/scripts/autorun", g_get_home_dir());
	dirp = opendir(path);
	if (dirp == NULL) {
		g_free(path);
		return;
	}

	while ((dp = readdir(dirp)) != NULL) {
		fname = g_strdup_printf("%s/%s", path, dp->d_name);
                if (stat(fname, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
			cmd_run(fname);
		g_free(fname);
	}
	closedir(dirp);
	g_free(path);
}
예제 #18
0
파일: uo_net.c 프로젝트: millken/zhuxianB30
u32 netmode_translate_value(UserOperate_t* user_op,
                            ResultContext_t *result_context,
                            s8 * original_flag, s8 * helper, u32 position,
                            u32 trans_type, void* trans_data, s32 trans_data_int)
{
    WS_ENV* ws_env;

    s8 cmd[256];
    s8 buf[16];
    s8 dev_name[64] = {0};
    s32 len;
    FILE* fp = NULL;
    struct uo_netmode_t *my_data;
    ResultContext__getWsEnv(result_context, &ws_env);
    my_data = (struct uo_netmode_t *)UserOperate__getUserData(user_op);

    if (strcmp(helper, "ifstatus") == 0)
    {
        if(1 == trans_data_int)
        {
            http_out("up");
            return DefaultTranslate__I_OK;
        }
        else
        {
            http_out("down");
            return DefaultTranslate__I_OK;
        }
    }

    if (strcmp(helper, "ips") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));
        if(0 == strncmp("IPS", dev_name, 3))
        {
            return DefaultTranslate__I_IF_IS_TRUE;
        }
        else
        {
            return DefaultTranslate__I_IF_IS_FALSE;
        }
    }

    if (strcmp(helper, "isips") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));
        if(0 == strncmp("IPS", dev_name, 3))
        {
            http_out("1");
        }
        else
        {
            http_out("0");
        }
    }

    if (strcmp(helper, "ipsmode") == 0)
    {
        http_out("2");
    }

    if (strcmp(helper, "dnsaddr") == 0)
    {
        snprintf(cmd, 256, "cat %s | awk '{if($1~/nameserver/) print $2}'|sed -n 1p", STATICIP_CONFIG_FILE);
        fp = cmd_run(cmd);
        if(NULL == fp)
        {
            http_out("");
        }
        else
        {
            len = (s32)fread(buf, 1, sizeof(buf), fp);
            cmd_closeio(fp);
            if (len > 0)
            {
                buf[len - 1] = '\0';
                buf[sizeof(buf)-1] = '\0';
            }
            else
            {
                buf[0] = '\0';
            }
            http_out("%s", buf);
        }
    }

    if (strcmp(helper, "fwdnsaddr") == 0)
    {
        snprintf(cmd, 256, "cat %s | awk '{if($1~/nameserver/) print $2}'|sed -n 1p", "/etc/resolv_gateway.conf");
        fp = cmd_run(cmd);
        if(NULL == fp)
        {
            http_out("");
        }
        else
        {
            len = (s32)fread(buf, 1, sizeof(buf), fp);
            cmd_closeio(fp);
            if (len > 0)
            {
                buf[len - 1] = '\0';
                buf[sizeof(buf)-1] = '\0';
            }
            else
            {
                buf[0] = '\0';
            }
            http_out("%s", buf);
        }
    }

    if (strcmp(helper, "vifName") == 0)
    {
        strcpy(my_data->vifName, (s8 *)trans_data);
    }

    if (strcmp(helper, "ifmode") == 0)
    {
        my_data->iftype = DB_IF_TYPE_NOT_VLAN;

    }
    if (strcmp(helper, "vlanmode") == 0)
    {
        my_data->iftype = DB_IF_TYPE_VLAN;

    }

    else if (strcmp(helper, "acc_none") == 0)
    {
        http_out("%d", WAN_ACCESS_NULL);
    }
    else if (strcmp(helper, "acc_static") == 0)
    {
        http_out("%d", WAN_ACCESS_STATICIP);
    }
    else if (strcmp(helper, "acc_pppoe") == 0)
    {
        http_out("%d", WAN_ACCESS_PPPOE);
    }
    else if (strcmp(helper, "acc_dhcp") == 0)
    {
        http_out("%d", WAN_ACCESS_DHCLIENT);
    }
    else if (strcmp(helper, "acc_dhcpv6") == 0)
    {
        http_out("%d", WAN_ACCESS_DHCLIENT6);
    }
    else if (strcmp(helper, "acc_dhcp_route") == 0)
    {
        http_out("%d", WAN_ACCESS_DHCLIENT_NO_ROUTE);
    }
    else if (strcmp(helper, "acc_dhcpv6_dslite") == 0)
    {
        http_out("%d", WAN_ACCESS_DHCLIENT6_DSLITE);
    }

    return user_op->parent_translateValue(user_op, result_context,
                                          original_flag, helper, position, trans_type, trans_data, trans_data_int);
}
예제 #19
0
/*****************************************************************************
 函 数 名  : ws__getOperationLogList
 功能描述  : web service实现函数,获得日志列表
 输入参数  : soap       ---- web service执行环境
             
 输出参数  : ret        ---- 返回结果
 返 回 值  : WS_OK		---- 执行成功
             soapFault  ---- 执行失败
 调用函数  : 
 被调函数  : 
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月8日
     
    修改内容   : 新生成函数
*****************************************************************************/
int ws__getOperationLogList(WS_ENV* ws_env, struct ws__getOperationLogList_Response *ret)
{
//    int ws_err;
    int sys_error_code = ERROR_SUCCESS;
    char file_name[100];
    struct LogFileNameList *log_content;
    int saved_log = 0;
    FILE * fp = NULL;
    int i;
    u_int32_t count, file_name_start, vrf_name_start;
    char *div_char, *disp_name, *vrfid, *vrf_name;
	s32 vrf_id;
	char vrfcmd[100];
	s32 flag = 0;

    //不知道会有多少个文件,使用此宏
    count = LOG_MAX_COUNT;
    
    /* 调用库函数glob列出文件名,并将其存入数组 */
	vrf_id = login_get_current_user_vfw_id();
	if( 0 == vrf_id )
	{
	    vfw_getvfwswitch(&flag);
		if( 0 == flag)
		{
            fp = cmd_run(CMD_LS " " OPERA_LOG_PATH "/"  FLAG_OPER "*.l*");
		}
		else
		{
            fp = cmd_run(CMD_LS " " OPERA_LOG_PATH "/" "*" FLAG_OPER "*.l*");
		}
	}
	else
	{
        sprintf(vrfcmd, "%s%d%s",CMD_LS " " OPERA_LOG_PATH "/", vrf_id, "_" FLAG_OPER "*.l*");
		fp = cmd_run(vrfcmd);
	}
    
    if (NULL == fp)
    {
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }
    //计算文件名公共部分长度
    file_name_start = strlen(OPERA_LOG_PATH "/" FLAG_OPER);
	vrf_name_start = strlen(OPERA_LOG_PATH "/");
    disp_name = file_name + file_name_start;
	vrf_name = file_name + vrf_name_start;
    
    /* 因为不知道能有多少条记录,所以按最大量分配 */
    log_content = (struct LogFileNameList*)ws_malloc(ws_env, count*sizeof(struct LogFileNameList));
    if (NULL == log_content)
    {
        return ws_new_soap_fault(ws_env, ERROR_SYSTEM);
    }
    memset(log_content, 0, count*sizeof(struct LogFileNameList));
    ret->ret.__ptrres = log_content;
    
    while (!feof(fp) && ERROR_SUCCESS == sys_error_code)
    {
        if (NULL == fgets(file_name, sizeof(file_name), fp))
        {
            // end of file
            break;
        }
        // 去掉结尾换行符
        for (i = (int)strlen(file_name) -1; i >=0; i--)
        {
            if ('\n' == file_name[i] || '\r' == file_name[i])
            {
                file_name[i] = '\0';
            }
            else
            {
                break;
            }
        }

        div_char = strchr(disp_name, '.');
        if (NULL == div_char)
        {
            //格式不对
            sys_error_code = ws_send_soap_error(ws_env, "Searching log file list error!");
            break;
        }
        *div_char = '\0';
		vrfid = strchr(vrf_name, '_');
		if(NULL == vrfid)
		{
            log_content->vrfid = "0";
			log_content->fileName = ws_strdup(ws_env, disp_name);
		}
		else
		{
		    vrfid = strtok(vrf_name, "_");
            log_content->vrfid = ws_strdup(ws_env, vrfid);
			vrfid = strtok(NULL,".");
			vrfid = vrfid + strlen(FLAG_OPER);
			log_content->fileName = ws_strdup(ws_env, vrfid);
		}
        
        //保存此文件名
        
        log_content++;

        saved_log++;
    }
    cmd_closeio(fp);
    
    if (ERROR_SUCCESS != sys_error_code)
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }

    ret->ret.sum = saved_log;
    ret->ret.res_USCOREcount = ret->ret.__size = saved_log;
    return WS_OK;

}
예제 #20
0
/*****************************************************************************
 函 数 名  : ws__removeOperationLog
 功能描述  : web service实现函数,删除日志
 输入参数  : soap       ---- web service执行环境
             
 输出参数  : ret        ---- 返回结果
 返 回 值  : WS_OK		---- 执行成功
             soapFault  ---- 执行失败
 调用函数  : 
 被调函数  : 
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月8日
     
    修改内容   : 新生成函数
*****************************************************************************/
int ws__removeOperationLog(WS_ENV* ws_env, char *fileName, char * vrfid, int *ret)
{
//    int ws_err;
    int sys_error_code = ERROR_SUCCESS;
    char file_to_del[100];
    char command[200];
    int deleted = 0;
    FILE * fp = NULL;
    int i;

    /* 检查参数$vFileName的合法性 */
    sys_error_code = check_filename(fileName);
    if (ERROR_SUCCESS != sys_error_code)
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }

    /* 调用库函数ulink执行删除命令,删除日志主文件以及以.x结尾的日志文件,
     * 如删除oper-current.log及oper-current.log.1 至 oper-current.log.x,日志文
     * 件如果不连续默认也要删除
     */                

    /* 查找符合条件的日志文件*/
	if(strcmp("0", vrfid) == 0)
	{
        sprintf(command, "%s%s.l*", CMD_LS " " OPERA_LOG_PATH "/" FLAG_OPER, fileName);
	}
	else
	{
        sprintf(command, "%s%s%s%s.l*", CMD_LS " " OPERA_LOG_PATH "/",vrfid, "_" FLAG_OPER, fileName);
	}
    
    /* 保护局部变量 */
    command[sizeof(command) - 1 ] = '\0';
    
    fp = cmd_run(command);
    if (NULL == fp)
    {
        WEB_SEND_DEBUG_ss("ls log file failed:", command);
        return ws_send_soap_error(ws_env, "Deleting log file error!");
    }
    
    while (!feof(fp) && ERROR_SUCCESS == sys_error_code)
    {
        if (NULL == fgets(file_to_del, sizeof(file_to_del), fp))
        {
            // end of file
            break;
        }
        // 去掉结尾换行符
        for (i = (int)strlen(file_to_del) -1; i >=0; i--)
        {
            if ('\n' == file_to_del[i] || '\r' == file_to_del[i])
            {
                file_to_del[i] = '\0';
            }
            else
            {
                break;
            }
        }
        
        if (NULL != strstr(file_to_del, "Today"))
        {
            /* 清空当天日志 */
            /* ":>data.xx",该命令可以清空data.xx文件 */
            sprintf(command, ": > %s", file_to_del);
        }
        else
        {
            //生成删除命令
            sprintf(command, "rm %s", file_to_del);
        }
        /* 保护局部变量 */
        command[sizeof(command) - 1 ] = '\0';
        if (ERROR_SUCCESS != system(command))
        {
            WEB_SEND_DEBUG_ss("rm log file failed:", command);
            return ws_send_soap_error(ws_env, "Deleting log file error!");

        }
        deleted++;
    }
    cmd_closeio(fp);
    
    /* 如果函数glob获取的文件数目为0,报找不到文件 */
    if (0 == deleted)
    {
        return ws_send_soap_error(ws_env, "Current log file not exists!");
    }
   
    /* 记录操作日志 */
    WEB_SEND_EX_OPERLOG_QUICK(sys_error_code, REMOVE_OPERLOG_LOG, fileName);
    *ret = 0;
	
    return WS_OK;
}
예제 #21
0
/*****************************************************************************
 * int bsdl_process_register_access( jtag_ctrl_t *jc )
 * Register Access management function
 *
 * Runs through the main instruction list and builds the instruction/register
 * association for each instruction from the register access specifications
 * via shell command
 *   instruction <instruction> <code> <register>
 *
 * Additional register are created on the fly:
 *   - standard registers that haven't been created so far
 *   - non-standard registers encountered in register access specs
 *
 * Mandatory instruction/register associations are generated also in
 * absence of a related register access specification (such specs are
 * optional in the BSDL standard).
 *
 * Parameters
 *   jc : jtag control structure
 *
 * Returns
 *   1 -> all ok
 *   0 -> error occured
 ****************************************************************************/
static int bsdl_process_register_access( jtag_ctrl_t *jc )
{
  ainfo_elem_t *ai;
  instr_elem_t *cinst;

  /* ensure that all mandatory registers are created prior to
     handling the instruction/register associations
     + BOUNDARY/BSR has been generated during the parsing process
     + DEVICE_ID/DIR has been generated during the parsing process
  */
  /* we need a BYPASS register */
  create_register( jc, "BYPASS", 1 );

  /* next scan through all register_access definitions and create
     the non-standard registers */
  ai = jc->ainfo_list;
  while (ai)
  {
    int is_std = 0;

    if (strcasecmp( ai->reg, "BOUNDARY"  ) == 0) is_std = 1;
    if (strcasecmp( ai->reg, "BYPASS"    ) == 0) is_std = 1;
    if (strcasecmp( ai->reg, "DEVICE_ID" ) == 0) is_std = 1;
    if (strcasecmp( ai->reg, "USERCODE"  ) == 0) is_std = 1;

    if (!is_std)
      create_register( jc, ai->reg, ai->reg_len );

    ai = ai->next;
  }


  /* next scan through all instruction/opcode definitions and resolve
     the instruction/register associations for these */
  cinst = jc->instr_list;
  while (cinst)
  {
    char *reg_name = NULL;
    char *instr_name = NULL;

    /* now see which of the register_access elements matches this instruction */
    ai = jc->ainfo_list;
    while (ai && (reg_name == NULL))
    {
      instr_elem_t *tinst = ai->instr_list;

      while (tinst && (reg_name == NULL))
      {
        if (strcasecmp( tinst->instr, cinst->instr ) == 0)
        {
          /* found the instruction inside the current access info,
             now set the register name
             map some standard register names to different internal names*/
          if (strcasecmp( ai->reg, "BOUNDARY" ) == 0) reg_name = "BSR";
          else if (strcasecmp( ai->reg, "DEVICE_ID" ) == 0) reg_name = "DIR";
          else reg_name = ai->reg;
        }

        tinst = tinst->next;
      }

      ai = ai->next;
    }

    if (reg_name == NULL)
    {
      /* BSDL file didn't specify an explicit register_access definition
         if we're looking at a standard mandatory instruction, we should
         build the association ourselves */
      if      (strcasecmp( cinst->instr, "BYPASS"   ) == 0) reg_name = "BYPASS";
      else if (strcasecmp( cinst->instr, "CLAMP"    ) == 0) reg_name = "BYPASS";
      else if (strcasecmp( cinst->instr, "EXTEST"   ) == 0) reg_name = "BSR";
      else if (strcasecmp( cinst->instr, "HIGHZ"    ) == 0) reg_name = "BYPASS";
      else if (strcasecmp( cinst->instr, "IDCODE"   ) == 0) reg_name = "DIR";
      else if (strcasecmp( cinst->instr, "INTEST"   ) == 0) reg_name = "BSR";
      else if (strcasecmp( cinst->instr, "PRELOAD"  ) == 0) reg_name = "BSR";
      else if (strcasecmp( cinst->instr, "SAMPLE"   ) == 0) reg_name = "BSR";
      else if (strcasecmp( cinst->instr, "USERCODE" ) == 0) reg_name = "USERCODE";
    }

    if (strcasecmp( cinst->instr, "SAMPLE" ) == 0)
      instr_name = "SAMPLE/PRELOAD";
    else
      instr_name = cinst->instr;

    if (reg_name)
    {
      char *cmd[] = {"instruction",
                     instr_name,
                     cinst->opcode,
                     reg_name,
                     NULL};

      if (jc->proc_mode & BSDL_MODE_INSTR_EXEC)
        cmd_run( jc->chain, cmd );
      if (jc->proc_mode & BSDL_MODE_INSTR_PRINT)
        print_cmd( cmd );
    }

    cinst = cinst->next;
  }

  return 1;
}
예제 #22
0
/*****************************************************************************
 * int bsdl_process_cell_info( jtag_ctrl_t *jc )
 * Cell Info management function
 *
 * Creates a BSR cell from the temporary storage variables via shell command
 *   bit <bit_num> <type> <default> <signal> [<cbit> <cval> Z]
 *
 * Parameters
 *   jc : jtag control structure
 *
 * Returns
 *   1 -> all ok
 *   0 -> error occured
 ****************************************************************************/
static int bsdl_process_cell_info( jtag_ctrl_t *jc )
{
  cell_info_t *ci = jc->cell_info_first;
  const size_t str_len = 10;
  char bit_num_str[str_len+1];
  char ctrl_bit_num_str[str_len+1];
  char disable_safe_value_str[str_len+1];
  char *cmd[] = {"bit",
                 bit_num_str,
                 NULL,
                 NULL,
                 NULL,
                 NULL,
                 disable_safe_value_str,
                 "Z",
                 NULL};

  while (ci)
  {
    /* convert bit number to string */
    snprintf( bit_num_str, str_len, "%i", ci->bit_num );
    bit_num_str[str_len] = '\0';
    /* convert cell function from BSDL token to jtag syntax */
    switch (ci->cell_function)
    {
      case INTERNAL:
        /* fall through */
      case OUTPUT2:
        /* fall through */
      case OUTPUT3:
        cmd[2] = "O";
        break;
      case OBSERVE_ONLY:
        /* fall through */
      case INPUT:
        /* fall through */
      case CLOCK:
        cmd[2] = "I";
        break;
      case CONTROL:
        /* fall through */
      case CONTROLR:
        cmd[2] = "C";
        break;
      case BIDIR:
        cmd[2] = "B";
        break;
      default:
        /* spoil command */
        cmd[2] = "?";
        break;
    }
    /* convert basic safe value */
    cmd[3] = strcasecmp( ci->basic_safe_value, "x" ) == 0 ? "?" : ci->basic_safe_value;
    /* apply port name */
    cmd[4] = ci->port_name;

    /* add disable spec if present */
    if (ci->ctrl_bit_num >= 0)
    {
      /* convert bit number to string */
      snprintf( ctrl_bit_num_str, str_len, "%i", ci->ctrl_bit_num );
      ctrl_bit_num_str[str_len] = '\0';
      /* convert disable safe value to string */
      snprintf( disable_safe_value_str, str_len, "%i", ci->disable_safe_value );
      disable_safe_value_str[str_len] = '\0';
      cmd[5] = ctrl_bit_num_str;
    }
    else
      /* stop command procssing here */
      cmd[5] = NULL;

    if (jc->proc_mode & BSDL_MODE_INSTR_EXEC)
      cmd_run( jc->chain, cmd );
    if (jc->proc_mode & BSDL_MODE_INSTR_PRINT)
      print_cmd( cmd );

    ci = ci->next;
  }

  return 1;
}
예제 #23
0
/*****************************************************************************
 函 数 名  : ws__getRecentOperationLog
 功能描述  : web service实现函数,最新日志的显示
             本函数由search函数简化而来
 输入参数  : soap       ---- web service执行环境
             
 输出参数  : ret        ---- 返回结果
 返 回 值  : WS_OK		---- 执行成功
             soapFault  ---- 执行失败
 调用函数  : 
 被调函数  : 
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月8日
     
    修改内容   : 新生成函数
*****************************************************************************/
int ws__getRecentOperationLog(WS_ENV* ws_env, int offset, int count, struct ws__getRecentOperationLog_Response *ret)
{
    int ws_err;
    int sys_error_code = ERROR_SUCCESS;
    unsigned int start_hour=0, end_hour=0;
    char start_date[50]={0}, end_date[50]={0}, file_name[100], command[500], debug[100], searchcmd[100], vfwid[20];
    int cmd_start_len, cmd_len;
    enum file_name_check_e file_check;
    int total = 0, file_count;
    int count_left, offset_left = offset, start_pos, end_pos;
    struct OperLogContent *log_content;
    int saved_log = 0;
    FILE * fp = NULL;
    int i, vrfid;
    long exporting;

	vrfid = login_get_current_user_vfw_id();
	snprintf(vfwid, sizeof(vfwid),"%d", vrfid);

    /* 获得是否正在导出的标记 */
    exporting = (long)ws_get_private_data(ws_env);

    /* 检查$vCount, $vOffset参数是否合法 */
    if (WS_OK != (ws_err = ws_check_offset_count(ws_env, offset, &count)))
    {
        return ws_err;
    }
    if (offset != 0)
    {
        /* $vOffset不支持不为0的情况 */
        return ws_send_soap_error(ws_env, "Offset must be 0!");
    }
    if (count > LOG_MAX_COUNT)
    {
        //count数受限
        count = LOG_MAX_COUNT;
    }
    count_left = count;
    
    /* 调用库函数glob列出文件名,并将其存入数组 */
	if(0 == vrfid)
	{
        fp = cmd_run(CMD_LS " " OPERA_LOG_PATH "/" FLAG_OPER "*.l*");
	}
	else
	{
        sprintf(searchcmd, "%s%d%s", CMD_LS " " OPERA_LOG_PATH "/", vrfid,"_" FLAG_OPER "*.l*");
		fp = cmd_run(searchcmd);
	}
    

    if (NULL == fp)
    {
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }
    
    /* 因为不知道能有多少条记录,所以按最大量分配 */
    log_content = (struct OperLogContent*)ws_malloc(ws_env, (u_int32_t)count*sizeof(struct OperLogContent));
    if (NULL == log_content)
    {
        return ws_new_soap_fault(ws_env, ERROR_SYSTEM);
    }

    // 构造初始命令
    cmd_start_len = sprintf(command, "(");
    while (!feof(fp) && ERROR_SUCCESS == sys_error_code)
    {
        if (NULL == fgets(file_name, sizeof(file_name), fp))
        {
            // end of file
            break;
        }
        // 去掉结尾换行符
        for (i = (int)strlen(file_name) -1; i >=0; i--)
        {
            if ('\n' == file_name[i] || '\r' == file_name[i])
            {
                file_name[i] = '\0';
            }
            else
            {
                break;
            }
        }
        WEB_SEND_DEBUG_ss("checking operalog file:",file_name);
        
        /* 检查文件名,确认是否在搜索范围内 */
        file_check = (enum file_name_check_e)check_log_file_name(file_name, start_date, end_date);

        if (FILE_NAME_CHK_FAIL == file_check )
        {
            //文件名不匹配
            continue;
        }
        cmd_len = cmd_start_len 
                + make_file_search_cmd(file_name, file_check, NULL, NULL, NULL,
                        start_hour, end_hour,
                        command + cmd_start_len);

        /* 得到总数的命令 */
        sprintf(command + cmd_len, ") |wc -l");
        /* 保护局部变量 */
        command[sizeof(command) - 1 ] = '\0';
        /* 运行脚本得到总数 */
        sys_error_code = run_to_get_total(command, (unsigned int*)&file_count);
//printf("--11--%s, %d, %d\n\n", command, file_count, sys_error_code);
        if (ERROR_SUCCESS != sys_error_code)
        {
            break;
        }
        total += file_count;

        if (count_left <= 0)
        {
            // 已经取完结果,只需计算总数
            WEB_SEND_DEBUG_ss(file_name, ": finished.");
            continue;
        }
        if (offset_left >= file_count)
        {
            // 现在不需要取数据
            WEB_SEND_DEBUG_ss(file_name, ": skipped.");
            offset_left -= file_count;
            continue;
        }
        /* 需要取数据,计算结束位置 */
        end_pos = file_count - offset_left;

        /* 计算开始位置,开始位置从1开始计数 */
        start_pos = ((file_count - offset_left) - count_left) + 1;
        if (start_pos >= 1)
        {
            // 本文件可以全部取完
            count_left = 0;
        }
        else
        {
            //还需要取下一个文件
            count_left = (0 - start_pos) + 1;
            start_pos = 1;
        }
        // 如果没取完,下次从0开始
        offset_left = 0;

    
        /* 得到所需结果的命令 */
        sprintf(command + cmd_len, ") |sed -n %d,%dp",
                start_pos, end_pos);
        /* 保护局部变量 */
        command[sizeof(command) - 1 ] = '\0';

//printf("\n--22--%s--\n\n", command);

        sprintf(debug, ": parse log %d to %d", start_pos, end_pos);
        WEB_SEND_DEBUG_ss(file_name, debug);
        sys_error_code = make_opera_log_result(ws_env, command, 
                log_content + saved_log, (end_pos - start_pos) + 1, exporting, vfwid);
        saved_log += ((end_pos - start_pos) + 1);

        if (saved_log >= count)
        {
            // 数量够了
            break;
        }
    }
    cmd_closeio(fp);
    if (ERROR_SUCCESS != sys_error_code)
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }
	
    if(DISK_LOG_EXPORTING == exporting)
    {
        saved_log = 0;
    }

    ret->ret.sum = total;
    ret->ret.res_USCOREcount = ret->ret.__size = saved_log;
    ret->ret.__ptrres = log_content;
    return WS_OK;
}
예제 #24
0
/*****************************************************************************
 函 数 名  : systeminfo_translate_value
 功能描述  : systeminfo值替换
 输入参数  : user_op        ---- user_opetate结构
             original_flag  ---- 原始替换标记
             helper         ---- 分割后的替换标记
             trans_type     ---- 替换值的类型
             trans_data     ---- 替换的具体值
 输出参数  : 无
 返 回 值  : WS_OK		    ---- 执行成功
 调用函数  :
 被调函数  :
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月8日

    修改内容   : 新生成函数
*****************************************************************************/
u_int32_t systeminfo_translate_value(UserOperate_t* user_op,
        ResultContext_t *result_context,
        char* original_flag, char* helper, u_int32_t position,
        u_int32_t trans_type, void* trans_data, s32 trans_data_int)
{
    char today[30], zone_Name[50];
    char dev_name[64] = {0};
    struct uo_systeminfo_t *my_data;
    FILE *fp;
    MEMBUFF *buff;
    time_t now;
    int tz;
    int tz_hour;
    int tz_min;
    struct tm  tcur;
    struct drv_cli_board_info board_info = {0};
    int retcode;
    s32 num;
    s32 ret = 0;


	sqlite3 * dba_con=NULL;
	sqlite3_res dba_res;	
    s32 dev_type;
	s32 rc;
	static s32 flag=0;
	u64 max_stream = 0;
    SEM_ID_T semid;

    time(&now);
    localtime_r(&now,&tcur);
    tz = tcur.tm_gmtoff / 60;

    my_data = (struct uo_systeminfo_t*)UserOperate__getUserData(user_op);
     //vsm
    if(strcmp(helper,"vsm_enable") == 0)
    {    
        /*enable  返回1     disable 返回0*/
        http_out("%d", ifm_is_stack_enable());
    }
    else if(strcmp(helper,"vsm_id") == 0)
    {
        http_out("%d", ifm_syscall_get_vsm_id());
    }	
	else if(strcmp(helper, "slot_offset") == 0)
	{
		//获取槽号偏移。
		http_out("%d", ifm_syscall_get_slot_offset());
	}
	
    //set_zone_from_env(my_data->zoneName);
    else if (strcmp(helper, "DevName") == 0)
    {
        dev_name[0] = '\0';
        wrap_drv_get_product_name(dev_name, sizeof(dev_name));
        http_out_buf(dev_name, strlen(dev_name));
    }
    else if (0 == strcmp(helper, "SysName"))
    {
    fp = cmd_run("hostname");
    if(NULL == fp)
        {
            return DefaultTranslate__I_OK;
        }
        buff = membuff_readfile(fp);
        cmd_closeio(fp);
        if(NULL == buff)
        {
            return DefaultTranslate__I_OK;
        }
        membuff_tolineformat(buff, FORMAT_TRIM);
        if(buff->len <1 || buff->array[0]->len <1)
        {
            membuff_free(buff);
            return DefaultTranslate__I_OK;
        }
        http_out("%s", buff->array[0]->buff);
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "SystemDate") || 0 == strcmp(helper, "timeValue"))
    {
        strftime(today, sizeof(today), "%Y-%m-%d %T", &tcur);
        http_out("%s", today);
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "time_zone"))
    {
        http_out("%d", tz);
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "slot_num"))
    {
        ret = sys_read_board_info(DRV_DEV_BOARD_BOARD_NUM, &num, sizeof(num));
        num = num -1;
        if (ERROR_SUCCESS == ret)
        {
            http_out("%d", num);
        }
        else
        {
            http_out("0");
        }
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "power_num"))
    {
        ret = sys_read_board_info(DRV_DEV_BOARD_POWER_NUM, &num, sizeof(num));
        if (ERROR_SUCCESS == ret)
        {
            http_out("%d", num);
        }
        else
        {
            http_out("0");
        }
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "fan_num"))
    {
        /* TODO: modify for driver */
        ret = wrap_drv_dev_get_fan_num(&num);
        if (ERROR_SUCCESS == ret)
        {
            http_out("%d", num);
        }
        else
        {
            http_out("0");
        }
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "power"))
    {
        ret = sys_read_board_info(DRV_DEV_BOARD_POWER_POWER, &num, sizeof(num));
        if (ERROR_SUCCESS == ret)
        {
            http_out("%d", num);
        }
        else
        {
            http_out("0");
        }
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "softwareVersion"))
    {
        http_out("%s", VERSION_NO);
        return DefaultTranslate__I_OK;
    }
    else if(0 == strcmp(helper, "TimeZone"))
    {
        tz_hour = abs(tz / 60);
        tz_min  = abs(tz % 60);

        snprintf(zone_Name, sizeof(zone_Name), "GMT%c%02d:%02d", (tz >= 0)?'+':'-',tz_hour , tz_min);
        http_out("%s", zone_Name);
        return DefaultTranslate__I_OK;
    }
    else if ( 0 == strcmp(helper, "devSpace") )
    {
    	http_out("%.1f", trans_data_int/1024.0);
        return DefaultTranslate__I_OK;
    }
    else if ( 0 == strcmp(helper, "ipsgen") )
    {
        board_info.slot_no = 1;
        retcode = sys_read_board_info(DRV_DEV_BOARD_BOARD_INFO, &board_info, sizeof(struct drv_cli_board_info));
        if(strcmp(board_info.board_name,"DP1IPS3KGED")==0)
        {
            return DefaultTranslate__I_IF_IS_TRUE;
        }
        else
        {
            return DefaultTranslate__I_IF_IS_FALSE;
        }
    }
    else if (strcmp(helper, "isips") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));

        if(0 == strncmp("UAG",dev_name,3))
        {
            if(DRV_CAPABILITY_ENABLE == wrap_drv_dev_get_system_capability(DRV_CAPABILITY_FPGA))
            {
                http_out("1");
            }
            else
            {
                http_out("0");
            }
        }
        else if (0 == strncmp("IPS",dev_name,3))
        {
              http_out("1");
        }
        else
        {
              http_out("0");
        }
    }
    else if (strcmp(helper, "isfw") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));

        if (0 == strncmp("FW",dev_name,2))
        {
            http_out("1");
        }
        else
        {
            http_out("0");
        }
    }
	else if (strcmp(helper, "isutm") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));

        if (0 == strncmp("UTM",dev_name,3))
        {
            http_out("1");
        }
        else
        {
            http_out("0");
        }
    }
    else if (strcmp(helper, "issrg") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));

        if (0 == strncmp("SRG",dev_name,3))
        {
            http_out("1");
        }
        else
        {
            http_out("0");
        }
    }
    else if (strcmp(helper, "isuag") == 0)
    {
        wrap_drv_get_device_type(dev_name, sizeof(dev_name));
        if (0 == strncmp("UAG", dev_name, 3))
        {
        	
			dev_type = web_get_slot_type();
			if (dev_type == 0)
			{
				dba_con = sqlite3_open_ex(1, SSA_CFG_DBFILE);
			}
			if(dba_con==NULL)
			{
				http_out("0");
				goto lable;
			}
			snprintf(g_sqlite_sql_buf,SQLITE_SQL_BUF_SIZE,"select switch from tb_ssa_log_switch;");
			sqlite3_exec_query_ex(dba_con,g_sqlite_sql_buf,&dba_res);
			sqlite3_get_s32_ex(dba_res,0,"switch",&flag);
			sqlite3_res_free_ex(dba_res);	dba_res=NULL;
			if(3==flag)
			{
				sqlite3_close_ex(dba_con);	dba_con=NULL;
				http_out("0");
				flag=0;
				goto lable;	
			}
			flag=0;
        	snprintf(g_sqlite_sql_buf,SQLITE_SQL_BUF_SIZE,"select sum(state) flag from tb_ssa_log_cfg where log_id=%u or log_id=%u",
				SSA_LOG_TYPE_IF,SSA_LOG_TYPE_IP);
			rc=sqlite3_exec_query_ex(dba_con,g_sqlite_sql_buf,&dba_res);
			if(rc!=SQLITE_OK)
			{
				sqlite3_close_ex(dba_con);
				http_out("0");
				goto lable;
				
			}
			rc=sqlite3_get_s32_ex(dba_res,0,"flag",&flag);
			if(rc!=SQLITE_OK||flag==0)
			{
				flag=0;	
				sqlite3_res_free_ex(dba_res);
				sqlite3_close_ex(dba_con);
				http_out("0");
				goto lable;
			}
			flag=1;
			sqlite3_res_free_ex(dba_res);
			sqlite3_close_ex(dba_con);
            http_out("1");
        }
        else
        {
            http_out("0");
        }
    }
	else if(strcmp(helper, "uag") == 0)
	{
		wrap_drv_get_device_type(dev_name, sizeof(dev_name));
        if (0 == strncmp("UAG", dev_name, 3))
        {
        	if(flag)
            {
				flag=0;
            	return DefaultTranslate__I_IF_IS_TRUE;
        	}
			else
			{
				return DefaultTranslate__I_IF_IS_FALSE;
			}
			
        }
        else
        {
            return DefaultTranslate__I_IF_IS_FALSE;
				
        }
	}
	else if (strcmp(helper, "oem") == 0)
    {
    	
    	if (OEM_DPTECH == get_isoem())
	    {
		       return DefaultTranslate__I_IF_IS_TRUE;
	    }
	    else
	    {
		      return DefaultTranslate__I_IF_IS_FALSE;
	    }
		
		
    }
	else if (strcmp(helper, "oem_cicotec") == 0)
    {
    	if (OEM_CICOTEC == get_isoem())
	    {
		       return DefaultTranslate__I_IF_IS_TRUE;
	    }
	    else
	    {
		       return DefaultTranslate__I_IF_IS_FALSE;
	    }
		
		
    }
	else if (strcmp(helper, "oem_zwtec") == 0)
    {	
    	if (OEM_ZWTEC == get_isoem())
	    {
		       return DefaultTranslate__I_IF_IS_TRUE;
	    }
	    else
	    {
		       return DefaultTranslate__I_IF_IS_FALSE;
	    }
		
		
    }
	else if (strcmp(helper, "oem_blank") == 0)
    {	
    	if (OEM_BLANK == get_isoem())
	    {
		       return DefaultTranslate__I_IF_IS_TRUE;
	    }
	    else
	    {
		       return DefaultTranslate__I_IF_IS_FALSE;
	    }
		
		
    }
	else if (strcmp(helper, "has_vcpu") == 0)
	{
        	s32 vcpu_max_count;
		vcpu_max_count = sysconf(_SC_NPROCESSORS_CONF);
		if(vcpu_max_count < 2)
		{
	        return DefaultTranslate__I_IF_IS_FALSE;
		}
		else
		{
			return DefaultTranslate__I_IF_IS_TRUE;
		}
	}
    else if (strcmp(helper, "eth") == 0)
    {
        http_out("%s", my_data->flux_opt.ethname);
    }
	else if(strcmp(helper, "unitnum") == 0)
	{
		if(my_data->flux_opt.unitnum>0)
		{
			http_out("%u",my_data->flux_opt.unitnum);
		}
		else
		{
			sem_get_binary_sem(SEM_KEY_SSA_FIRSTPAGE, &semid);
	        	sem_oper_lock(semid);
	        	max_stream = get_flux_firstpage_unit(my_data->flux_opt.ethname);
	        	sem_oper_unlock(semid);
	       
	    		if(max_stream < REPORT_UNIT_SPEED_MBPS)
	     		{
	     			http_out("%u",REPORT_UNIT_SPEED_KBPS); 
				strcpy(my_data->flux_opt.unitname,"Kbps");
	     		}
	     		else if(max_stream < REPORT_UNIT_SPEED_GBPS)
	     		{
	     			http_out("%u",REPORT_UNIT_SPEED_MBPS);
				strcpy(my_data->flux_opt.unitname,"Mbps");
	     		}
	     		else
	     		{
	     			http_out("%u",REPORT_UNIT_SPEED_GBPS);
				strcpy(my_data->flux_opt.unitname,"Gbps");
	     		}
		}
	}
	else if(strcmp(helper, "unitname") == 0)
	{		
		http_out("%s",my_data->flux_opt.unitname); 			
    }
	else if(strcmp(helper,"dpxorfw") == 0)
	{
		wrap_drv_get_device_type(dev_name, sizeof(dev_name));
		if(0 == strncmp("DPX",dev_name,3) || 0 == strncmp("FW",dev_name,2))
		{
			return DefaultTranslate__I_IF_IS_TRUE;
		}
		else
		{
			return DefaultTranslate__I_IF_IS_FALSE;
		}
	}
lable:
    return user_op->parent_translateValue(user_op, result_context,
            original_flag, helper, position, trans_type, trans_data, trans_data_int);
}
예제 #25
0
/*******************************************************************************
 函数名称: make_opera_log_result
 功能描述: 运行命令,生成日志返回值。倒序存放
 输入参数: ws_env,web service运行时的环境变量
           cmd,要运行的命令
           count,结果数
 输出参数: log_content_ptr,存放日志内容的指针
 返 回 值: ERROR_SUCCESS,操作成功
           ERROR_FAIL,操作失败
--------------------------------------------------------------------------------
 最近一次修改记录:
 修改作者: qianjunjie
 修改目的: 根据新的日志格式重新修改了日志格式识别流程
 修改日期: 2009年7月1日
*******************************************************************************/
static int make_opera_log_result(WS_ENV* ws_env, char* cmd, struct OperLogContent *log_content_ptr, int count, long exporting, char * vfwid)
{
    FILE * fp = NULL;
    char* file_buf;
    int sys_error_code = ERROR_SUCCESS;
    regex_t preg_op1, preg_op2;
    regmatch_t pmatch[20];
    char time_stamp[20], vfwname[20];
    int dif_log, errindex;
    struct OperLogContent *log_content;
    int i;
    s8 * vfwname_tmp;

	sqlite3_res res = NULL;
	sqlite3* db = NULL;
	char sql[200];
	s32 result;
	s8 * tmp;

	db = sqlite3_open_ex(1, "/config/db/vfw_cfg.db");
	if(NULL == db)
	{
        return SQLITE_FAILD_OPEN;
	}

	snprintf(sql, sizeof(sql), "select name from tb_vfw where vfw_id = %s;", vfwid);
	result = (u32)sqlite3_exec_query_ex(db, sql, &res);
	if(SQLITE_OK != result)
	{
        return SQLITE_ERROR;
	}

	if(SQLITE_OK != sqlite3_get_str_ex(res, 0, "name", &tmp))
	{
        sqlite3_close_ex(db);
		return SQLITE_ERROR;
	}
	vfwname_tmp = ws_strdup(ws_env, tmp);
    sqlite3_res_free_ex(res);
	res = NULL;
	strncpy(vfwname, ws_iconv_utf8_to_gbk(ws_env, vfwname_tmp), sizeof(vfwname));

	sqlite3_close_ex(db);
    memset(&preg_op1, 0, sizeof(regex_t));
    memset(&preg_op2, 0, sizeof(regex_t));
    if(0 != regcomp(&preg_op1, MATCH_OPER_LOG_1, REG_EXTENDED))
    {
        WEB_SEND_DEBUG_ss("compile regexp fail:", MATCH_OPER_LOG_1);
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }
    if(0 != regcomp(&preg_op2, MATCH_OPER_LOG_2, REG_EXTENDED))
    {
        WEB_SEND_DEBUG_ss("compile regexp fail:", MATCH_OPER_LOG_2);
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }
    
    fp = cmd_run(cmd);
    if (NULL == fp)
    {
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }

    file_buf = (char*)ws_malloc(ws_env, LOG_LINE_MAX*(u_int32_t)count);
    if (NULL == file_buf)
    {
        return ERROR_SYSTEM;
    }

    /* 日志需要反着填 */
    log_content = log_content_ptr + count -1;
    while (!feof(fp) && log_content >= log_content_ptr)
    {
        
        if (NULL == fgets(file_buf, LOG_LINE_MAX, fp))
        {
            // end of file
            break;
        }
        /* 防止越界 */
        file_buf[LOG_LINE_MAX - 1] = '\0';
        
        // 去掉结尾换行符
        for (i = (int)strlen(file_buf) -1; i >=0; i--)
        {
            if ('\n' == file_buf[i] || '\r' == file_buf[i])
            {
                file_buf[i] = '\0';
            }
            else
            {
                break;
            }
        }

        /* 拆分日志 */
        sys_error_code = split_log(file_buf, &preg_op1, &preg_op2, 
        	        sizeof(pmatch)/sizeof(regmatch_t), pmatch,
        	        time_stamp, &dif_log);

        /*如果日志格式识别失败,应该立即返回,避免在下面的流程中出现异常*/
        if(sys_error_code != ERROR_SUCCESS)
        {
            cmd_closeio(fp);
            return  sys_error_code;
        }

        log_content->timestamp = ws_strdup(ws_env, time_stamp);
        log_content->hostname = file_buf + pmatch[HOST_NAME_LOG + dif_log].rm_so;
        log_content->degree = atoi(file_buf + pmatch[SERVERITY_LOG + dif_log].rm_so);
        log_content->client_USCOREtype = file_buf + pmatch[CLIENT_TYPE_LOG + dif_log].rm_so;
        log_content->username = file_buf + pmatch[OPER_LOG_USR + dif_log].rm_so;
        log_content->hostip = file_buf + pmatch[OPER_LOG_IP + dif_log].rm_so;
        log_content->content = file_buf + pmatch[LOG_TYPE + dif_log + 9].rm_so;
		log_content->vfwname = ws_strdup(ws_env, vfwname);

        errindex = atoi(file_buf + pmatch[OPER_LOG_ERRINDEX + dif_log].rm_so);
        if (0 == errindex)
        {
            log_content->errindex = "success";
        }
        else
        {
            log_content->errindex = "fail";
        }
        
        if (DISK_LOG_EXPORTING == exporting)
        {
            // 正在导出,在这里直接输出。导出的时候每次填在固定位置
            http_out("\"%s\",%s,%s,%s,%s,%s,\"%s\"\r\n",
                    vfwname,
                    log_content->timestamp,
                    log_content->client_USCOREtype, log_content->username,
                    log_content->hostip, log_content->errindex, 
                    ws_iconv_utf8_to_gbk(ws_env, log_content->content));
        }
        else
        {
            //正常搜索要反着填,每次填在缓冲区的不同位置
            log_content--;
            file_buf += LOG_LINE_MAX;
        }
    }

    cmd_closeio(fp);

    return  sys_error_code;
}
예제 #26
0
파일: script.c 프로젝트: EXio4/Lex4
// runs a script
// returns -1 is esc was pressed, 0 o/w
int run_script(char *script, DATAFILE *d) {
    char buf[512];
    Ttoken *token;
	int i;

	// set datafile
	data = d;

	clear_keybuf();

	// init sound memory
	for(i = 0; i < MAX_SCRIPT_SOUNDS; i ++) active_sounds[i] = -1;

	// create gfx buffers
    swap_buffer = create_bitmap(160, 120);
	buffer = create_bitmap(160, 120);

    script_done = FALSE;
    
    while(!script_done) {
      
		// get commands from script string
		script = get_line(buf, script);
		
		if (buf[0] != '#' && buf[0] != '\n' && buf[0] != '\r' && buf[0] != '-') {
			token = tokenize(buf);	
			if (token != NULL) {
				if      (!stricmp(token->word, "load_map"))		cmd_loadmap(get_next_word(token));
				else if (!stricmp(token->word, "draw_map"))		cmd_drawmap();
				else if (!stricmp(token->word, "set"))			cmd_set((Ttoken *)token->next);
				else if (!stricmp(token->word, "move"))			cmd_move((Ttoken *)token->next);
				else if (!stricmp(token->word, "delete"))		cmd_del((Ttoken *)token->next);
				else if (!stricmp(token->word, "run"))			cmd_run((Ttoken *)token->next);
				else if (!stricmp(token->word, "speak"))		cmd_speak((Ttoken *)token->next, 1);
				else if (!stricmp(token->word, "text"))			cmd_speak((Ttoken *)token->next, 0);
				else if (!stricmp(token->word, "save_buffer"))	cmd_savebmp();
				else if (!stricmp(token->word, "show_bmp"))		cmd_showbmp(get_next_word(token));
				else if (!stricmp(token->word, "blit"))			cmd_blit();
				else if (!stricmp(token->word, "fade_in"))		cmd_fadein();
				else if (!stricmp(token->word, "fade_out"))		cmd_fadeout();
				else if (!stricmp(token->word, "wait"))			cmd_wait(atoi(get_next_word(token)));
				else if (!stricmp(token->word, "play_sample"))  cmd_play_sample((Ttoken *)token->next);
				else if (!stricmp(token->word, "stop_sample"))  cmd_stop_sample((Ttoken *)token->next);
				else if (!stricmp(token->word, "end_script"))	cmd_end();
				else {
					char msg[256];
					sprintf(msg, "unknown: %s", token->word);
					msg_box(msg);
				}
				
				flush_tokens(token);
			}
		}
    }

	// destroy buffers
	delete_all_objects();
	destroy_bitmap(buffer);
	destroy_bitmap(swap_buffer);

	// stop old sounds
	for(i = 0; i < MAX_SCRIPT_SOUNDS; i ++) {
		if (active_sounds[i] != -1) {
			stop_sound_id(active_sounds[i]);
			forget_sound(active_sounds[i]);
		}
	}

	return (script_done == -1 ? -1 : 0);
}
예제 #27
0
int
main (int argc, char **argv)
{
	char *input_buffer;
	char *input_line;
	char *procprog;

	pid_t mypid = 0;
	int procuid = 0;
	pid_t procpid = 0;
	pid_t procppid = 0;
	int procvsz = 0;
	int procrss = 0;
	int procseconds = 0;
	float procpcpu = 0;
	char procstat[8];
	char procetime[MAX_INPUT_BUFFER] = { '\0' };
	char *procargs;

	const char *zombie = "Z";

	int resultsum = 0; /* bitmask of the filter criteria met by a process */
	int found = 0; /* counter for number of lines returned in `ps` output */
	int procs = 0; /* counter for number of processes meeting filter criteria */
	int pos; /* number of spaces before 'args' in `ps` output */
	int cols; /* number of columns in ps output */
	int expected_cols = PS_COLS - 1;
	int warn = 0; /* number of processes in warn state */
	int crit = 0; /* number of processes in crit state */
	int i = 0, j = 0;
	int result = STATE_UNKNOWN;
	output chld_out, chld_err;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);
	setlocale(LC_NUMERIC, "POSIX");

	input_buffer = malloc (MAX_INPUT_BUFFER);
	procprog = malloc (MAX_INPUT_BUFFER);

	xasprintf (&metric_name, "PROCS");
	metric = METRIC_PROCS;

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage4 (_("Could not parse arguments"));

	/* get our pid */
	mypid = getpid();

	/* Set signal handling and alarm timeout */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		die (STATE_UNKNOWN, _("Cannot catch SIGALRM"));
	}
	(void) alarm ((unsigned) timeout_interval);

	if (verbose >= 2)
		printf (_("CMD: %s\n"), PS_COMMAND);

	if (input_filename == NULL) {
		result = cmd_run( PS_COMMAND, &chld_out, &chld_err, 0);
		if (chld_err.lines > 0) {
			printf ("%s: %s", _("System call sent warnings to stderr"), chld_err.line[0]);
			exit(STATE_WARNING);
		}
	} else {
		result = cmd_file_read( input_filename, &chld_out, 0);
	}

	/* flush first line: j starts at 1 */
	for (j = 1; j < chld_out.lines; j++) {
		input_line = chld_out.line[j];

		if (verbose >= 3)
			printf ("%s", input_line);

		strcpy (procprog, "");
		xasprintf (&procargs, "%s", "");

		cols = sscanf (input_line, PS_FORMAT, PS_VARLIST);

		/* Zombie processes do not give a procprog command */
		if ( cols < expected_cols && strstr(procstat, zombie) ) {
			cols = expected_cols;
		}
		if ( cols >= expected_cols ) {
			resultsum = 0;
			xasprintf (&procargs, "%s", input_line + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			strcpy(procprog, base_name(procprog));

			/* we need to convert the elapsed time to seconds */
			procseconds = convert_to_seconds(procetime);

			if (verbose >= 3)
				printf ("proc#=%d uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", 
					procs, procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat, 
					procetime, procprog, procargs);

			/* Ignore self */
			if (mypid == procpid) continue;

			if ((options & STAT) && (strstr (statopts, procstat)))
				resultsum |= STAT;
			if ((options & ARGS) && procargs && (strstr (procargs, args) != NULL))
				resultsum |= ARGS;
			if ((options & EREG_ARGS) && procargs && (regexec(&re_args, procargs, (size_t) 0, NULL, 0) == 0))
				resultsum |= EREG_ARGS;
			if ((options & PROG) && procprog && (strcmp (prog, procprog) == 0))
				resultsum |= PROG;
			if ((options & PPID) && (procppid == ppid))
				resultsum |= PPID;
			if ((options & USER) && (procuid == uid))
				resultsum |= USER;
			if ((options & VSZ)  && (procvsz >= vsz))
				resultsum |= VSZ;
			if ((options & RSS)  && (procrss >= rss))
				resultsum |= RSS;
			if ((options & PCPU)  && (procpcpu >= pcpu))
				resultsum |= PCPU;

			found++;

			/* Next line if filters not matched */
			if (!(options == resultsum || options == ALL))
				continue;

			procs++;
			if (verbose >= 2) {
				printf ("Matched: uid=%d vsz=%d rss=%d pid=%d ppid=%d pcpu=%.2f stat=%s etime=%s prog=%s args=%s\n", 
					procuid, procvsz, procrss,
					procpid, procppid, procpcpu, procstat, 
					procetime, procprog, procargs);
			}

			if (metric == METRIC_VSZ)
				i = get_status ((double)procvsz, procs_thresholds);
			else if (metric == METRIC_RSS)
				i = get_status ((double)procrss, procs_thresholds);
			/* TODO? float thresholds for --metric=CPU */
			else if (metric == METRIC_CPU)
				i = get_status (procpcpu, procs_thresholds);
			else if (metric == METRIC_ELAPSED)
				i = get_status ((double)procseconds, procs_thresholds);

			if (metric != METRIC_PROCS) {
				if (i == STATE_WARNING) {
					warn++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
				if (i == STATE_CRITICAL) {
					crit++;
					xasprintf (&fails, "%s%s%s", fails, (strcmp(fails,"") ? ", " : ""), procprog);
					result = max_state (result, i);
				}
			}
		} 
		/* This should not happen */
		else if (verbose) {
			printf(_("Not parseable: %s"), input_buffer);
		}
	}

	if (found == 0) {							/* no process lines parsed so return STATE_UNKNOWN */
		printf (_("Unable to read output\n"));
		return STATE_UNKNOWN;
	}

	if ( result == STATE_UNKNOWN ) 
		result = STATE_OK;

	/* Needed if procs found, but none match filter */
	if ( metric == METRIC_PROCS ) {
		result = max_state (result, get_status ((double)procs, procs_thresholds) );
	}

	if ( result == STATE_OK ) {
		printf ("%s %s: ", metric_name, _("OK"));
	} else if (result == STATE_WARNING) {
		printf ("%s %s: ", metric_name, _("WARNING"));
		if ( metric != METRIC_PROCS ) {
			printf (_("%d warn out of "), warn);
		}
	} else if (result == STATE_CRITICAL) {
		printf ("%s %s: ", metric_name, _("CRITICAL"));
		if (metric != METRIC_PROCS) {
			printf (_("%d crit, %d warn out of "), crit, warn);
		}
	} 
	printf (ngettext ("%d process", "%d processes", (unsigned long) procs), procs);
	
	if (strcmp(fmt,"") != 0) {
		printf (_(" with %s"), fmt);
	}

	if ( verbose >= 1 && strcmp(fails,"") )
		printf (" [%s]", fails);

	if (metric == METRIC_PROCS)
		printf (" | procs=%d;%s;%s;0;", procs,
				warning_range ? warning_range : "",
				critical_range ? critical_range : "");
	else
		printf (" | procs=%d;;;0; procs_warn=%d;;;0; procs_crit=%d;;;0;", procs, warn, crit);

	printf ("\n");
	return result;
}
예제 #28
0
/*****************************************************************************
 函 数 名  : ws__getUrlPolicyById
 功能描述  : web service实现函数,日志的查询
 输入参数  : soap       ---- web service执行环境
             
 输出参数  : ret        ---- 返回结果
 返 回 值  : WS_OK		---- 执行成功
             soapFault  ---- 执行失败
 调用函数  : 
 被调函数  : 
 ============================================================================
 修改历史      :
  1.日    期   : 2008年8月8日
     
    修改内容   : 新生成函数
*****************************************************************************/
int ws__searchOperationLog(WS_ENV* ws_env, char *userIp, char *userName, char* keyword, char *startTime, char *endTime, char * vrfid, int offset, int count, struct ws__searchOperationLog_Response *ret)
{
    unsigned int name_len;
    int ws_err;
    int sys_error_code = ERROR_SUCCESS;
    unsigned int start_hour=0, end_hour=0;
    char start_date[50]={0}, end_date[50]={0}, file_name[100], command[COMMAND_LENGTH*6], debug[100];
    int cmd_start_len, cmd_len;
    enum file_name_check_e file_check;
    int total = 0, file_count;
    int count_left, offset_left, start_pos, end_pos;
    struct OperLogContent *log_content;
    int saved_log = 0;
    FILE * fp = NULL;
    int i;
    long exporting;
	char searchcmd[200];

    /* 获得是否正在导出的标记 */
    exporting = (long)ws_get_private_data(ws_env);

    /* 检查用户名 */
    name_len = strlen(userName);
    if (('\0' != userName[0]) && ((name_len < 3) || (name_len > 20)))
    {
        return ws_send_soap_error(ws_env, "Incorrect username!");
    }
    
    /* 检查$vCount, $vOffset参数是否合法 */
    if (DISK_LOG_EXPORTING == exporting)
    {
        // 正在导出配置
        offset = 0;
        count = 1;
        saved_log = 1;
    }
    else
    {
        //正常搜索
        if (WS_OK != (ws_err = ws_check_offset_count(ws_env, offset, &count)))
        {
            return ws_err;
        }
        if (count > LOG_MAX_COUNT)
        {
            //count数受限
            count = LOG_MAX_COUNT;
        }
    }
    offset_left = offset;
    count_left = count;
    
    /* 判断输入ip是否合法,ip为空时默认为查询所有ip */
    if ('\0' != userIp [0]
        && WS_OK != (ws_err = ws_check_ip(ws_env, userIp, "userIp", NULL)))
    {
        return ws_err;
    }
    

    /* 拆分传入$vStartTime的日期格式 */
    if ('\0' != startTime[0] 
        && ERROR_SUCCESS != (sys_error_code = split_date(startTime, &start_hour, start_date)))
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }

    /* 拆分传入$vEndTime的日期格式 */
    if ('\0' != endTime[0] 
        && ERROR_SUCCESS != (sys_error_code = split_date(endTime, &end_hour, end_date)))
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }

    /* 调用库函数glob列出文件名,并将其存入数组 */
    if (DISK_LOG_EXPORTING == exporting)
    {
        if(strcmp("0", vrfid) != 0)
		{
	        sprintf(searchcmd, "%s%s%s",CMD_LS_EXPORT " " OPERA_LOG_PATH "/", vrfid, "_" FLAG_OPER "*.l*");
		}
		else
		{
	        sprintf(searchcmd, "%s",CMD_LS_EXPORT " " OPERA_LOG_PATH "/" FLAG_OPER "*.l*");
		}
	        //正在导出,使用正序
	        fp = cmd_run(searchcmd);
        //fp = cmd_run(CMD_LS_EXPORT " " OPERA_LOG_PATH "/" FLAG_OPER "*.l*");
    }
    else
    {
        if(strcmp("0", vrfid) != 0)
		{
	        sprintf(searchcmd, "%s%s%s",CMD_LS " " OPERA_LOG_PATH "/", vrfid, "_" FLAG_OPER "*.l*");
		}
		else
		{
	        sprintf(searchcmd, "%s",CMD_LS " " OPERA_LOG_PATH "/" FLAG_OPER "*.l*");
		}
        //一般搜索,使用倒序
        fp = cmd_run(searchcmd);
        //fp = cmd_run(CMD_LS " " OPERA_LOG_PATH "/" FLAG_OPER "*.l*");
    }

    if (NULL == fp)
    {
        return ws_send_soap_error(ws_env, "Searching log file list error!");
    }
    
    /* 因为不知道能有多少条记录,所以按最大量分配 */
    log_content = (struct OperLogContent*)ws_malloc(ws_env, (u_int32_t)count*sizeof(struct OperLogContent));
    if (NULL == log_content)
    {
        return ws_new_soap_fault(ws_env, ERROR_SYSTEM);
    }

    // 构造初始命令
    cmd_start_len = sprintf(command, "(");
    while (!feof(fp) && ERROR_SUCCESS == sys_error_code)
    {
        if (NULL == fgets(file_name, sizeof(file_name), fp))
        {
            // end of file
            break;
        }
        // 去掉结尾换行符
        for (i = (int)strlen(file_name) -1; i >=0; i--)
        {
            if ('\n' == file_name[i] || '\r' == file_name[i])
            {
                file_name[i] = '\0';
            }
            else
            {
                break;
            }
        }
        WEB_SEND_DEBUG_ss("checking operalog file:",file_name);
        
        /* 检查文件名,确认是否在搜索范围内 */
        file_check = (enum file_name_check_e)check_log_file_name(file_name, start_date, end_date);

        if (FILE_NAME_CHK_FAIL == file_check )
        {
            //文件名不匹配
            continue;
        }
        cmd_len = cmd_start_len 
                + make_file_search_cmd(file_name, file_check, userIp, userName, keyword,
                        start_hour, end_hour,
                        command + cmd_start_len);
        /* Modified by Fuzhiqing for Bug22 on 04-03-2009: There are too many users. */
        if(cmd_len == cmd_start_len - 1 )
        {
            return ws_send_soap_error(ws_env, "Too many administrators for searching deleted ones!");
        }

        if (DISK_LOG_EXPORTING == exporting)
        {
            //导出的时候只需取数据,不计算总数,不处理offset, count
            /* 得到所需结果的命令 */
            sprintf(command + cmd_len, ")");
            /* 保护局部变量 */
            command[sizeof(command) - 1 ] = '\0';

            sys_error_code = make_opera_log_result(ws_env, command, 
                    log_content , 1, exporting, vrfid);
        }
        else
        {
            //正常搜索要计算总数,offset, count
            /* 得到总数的命令 */
            sprintf(command + cmd_len, ") |wc -l");
            /* 保护局部变量 */
            command[sizeof(command) - 1 ] = '\0';
            /* 运行脚本得到总数 */
            sys_error_code = run_to_get_total(command, (unsigned int*)&file_count);

            if (ERROR_SUCCESS != sys_error_code)
            {
                break;
            }
            total += file_count;

            if (count_left <= 0)
            {
                // 已经取完结果,只需计算总数
                WEB_SEND_DEBUG_ss(file_name, ": finished.");
                continue;
            }
            if (offset_left >= file_count)
            {
                // 现在不需要取数据
                WEB_SEND_DEBUG_ss(file_name, ": skipped.");
                offset_left -= file_count;
                continue;
            }
            /* 需要取数据,计算结束位置 */
            end_pos = file_count - offset_left;

            /* 计算开始位置,开始位置从1开始计数 */
            start_pos = ((file_count - offset_left) - count_left) + 1;
            if (start_pos >= 1)
            {
                // 本文件可以全部取完
                count_left = 0;
            }
            else
            {
                //还需要取下一个文件
                count_left = (0 - start_pos) + 1;
                start_pos = 1;
            }
            // 如果没取完,下次从0开始
            offset_left = 0;

        
            /* 得到所需结果的命令 */
            sprintf(command + cmd_len, ") |sed -n %d,%dp",
                    start_pos, end_pos);
            /* 保护局部变量 */
            command[sizeof(command) - 1 ] = '\0';

            sprintf(debug, ": parse log %d to %d", start_pos, end_pos);
            WEB_SEND_DEBUG_ss(file_name, debug);
            sys_error_code = make_opera_log_result(ws_env, command, 
                    log_content + saved_log, (end_pos - start_pos) + 1, exporting, vrfid);
            saved_log += ((end_pos - start_pos) + 1);
        }
    }
    cmd_closeio(fp);
    if (ERROR_SUCCESS != sys_error_code)
    {
        return ws_new_soap_fault(ws_env, sys_error_code);
    }

	if(DISK_LOG_EXPORTING == exporting)
	{
	    saved_log = 0;
	}

    ret->ret.sum = total;
    ret->ret.res_USCOREcount = ret->ret.__size = saved_log;
    ret->ret.__ptrres = log_content;
    return WS_OK;
}
예제 #29
0
int
main (int argc, char **argv)
{
	int found = 0, result = STATE_UNKNOWN;
	char *buf, *sub;
	char **command_line;
	output chld_out, chld_err;
	int i;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	timeout_interval = DEFAULT_TIMEOUT;

	command_line = (char **) process_arguments (argc, argv);

	/* Set signal handling and alarm */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR)
		die (STATE_UNKNOWN, _("Cannot catch SIGALRM"));

	(void) alarm ((unsigned) timeout_interval);

	/* catch when the command is quoted */
	if(command_line[1] == NULL) {
		result = cmd_run (command_line[0], &chld_out, &chld_err, 0);
	} else {
		result = cmd_run_array (command_line, &chld_out, &chld_err, 0);
	}
	if (chld_err.lines > 0) {
		printf ("Error output from command:\n");
		for (i = 0; i < chld_err.lines; i++) {
			printf ("%s\n", chld_err.line[i]);
		}
		exit (STATE_WARNING);
	}

	/* Return UNKNOWN or worse if no output is returned */
	if (chld_out.lines == 0)
		die (max_state_alt (result, STATE_UNKNOWN), _("No data returned from command\n"));

	for (i = 0; i < chld_out.lines; i++) {
		if (subst_text && result != state[result] &&
		    result >= 0 && result <= 4) {
			/* Loop over each match found */
			while ((sub = strstr (chld_out.line[i], state_text (result)))) {
				/* Terminate the first part and skip over the string we'll substitute */
				*sub = '\0';
				sub += strlen (state_text (result));
				/* then put everything back together */
				xasprintf (&chld_out.line[i], "%s%s%s", chld_out.line[i], state_text (state[result]), sub);
			}
		}
		printf ("%s\n", chld_out.line[i]);
	}

	if (result >= 0 && result <= 4) {
		exit (state[result]);
	} else {
		exit (result);
	}
}
예제 #30
0
파일: log.c 프로젝트: jeffreywugz/keystack
void
log_rewrite(const char *filename, struct server *s) {
	
	struct client c;
	struct cmd *cm;
	int fd = open(filename, O_RDONLY), tmp_fd, ret;
	char tmp_filename[] = "/tmp/keystack-rewrite-file-XXXXXX";

	c.s = s;

	s->log = NULL;

	printf("Importing existing data..."); fflush(stdout);
	/* first, import log */
	while(1) {
		int ret;
		uint32_t sz;
		char *buffer;

		/* read size */
		ret = read(fd, &sz, sizeof(uint32_t));
		if(ret != sizeof(uint32_t)) {
			break;
		}
		sz = ntohl(sz);
		
		/* read message */
		buffer = malloc(sz);
		ret = read(fd, buffer, sz);
		if(ret != (int)sz) {
			break;
		}

		/* process message */
		cm = cmd_parse(buffer, sz);
		cmd_run(s, cm);
		cmd_free(cm);
	}
	close(fd);	
	printf("done.\nRewriting log file... "); fflush(stdout);

	/* second, write to tmp file. */
	tmp_fd = mkstemp(tmp_filename);
	if(tmp_fd == -1) {
		fprintf(stderr, "Failed to create tmp log file.\n");
		return;
	}

	dict_foreach(s->d, log_add_cb, &tmp_fd);
	printf("done (%ld keys).\nSyncing... ", dict_count(s->d)); fflush(stdout);
	fdatasync(tmp_fd);
	close(tmp_fd);

	printf("done.\nReplacing log file... "); fflush(stdout);
	ret = rename(tmp_filename, filename);
	if(ret != 0) {
		fprintf(stderr, "Failed to replace log file.\n");
		return;
	}

	/* third, replace log file with tmp file */
	printf("done.\nStarting to serve clients.\n");
}