Exemplo n.º 1
0
int main(int argc, char* argv[]) {
	int input;
	FILE* gnuplot;
	int i;
	float out_data;
	unsigned char buf[SAMPLES_PER_PLOT];
	unsigned char trig = TRIG_LEVEL;
	unsigned freq = SAMPLE_FREQ;
	
	input = open(DEVICE, O_RDONLY | O_NOCTTY);
	if (input <0) {perror(DEVICE); return -1; }
	gnuplot = popen("gnuplot", "w");
	
	tcgetattr(input,&oldtio); /* save current port settings */
	
	// bzero not defined? moving newtio outside main to zero it. 
	//bzero(&newtio, sizeof(newtio));
	newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR;
	newtio.c_oflag = 0;
	
	/* set input mode (non-canonical, no echo,...) */
	newtio.c_lflag = 0;
	
	newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
	newtio.c_cc[VMIN]     = SAMPLES_PER_PLOT;   /* blocking read until all samples received */
	
	tcflush(input, TCIFLUSH);
    tcsetattr(input,TCSANOW,&newtio);
	
	fprintf(gnuplot, "set yrange [-0.1:5.1]\n");
	while(1) {
		// Wait for trig
		do {
			if (read(input, buf, 1) != 1) return 0;
		} while (buf[0] >= trig);
		do {
			if (read(input, buf, 1) != 1) return 0;
		} while (buf[0] < trig);
		
		// Read rest of the buffer
		for (i=1; i<SAMPLES_PER_PLOT; i++) {
			if (read(input, buf+i, 1) != 1) return 0;
		}
		//read(input, buf+i, SAMPLES_PER_PLOT-1);
		
		fprintf(gnuplot, "plot '-' with lines\n");
		
		for (i=0; i<SAMPLES_PER_PLOT; i++) {
			out_data = buf[i]*5.0/256;
			fprintf(gnuplot, "%g %g\n", (float)i/freq, out_data);
		}
		fprintf(gnuplot, "e\n"); // Display output
		fflush(gnuplot);
	}
	
	tcsetattr(input,TCSANOW,&oldtio);
	close(input);
	pclose(gnuplot);
	printf("\n");
	return 0;
}
Exemplo n.º 2
0
void MainWindow::Load(const nglPath& p)
{    
  mpScrollView->Clear();
  ///////////////////////////////

  nglString cmdline;
  //cmdline.Add("/usr/bin/nm -n -U -arch i386 ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
  cmdline.Add("/usr/bin/nm -n -U ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
  printf("Launching\n%ls\n", cmdline.GetChars());
  FILE * file = popen(cmdline.GetStdString().c_str(), "r");
  nglOMemory omem;
  uint32 res = 0;
  do
  {
    char buf[1025];
    memset(buf, 0, 1025);
    uint32 res = fread(buf, 1024, 1, file);
    //printf("%s", buf);
    omem.Write(buf, 1024, 1);
  } while (!feof(file));
  pclose(file);
  
  printf("redirection done\n");
  nglIStream* pStream = new nglIMemory(omem.GetBufferData(), omem.GetBufferSize());;
  
  nglString line;
  
  uint64 lastaddr = 0;
  nglString lastsymbol;
  
  std::map<nglString, Node*> methods;
  std::map<nglString, Node*> classes;
  
  printf("read result\n");
  while (pStream->ReadLine(line))
  {
    // Read address
    int32 c = 0;
    while (line[c] && line[c] != ' ')
      c++;
    nglString a(line.Extract(0, c));
    uint64 address = a.GetCUInt(16);

    c++;
    // Read type char
    nglChar type = line[c];
    
    // Read Symbol if we are on a method / function decl
    if (type == 't')
    {
      c++;

      if (!lastsymbol.IsEmpty())
      {
        uint64 lastsize = address - lastaddr;
        
        std::map<nglString, Node*>::iterator it = methods.find(lastsymbol);
        
        bool skip = false;
        Node* pMethod = NULL;
        if (it != methods.end())
        {
          pMethod = it->second;
          pMethod->SetSize(pMethod->GetSize() + lastsize);
          //it->second += lastsize;
          skip = true;
        }
        else
        {
          //NGL_OUT(_T("new method \t %ls\n"), lastsymbol.GetChars());
          pMethod = new Node(lastsymbol);
          pMethod->SetSize(lastsize);
          methods[lastsymbol] = pMethod;
        }
        
        NGL_ASSERT(pMethod != NULL);
        
        if (!skip) // The method already exist so no need to add it to its class
        {
          int32 pos = lastsymbol.Find(':');
          if (pos > 0 && lastsymbol[pos+1] == ':')
          {
            nglString classname = lastsymbol.GetLeft(pos);
            //NGL_OUT(_T("new class %ls\n"), classname.GetChars());
            
            std::map<nglString, Node*>::iterator it = classes.find(classname);
            Node* pNode = NULL;
            if (it != classes.end())
            {
              pNode = it->second;
              pNode->SetSize(it->second->GetSize() + lastsize);
            }
            else
            {
              pNode = new Node(classname);
              pNode->SetSize(lastsize);
              classes[classname] = pNode;
            }
            
            pNode->AddChild(pMethod);
          }
        }
      }
      
      lastaddr = address;
      lastsymbol = line.GetRight(line.GetLength() - c);
    }
  }
  printf("done\n");
  
  printf("build tree\n");
  delete pStream;
  
  std::list<std::pair<nglString, Node*> > sorted;
  {
    std::map<nglString, Node*>::const_iterator it = classes.begin();
    std::map<nglString, Node*>::const_iterator end = classes.end();
    
    while (it != end)
    {
      //NGL_OUT(_T("add unsorted %ls\n"), it->first.GetChars());
      sorted.push_back(std::pair<nglString, Node*>(it->first, it->second) );
      ++it;
    }
  }
  
  sorted.sort(cmp);
  
  nuiTreeNode* pTree = new nuiTreeNode(new nuiLabel(_T("Classes")));
  
  {
    std::list<std::pair<nglString, Node*> >::const_iterator it = sorted.begin();
    std::list<std::pair<nglString, Node*> >::const_iterator end = sorted.end();
    
    while (it != end)
    {
      //NGL_OUT(_T("%lld\t\t%ls\n"), it->second->GetSize(), it->first.GetChars());
      pTree->AddChild(it->second);
      ++it;
    }
  }
  
  nuiTreeView* pTreeView = new nuiTreeView(pTree);
  mpScrollView->AddChild(pTreeView);
  printf("done\n");
}
Exemplo n.º 3
0
/*
 * var_apWholeInfo():
 *   This function is called every time the agent gets a request for
 *   a scalar variable that might be found within your mib section
 *   registered above.  It is up to you to do the right thing and
 *   return the correct value.
 *     You should also correct the value of "var_len" if necessary.
 *
 *   Please see the documentation for more information about writing
 *   module extensions, and check out the examples in the examples
 *   and mibII directories.
 */
unsigned char *
var_apWholeInfo(struct variable *vp, 
                oid     *name, 
                size_t  *length, 
                int     exact, 
                size_t  *var_len, 
                WriteMethod **write_method)
{
    /* variables we may use later */
    static long long_ret;
    static u_long ulong_ret;
    static unsigned char string[MAX_LEN];
    static unsigned char buffer[MIN_LEN];
    static oid objid[MAX_OID_LEN];
    static struct counter64 c64;

    if (header_generic(vp,name,length,exact,var_len,write_method)
                                  == MATCH_FAILED )
    return NULL;

    /* 
   * this is where we do the value assignments for the mib results.
   */
    switch(vp->magic) {
    case AP80211STATSVALUE:
  { 
	  FILE *fp;
	  if(fp=popen( "/usr/sbin/80211stats","r")){
		  memset( string, 0, MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		    }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
	   }
 }
 
    case APATHSTATSVALUE:
   { 
	  FILE *fp;
	  if(fp=popen( "/usr/sbin/athstats","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		   }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
	   }
   }     

    case APINTERFACERATE:
   { 
	  FILE *fp;
	  if(fp=popen( "cat   /tmp/interface-rate","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		     }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
	   }
   }    

	case APUSERRATE:
    { 
		  FILE *fp;
		  if(fp=popen( "cat   /tmp/user-rate","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		     }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
		  }
	}   

   case APNETETH0CONNETSTATES:
     { 
		  FILE *fp;
		  if(fp=popen( "/usr/sbin/ethtool    eth0","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		     }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
		  }
	}   
    case APNETETH1CONNETSTATES:
     { 
		  FILE *fp;
		  if(fp=popen( "/usr/sbin/ethtool    eth1","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		     }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
		  }
	}   

 
    case APGATEWAY:
     { 
		  FILE *fp;
		 if(fp=popen( "/sbin/route","r")){
		  memset( string, 0,MAX_LEN );
		  memset(buffer,0,MIN_LEN);
		  while(NULL != fgets(buffer,sizeof(buffer),fp)){
		  	strcat(string, buffer);
		     }
		  pclose(fp);
		  string[strlen(string)-1]='\0';
		  *var_len = strlen (string );
		  return (u_char*)string;
		  }
	}

  default:
      ERROR_MSG("");
    }
    return NULL;
}
Exemplo n.º 4
0
int PBSD_munge_authenticate(

  int psock,  /* I */
  int handle) /* I */

  {
  int                 rc = PBSE_NONE;

  int                 fd;
  FILE               *munge_pipe;
  char                munge_buf[MUNGE_SIZE];
  char                munge_command[MUNGE_SIZE];
  char               *ptr; /* pointer to the current place to copy data into munge_buf */
  int                 bytes_read;
  int                 total_bytes_read = 0;
  int                 local_errno = 0;
  
  /* user id and name stuff */
  struct passwd      *pwent;
  uid_t               myrealuid;
  struct batch_reply *reply;
  unsigned short      user_port = 0;
  struct sockaddr_in  sockname;
  socklen_t           socknamelen = sizeof(sockname);
  struct tcp_chan *chan = NULL;

  snprintf(munge_command,sizeof(munge_command),
    "munge -n 2>/dev/null");

  memset(munge_buf, 0, MUNGE_SIZE);
  ptr = munge_buf; 

  if ((munge_pipe = popen(munge_command,"r")) == NULL)
    {
    /* FAILURE */
    return(-1);
    }

  fd = fileno(munge_pipe);

  while ((bytes_read = read(fd, ptr, MUNGE_SIZE - total_bytes_read)) > 0)
    {
    total_bytes_read += bytes_read;
    ptr += bytes_read;
    }

  pclose(munge_pipe);

  if (bytes_read == -1)
    {
    /* read failed */
    local_errno = errno;
    log_err(local_errno, __func__, (char *)"error reading pipe in PBSD_munge_authenticate");
    return -1;
    }
  
  /* if we got no bytes back then Munge may not be installed etc. */
  if (total_bytes_read == 0)
    {
    return(PBSE_MUNGE_NOT_FOUND);
    }

  /* We got the certificate. Now make the PBS_BATCH_AltAuthenUser request */
  myrealuid = getuid();  
  pwent = getpwuid(myrealuid);
  
  rc = getsockname(psock, (struct sockaddr *)&sockname, &socknamelen);
  
  if (rc == -1)
    {
    fprintf(stderr, "getsockname failed: %d\n", errno);
    return rc;
    }
  
  user_port = ntohs(sockname.sin_port);
  
  if ((chan = DIS_tcp_setup(psock)) == NULL)
    {
    rc = PBSE_MEM_MALLOC;
    }
  else if ((rc = encode_DIS_ReqHdr(chan,PBS_BATCH_AltAuthenUser,pwent->pw_name)) ||
           (rc = diswui(chan, user_port)) ||
           (rc = diswst(chan, munge_buf)) ||
           (rc = encode_DIS_ReqExtend(chan, NULL)) ||
           (rc = DIS_tcp_wflush(chan)))
    {
    /* ERROR */
    }
  else
    {
    /* read the reply */
    if ((reply = PBSD_rdrpy(&local_errno, handle)) != NULL)
      free(reply);

    rc = PBSE_NONE;
    }
  if (chan != NULL)
    DIS_tcp_cleanup(chan);
  return rc;
  } /* END PBSD_munge_authenticate() */
Exemplo n.º 5
0
int Main(int argc, char const * const argv[], char const * const envp[]) {
    _aprcall(apr_initialize());

    apr_pool_t *pool;
    apr_pool_create(&pool, NULL);

    bool tty(isatty(STDIN_FILENO));
    bool compile(false);
    CYOptions options;

    append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));

#ifdef CY_ATTACH
    pid_t pid(_not(pid_t));
#endif

    const char *host(NULL);
    const char *port(NULL);

    apr_getopt_t *state;
    _aprcall(apr_getopt_init(&state, pool, argc, argv));

    for (;;) {
        char opt;
        const char *arg;

        apr_status_t status(apr_getopt(state,
            "cg:n:"
#ifdef CY_ATTACH
            "p:"
#endif
            "r:"
            "s"
        , &opt, &arg));

        switch (status) {
            case APR_EOF:
                goto getopt;
            case APR_BADCH:
            case APR_BADARG:
                fprintf(stderr,
                    "usage: cycript [-c]"
#ifdef CY_ATTACH
                    " [-p <pid|name>]"
#endif
                    " [-r <host:port>]"
                    " [<script> [<arg>...]]\n"
                );
                return 1;
            default:
                _aprcall(status);
        }

        switch (opt) {
            case 'c':
                compile = true;
            break;

            case 'g':
                if (false);
                else if (strcmp(arg, "rename") == 0)
                    options.verbose_ = true;
#if YYDEBUG
                else if (strcmp(arg, "bison") == 0)
                    bison_ = true;
#endif
                else {
                    fprintf(stderr, "invalid name for -g\n");
                    return 1;
                }
            break;

            case 'n':
                if (false);
                else if (strcmp(arg, "minify") == 0)
                    pretty_ = true;
                else {
                    fprintf(stderr, "invalid name for -n\n");
                    return 1;
                }
            break;

#ifdef CY_ATTACH
            case 'p': {
                size_t size(strlen(arg));
                char *end;

                pid = strtoul(arg, &end, 0);
                if (arg + size != end) {
                    // XXX: arg needs to be escaped in some horrendous way of doom
                    const char *command(apr_pstrcat(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^", arg, " /{s/^[^ ]* //;q;};};d'", NULL));

                    if (FILE *pids = popen(command, "r")) {
                        char value[32];
                        size = 0;

                        for (;;) {
                            size_t read(fread(value + size, 1, sizeof(value) - size, pids));
                            if (read == 0)
                                break;
                            else {
                                size += read;
                                if (size == sizeof(value)) {
                                    pid = _not(pid_t);
                                    goto fail;
                                }
                            }
                        }

                      size:
                        if (size == 0)
                            goto fail;
                        if (value[size - 1] == '\n') {
                            --size;
                            goto size;
                        }

                        value[size] = '\0';
                        size = strlen(value);
                        pid = strtoul(value, &end, 0);
                        if (value + size != end) fail:
                            pid = _not(pid_t);
                        _syscall(pclose(pids));
                    }

                    if (pid == _not(pid_t)) {
                        fprintf(stderr, "invalid pid for -p\n");
                        return 1;
                    }
                }
            } break;
#endif

            case 'r': {
                //size_t size(strlen(arg));

                char *colon(strrchr(arg, ':'));
                if (colon == NULL) {
                    fprintf(stderr, "missing colon in hostspec\n");
                    return 1;
                }

                /*char *end;
                port = strtoul(colon + 1, &end, 10);
                if (end != arg + size) {
                    fprintf(stderr, "invalid port in hostspec\n");
                    return 1;
                }*/

                host = arg;
                *colon = '\0';
                port = colon + 1;
            } break;

            case 's':
                strict_ = true;
            break;
        }
    } getopt:;

    const char *script;
    int ind(state->ind);

#ifdef CY_ATTACH
    if (pid != _not(pid_t) && ind < argc - 1) {
        fprintf(stderr, "-p cannot set argv\n");
        return 1;
    }

    if (pid != _not(pid_t) && compile) {
        fprintf(stderr, "-p conflicts with -c\n");
        return 1;
    }
#endif

    if (ind == argc)
        script = NULL;
    else {
#ifdef CY_EXECUTE
        // XXX: const_cast?! wtf gcc :(
        CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
#endif
        script = argv[ind];
        if (strcmp(script, "-") == 0)
            script = NULL;
    }

#ifdef CY_ATTACH
    if (pid != _not(pid_t) && script == NULL && !tty) {
        fprintf(stderr, "non-terminal attaching to remote console\n");
        return 1;
    }
#endif

#ifdef CY_ATTACH
    if (pid == _not(pid_t))
        client_ = -1;
    else {
        int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
            struct sockaddr_un address;
            memset(&address, 0, sizeof(address));
            address.sun_family = AF_UNIX;

            sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());

            _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
            _syscall(chmod(address.sun_path, 0777));

            try {
                _syscall(listen(server, 1));
                InjectLibrary(pid);
                client_ = _syscall(accept(server, NULL, NULL));
            } catch (...) {
                // XXX: exception?
                unlink(address.sun_path);
                throw;
            }
        } catch (...) {
            _syscall(close(server));
            throw;
        }
    }
#else
    client_ = -1;
#endif

    if (client_ == -1 && host != NULL && port != NULL) {
        struct addrinfo hints;
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = 0;
        hints.ai_flags = 0;

        struct addrinfo *infos;
        _syscall(getaddrinfo(host, port, &hints, &infos));

        _assert(infos != NULL); try {
            for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
                int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
                    _syscall(connect(client, info->ai_addr, info->ai_addrlen));
                    client_ = client;
                    break;
                } catch (...) {
                    _syscall(close(client));
                    throw;
                }
            }
        } catch (...) {
            freeaddrinfo(infos);
            throw;
        }
    }

    if (script == NULL && tty)
        Console(options);
    else {
        CYLocalPool pool;

        char *start, *end;
        std::istream *indirect;

        if (script == NULL) {
            start = NULL;
            end = NULL;
            indirect = &std::cin;
        } else {
            size_t size;
            start = reinterpret_cast<char *>(Map(script, &size));
            end = start + size;

            if (size >= 2 && start[0] == '#' && start[1] == '!') {
                start += 2;

                if (void *line = memchr(start, '\n', end - start))
                    start = reinterpret_cast<char *>(line);
                else
                    start = end;
            }

            indirect = NULL;
        }

        CYStream direct(start, end);
        std::istream &stream(indirect == NULL ? direct : *indirect);
        CYDriver driver(stream, script ?: "<stdin>");

        cy::parser parser(driver);
        Setup(driver, parser);

        if (parser.parse() != 0 || !driver.errors_.empty()) {
            for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
                std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
        } else if (driver.program_ != NULL)
            if (client_ != -1) {
                // XXX: this code means that you can't pipe to another process
                std::string code(start, end-start);
                Run(client_, false, code, &std::cout);
            } else {
                std::ostringstream str;
                CYOutput out(str, options);
                Setup(out, driver, options);
                out << *driver.program_;
                std::string code(str.str());
                if (compile)
                    std::cout << code;
                else
                    Run(client_, false, code, &std::cout);
            }
    }

    apr_pool_destroy(pool);

    return 0;
}
Exemplo n.º 6
0
 static FILE *procFile( char *cmdLine, unsigned cmdSize, char const *fileName )
 {
    snprintf( cmdLine, cmdSize, "cat %s", fileName );
    return popen( cmdLine, "r" );
 }
Exemplo n.º 7
0
/**
 * Default implementation to get the default gateway by parsing the
 * output of the "netstat -rn" command.
 *
 * @param addrp		where gateway address is to be written
 *
 * @return 0 on success, -1 on failure with errno set.
 */
static G_GNUC_COLD int
parse_netstat(host_addr_t *addrp)
#ifdef HAS_POPEN
{
	FILE *f = NULL;
	char tmp[80];
	guint32 gate = 0;

	/*
	 * This implementation should be a safe default on UNIX platforms, but
	 * it is inefficient and as such can only constitute a fallback.
	 */

	if (-1 != access("/bin/netstat", X_OK)) {
		f = popen("/bin/netstat -rn", "r");
	} else if (-1 != access("/usr/bin/netstat", X_OK)) {
		f = popen("/usr/bin/netstat -rn", "r");
	}

	if (NULL == f) {
		errno = ENOENT;		/* netstat not found */
		return -1;
	}

	/*
	 * Typical netstat -rn output:
	 *
	 * Destination        Gateway            Flags .....
	 * 0.0.0.0            192.168.0.200      UG
	 * default            192.168.0.200      UG
	 *
	 * Some systems like linux display "0.0.0.0", but traditional UNIX
	 * output is "default" for the default route.
	 */

	while (fgets(tmp, sizeof tmp, f)) {
		char *p;
		guint32 ip;

		p = is_strprefix(tmp, "default");
		if (NULL == p)
			p = is_strprefix(tmp, "0.0.0.0");

		if (NULL == p || !is_ascii_space(*p))
			continue;

		ip = string_to_ip(p);
		if (ip != 0) {
			gate = ip;
			break;
		}
	}

	pclose(f);

	if (0 == gate) {
		errno = ENETUNREACH;
		return -1;
	}

	*addrp = host_addr_get_ipv4(gate);
	return 0;
}
Exemplo n.º 8
0
/**
 * save_environment: save configuration data and arguments.
 */
static void
save_environment(int argc, char *const *argv)
{
	char command[MAXFILLEN];
	STRBUF *sb = strbuf_open(0);
	STRBUF *save_c = strbuf_open(0);
	STRBUF *save_a = strbuf_open(0);
	int i;
	const char *p;
	FILE *ip;

	/*
	 * save config values.
	 */
	snprintf(command, sizeof(command), PQUOTE "%s --config" PQUOTE, quote_shell(gtags_path));
	if ((ip = popen(command, "r")) == NULL)
		die("cannot execute '%s'.", command);
	while (strbuf_fgets(sb, ip, STRBUF_NOCRLF) != NULL) {
		for (p = strbuf_value(sb); *p; p++) {
			if (*p == '\'') {
				strbuf_putc(save_c, '\'');
				strbuf_putc(save_c, '"');
				strbuf_putc(save_c, '\'');
				strbuf_putc(save_c, '"');
				strbuf_putc(save_c, '\'');
			} else
				strbuf_putc(save_c, *p);
		}
	}
	if (pclose(ip) != 0)
		die("terminated abnormally '%s' (errno = %d).", command, errno);
	strbuf_close(sb);
	save_config = strbuf_value(save_c);
	/* doesn't close string buffer for save config. */
	/* strbuf_close(save_c); */

	/*
	 * save arguments.
	 */
	{
		char *opt_gtagsconf = "--gtagsconf";

		for (i = 1; i < argc; i++) {
			char *blank;

			/*
			 * skip --gtagsconf because it is already read
			 * as config value.
			 */
			if ((p = locatestring(argv[i], opt_gtagsconf, MATCH_AT_FIRST))) {
				if (*p == '\0')
					i++;
				continue;
			}
			blank = locatestring(argv[i], " ", MATCH_FIRST);
			strbuf_putc(save_a, ' ');
			if (blank)
				strbuf_putc(save_a, '\'');
			strbuf_puts(save_a, argv[i]);
			if (blank)
				strbuf_putc(save_a, '\'');
		}
	}
	save_argv = strbuf_value(save_a);
	/* doesn't close string buffer for save arguments. */
	/* strbuf_close(save_a); */
}
Exemplo n.º 9
0
Arquivo: file.c Projeto: mirage335/pcb
/* ---------------------------------------------------------------------------
 * writes to pipe using the command defined by Settings.SaveCommand
 * %f are replaced by the passed filename
 */
static int
WritePipe (char *Filename, bool thePcb)
{
  FILE *fp;
  int result;
  char *p;
  static DynamicStringType command;
  int used_popen = 0;

  if (EMPTY_STRING_P (Settings.SaveCommand))
    {
      fp = fopen (Filename, "w");
      if (fp == 0)
	{
	  Message ("Unable to write to file %s\n", Filename);
	  return STATUS_ERROR;
	}
    }
  else
    {
      used_popen = 1;
      /* setup commandline */
      DSClearString (&command);
      for (p = Settings.SaveCommand; *p; p++)
	{
	  /* copy character if not special or add string to command */
	  if (!(*p == '%' && *(p + 1) == 'f'))
	    DSAddCharacter (&command, *p);
	  else
	    {
	      DSAddString (&command, Filename);

	      /* skip the character */
	      p++;
	    }
	}
      DSAddCharacter (&command, '\0');
      printf ("write to pipe \"%s\"\n", command.Data);
      if ((fp = popen (command.Data, "w")) == NULL)
	{
	  PopenErrorMessage (command.Data);
	  return (STATUS_ERROR);
	}
    }
  if (thePcb)
    {
      if (PCB->is_footprint)
	{
	  WriteElementData (fp, PCB->Data);
	  result = 0;
	}
      else
	result = WritePCB (fp);
    }
  else
    result = WriteBuffer (fp);

  if (used_popen)
    return (pclose (fp) ? STATUS_ERROR : result);
  return (fclose (fp) ? STATUS_ERROR : result);
}
Exemplo n.º 10
0
bool address_to_line(void* call_addr, char* buffer, size_t size_of_buffer)
{
   if(!call_addr) return false;
   char buff[1024];
   ssize_t len; 
   if(!get_self_path(buff,sizeof(buff),len)) return false;
   const char addr2line_cmd[] = "addr2line -e";
   const char postfix_cmd[] = "";
   
   // convert address to char array
   char addr[32];
   sprintf(addr,"%p",call_addr);
   size_t addr_len = strlen(addr);
   addr[addr_len] = '\0';
   
   // allocate memory for command
   char* cmd = (char*)(malloc)(sizeof(addr2line_cmd) // command length + NULL termination
                               + len // main path
                               + sizeof(postfix_cmd) // postfix length + extra space
                               + addr_len); // address length 
   
   // make command
   strcpy(cmd,addr2line_cmd);
   strcat(cmd+sizeof(addr2line_cmd)-1,buff);
   sprintf(cmd+strlen(cmd)," %s",addr);
   strcat(cmd,postfix_cmd);
   
   size_t cmd_len = strlen(cmd);
   cmd[cmd_len]='\0';
   
   // run command
   FILE* fp = popen(cmd,"r");
   if(fp)
   {
      //char buffer[1024];
      if(fgets(buffer, size_of_buffer, fp)!=NULL)
      {
         if(buffer[0] == '?')
         {
            size_t buffer_len = strlen(buffer);
            buffer[buffer_len-1] = '\0';
            pclose(fp);
            free(cmd);
            return false;
         }
      }
      else
      {
         size_t buffer_len = strlen(buffer);
         buffer[buffer_len-1] = '\0';
         pclose(fp);
         free(cmd);
         return false;
      }
   }
   
   size_t buffer_len = strlen(buffer);
   buffer[buffer_len-1] = '\0';

   pclose(fp);
   free(cmd);
   return true;
}
Exemplo n.º 11
0
Arquivo: file.c Projeto: mirage335/pcb
int
ReadNetlist (char *filename)
{
  static char *command = NULL;
  char inputline[MAX_NETLIST_LINE_LENGTH + 1];
  char temp[MAX_NETLIST_LINE_LENGTH + 1];
  FILE *fp;
  LibraryMenuType *menu = NULL;
  LibraryEntryType *entry;
  int i, j, lines, kind;
  bool continued;
  bool used_popen = false;
  int retval = 0;

  if (!filename)
    return 1;			/* nothing to do */

  Message (_("Importing PCB netlist %s\n"), filename);

  if (EMPTY_STRING_P (Settings.RatCommand))
    {
      fp = fopen (filename, "r");
      if (!fp)
	{
	  Message("Cannot open %s for reading", filename);
	  return 1;
	}
    }
  else
    {
      used_popen = true;
      free (command);
      command = EvaluateFilename (Settings.RatCommand,
				  Settings.RatPath, filename, NULL);

      /* open pipe to stdout of command */
      if (*command == '\0' || (fp = popen (command, "r")) == NULL)
	{
	  PopenErrorMessage (command);
	  return 1;
	}
    }
  lines = 0;
  /* kind = 0  is net name
   * kind = 1  is route style name
   * kind = 2  is connection
   */
  kind = 0;
  while (fgets (inputline, MAX_NETLIST_LINE_LENGTH, fp))
    {
      size_t len = strlen (inputline);
      /* check for maximum length line */
      if (len)
	{
	  if (inputline[--len] != '\n')
	    Message (_("Line length (%i) exceeded in netlist file.\n"
		       "additional characters will be ignored.\n"),
		     MAX_NETLIST_LINE_LENGTH);
	  else
	    inputline[len] = '\0';
	}
      continued = (inputline[len - 1] == '\\') ? true : false;
      if (continued)
	inputline[len - 1] = '\0';
      lines++;
      i = 0;
      while (inputline[i] != '\0')
	{
	  j = 0;
	  /* skip leading blanks */
	  while (inputline[i] != '\0' && BLANK (inputline[i]))
	    i++;
	  if (kind == 0)
	    {
	      /* add two spaces for included/unincluded */
	      temp[j++] = ' ';
	      temp[j++] = ' ';
	    }
	  while (!BLANK (inputline[i]))
	    temp[j++] = inputline[i++];
	  temp[j] = '\0';
	  while (inputline[i] != '\0' && BLANK (inputline[i]))
	    i++;
	  if (kind == 0)
	    {
	      menu = GetLibraryMenuMemory (&PCB->NetlistLib);
	      menu->Name = strdup (temp);
	      menu->flag = 1;
	      kind++;
	    }
	  else
	    {
	      if (kind == 1 && strchr (temp, '-') == NULL)
		{
		  kind++;
		  menu->Style = strdup (temp);
		}
	      else
		{
		  entry = GetLibraryEntryMemory (menu);
		  entry->ListEntry = strdup (temp);
		}
	    }
	}
      if (!continued)
	kind = 0;
    }
  if (!lines)
    {
      Message (_("Empty netlist file!\n"));
      retval = 1;
    }
  if (used_popen)
    pclose (fp);
  else
    fclose (fp);
  sort_netlist ();
  return retval;
}
Exemplo n.º 12
0
Arquivo: file.c Projeto: mirage335/pcb
/* ---------------------------------------------------------------------------
 * Read contents of the library description file (for M4)
 * and then read in M4 libs.  Then call a fcn to read the newlib
 * footprints.
 */
int
ReadLibraryContents (void)
{
  static char *command = NULL;
  char inputline[MAX_LIBRARY_LINE_LENGTH + 1];
  FILE *resultFP = NULL;
  LibraryMenuType *menu = NULL;
  LibraryEntryType *entry;

  /* If we don't have a command to execute to find the library contents,
   * skip this. This is used by default on Windows builds (set in main.c),
   * as we can't normally run shell scripts or expect to have m4 present.
   */
  if (Settings.LibraryContentsCommand != NULL &&
      Settings.LibraryContentsCommand[0] != '\0')
    {
      /*  First load the M4 stuff.  The variable Settings.LibraryPath
       *  points to it.
       */
      free (command);
      command = EvaluateFilename (Settings.LibraryContentsCommand,
				  Settings.LibraryPath, Settings.LibraryFilename,
				  NULL);

#ifdef DEBUG
      printf("In ReadLibraryContents, about to execute command %s\n", command);
#endif

      /* This uses a pipe to execute a shell script which provides the names of
       * all M4 libs and footprints.  The results are placed in resultFP.
       */
      if (command && *command && (resultFP = popen (command, "r")) == NULL)
	{
	  PopenErrorMessage (command);
	}

      /* the M4 library contents are separated by colons;
       * template : package : name : description
       */
      while (resultFP != NULL && fgets (inputline, MAX_LIBRARY_LINE_LENGTH, resultFP))
	{
	  size_t len = strlen (inputline);

	  /* check for maximum linelength */
	  if (len)
	    {
	      len--;
	      if (inputline[len] != '\n')
		Message
		  ("linelength (%i) exceeded; following characters will be ignored\n",
		   MAX_LIBRARY_LINE_LENGTH);
	      else
		inputline[len] = '\0';
	    }

	  /* if the line defines a menu */
	  if (!strncmp (inputline, "TYPE=", 5))
	    {
	      menu = GetLibraryMenuMemory (&Library);
	      menu->Name = strdup (UNKNOWN (&inputline[5]));
	      menu->directory = strdup (Settings.LibraryFilename);
	    }
	  else
	    {
	      /* allocate a new menu entry if not already done */
	      if (!menu)
		{
		  menu = GetLibraryMenuMemory (&Library);
		  menu->Name = strdup (UNKNOWN ((char *) NULL));
		  menu->directory = strdup (Settings.LibraryFilename);
		}
	      entry = GetLibraryEntryMemory (menu);
	      entry->AllocatedMemory = strdup (inputline);

	      /* now break the line into pieces separated by colons */
	      if ((entry->Template = strtok (entry->AllocatedMemory, ":")) !=
		  NULL)
		if ((entry->Package = strtok (NULL, ":")) != NULL)
		  if ((entry->Value = strtok (NULL, ":")) != NULL)
		    entry->Description = strtok (NULL, ":");

	      /* create the list entry */
	      len = strlen (EMPTY (entry->Value)) +
		strlen (EMPTY (entry->Description)) + 4;
	      entry->ListEntry = (char *)calloc (len, sizeof (char));
	      sprintf (entry->ListEntry,
		       "%s, %s", EMPTY (entry->Value),
		       EMPTY (entry->Description));
	    }
	}
      if (resultFP != NULL)
	pclose (resultFP);
    }

  /* Now after reading in the M4 libs, call a function to
   * read the newlib footprint libraries.  Then sort the whole
   * library.
   */
  if (ParseLibraryTree () > 0 || resultFP != NULL)
    {
      sort_library (&Library);
      return 0;
    }
  
  return (1);
}
Exemplo n.º 13
0
/*
 * PQprint()
 *
 * Format results of a query for printing.
 *
 * PQprintOpt is a typedef (structure) that contains
 * various flags and options. consult libpq-fe.h for
 * details
 *
 * This function should probably be removed sometime since psql
 * doesn't use it anymore. It is unclear to what extent this is used
 * by external clients, however.
 */
void
PQprint(FILE *fout, const PGresult *res, const PQprintOpt *po)
{
	int			nFields;

	nFields = PQnfields(res);

	if (nFields > 0)
	{							/* only print rows with at least 1 field.  */
		int			i,
					j;
		int			nTups;
		int		   *fieldMax = NULL;	/* in case we don't use them */
		unsigned char *fieldNotNum = NULL;
		char	   *border = NULL;
		char	  **fields = NULL;
		const char **fieldNames;
		int			fieldMaxLen = 0;
		int			numFieldName;
		int			fs_len = strlen(po->fieldSep);
		int			total_line_length = 0;
		int			usePipe = 0;
		char	   *pagerenv;

#if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
		sigset_t	osigset;
		bool		sigpipe_masked = false;
		bool		sigpipe_pending;
#endif
#if !defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
		pqsigfunc	oldsigpipehandler = NULL;
#endif

#ifdef TIOCGWINSZ
		struct winsize screen_size;
#else
		struct winsize
		{
			int			ws_row;
			int			ws_col;
		}			screen_size;
#endif

		nTups = PQntuples(res);
		if (!(fieldNames = (const char **) calloc(nFields, sizeof(char *))))
		{
			fprintf(stderr, libpq_gettext("out of memory\n"));
			abort();
		}
		if (!(fieldNotNum = (unsigned char *) calloc(nFields, 1)))
		{
			fprintf(stderr, libpq_gettext("out of memory\n"));
			abort();
		}
		if (!(fieldMax = (int *) calloc(nFields, sizeof(int))))
		{
			fprintf(stderr, libpq_gettext("out of memory\n"));
			abort();
		}
		for (numFieldName = 0;
			 po->fieldName && po->fieldName[numFieldName];
			 numFieldName++)
			;
		for (j = 0; j < nFields; j++)
		{
			int			len;
			const char *s = (j < numFieldName && po->fieldName[j][0]) ?
			po->fieldName[j] : PQfname(res, j);

			fieldNames[j] = s;
			len = s ? strlen(s) : 0;
			fieldMax[j] = len;
			len += fs_len;
			if (len > fieldMaxLen)
				fieldMaxLen = len;
			total_line_length += len;
		}

		total_line_length += nFields * strlen(po->fieldSep) + 1;

		if (fout == NULL)
			fout = stdout;
		if (po->pager && fout == stdout && isatty(fileno(stdin)) &&
			isatty(fileno(stdout)))
		{
			/*
			 * If we think there'll be more than one screen of output, try to
			 * pipe to the pager program.
			 */
#ifdef TIOCGWINSZ
			if (ioctl(fileno(stdout), TIOCGWINSZ, &screen_size) == -1 ||
				screen_size.ws_col == 0 ||
				screen_size.ws_row == 0)
			{
				screen_size.ws_row = 24;
				screen_size.ws_col = 80;
			}
#else
			screen_size.ws_row = 24;
			screen_size.ws_col = 80;
#endif
			pagerenv = getenv("PAGER");
			if (pagerenv != NULL &&
				pagerenv[0] != '\0' &&
				!po->html3 &&
				((po->expanded &&
				  nTups * (nFields + 1) >= screen_size.ws_row) ||
				 (!po->expanded &&
				  nTups * (total_line_length / screen_size.ws_col + 1) *
				  (1 + (po->standard != 0)) >= screen_size.ws_row -
				  (po->header != 0) *
				  (total_line_length / screen_size.ws_col + 1) * 2
				  - (po->header != 0) * 2		/* row count and newline */
				  )))
			{
				fout = popen(pagerenv, "w");
				if (fout)
				{
					usePipe = 1;
#ifndef WIN32
#ifdef ENABLE_THREAD_SAFETY
					if (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0)
						sigpipe_masked = true;
#else
					oldsigpipehandler = pqsignal(SIGPIPE, SIG_IGN);
#endif   /* ENABLE_THREAD_SAFETY */
#endif   /* WIN32 */
				}
				else
					fout = stdout;
			}
		}

		if (!po->expanded && (po->align || po->html3))
		{
			if (!(fields = (char **) calloc(nFields * (nTups + 1), sizeof(char *))))
			{
				fprintf(stderr, libpq_gettext("out of memory\n"));
				abort();
			}
		}
		else if (po->header && !po->html3)
		{
			if (po->expanded)
			{
				if (po->align)
					fprintf(fout, libpq_gettext("%-*s%s Value\n"),
							fieldMaxLen - fs_len, libpq_gettext("Field"), po->fieldSep);
				else
					fprintf(fout, libpq_gettext("%s%sValue\n"), libpq_gettext("Field"), po->fieldSep);
			}
			else
			{
				int			len = 0;

				for (j = 0; j < nFields; j++)
				{
					const char *s = fieldNames[j];

					fputs(s, fout);
					len += strlen(s) + fs_len;
					if ((j + 1) < nFields)
						fputs(po->fieldSep, fout);
				}
				fputc('\n', fout);
				for (len -= fs_len; len--; fputc('-', fout));
				fputc('\n', fout);
			}
		}
		if (po->expanded && po->html3)
		{
			if (po->caption)
				fprintf(fout, "<center><h2>%s</h2></center>\n", po->caption);
			else
				fprintf(fout,
						"<center><h2>"
						"Query retrieved %d rows * %d fields"
						"</h2></center>\n",
						nTups, nFields);
		}
		for (i = 0; i < nTups; i++)
		{
			if (po->expanded)
			{
				if (po->html3)
					fprintf(fout,
							"<table %s><caption align=\"top\">%d</caption>\n",
							po->tableOpt ? po->tableOpt : "", i);
				else
					fprintf(fout, libpq_gettext("-- RECORD %d --\n"), i);
			}
			for (j = 0; j < nFields; j++)
				do_field(po, res, i, j, fs_len, fields, nFields,
						 fieldNames, fieldNotNum,
						 fieldMax, fieldMaxLen, fout);
			if (po->html3 && po->expanded)
				fputs("</table>\n", fout);
		}
		if (!po->expanded && (po->align || po->html3))
		{
			if (po->html3)
			{
				if (po->header)
				{
					if (po->caption)
						fprintf(fout,
						   "<table %s><caption align=\"top\">%s</caption>\n",
								po->tableOpt ? po->tableOpt : "",
								po->caption);
					else
						fprintf(fout,
								"<table %s><caption align=\"top\">"
								"Retrieved %d rows * %d fields"
								"</caption>\n",
						   po->tableOpt ? po->tableOpt : "", nTups, nFields);
				}
				else
					fprintf(fout, "<table %s>", po->tableOpt ? po->tableOpt : "");
			}
			if (po->header)
				border = do_header(fout, po, nFields, fieldMax, fieldNames,
								   fieldNotNum, fs_len, res);
			for (i = 0; i < nTups; i++)
				output_row(fout, po, nFields, fields,
						   fieldNotNum, fieldMax, border, i);
			free(fields);
			if (border)
				free(border);
		}
		if (po->header && !po->html3)
			fprintf(fout, "(%d row%s)\n\n", PQntuples(res),
					(PQntuples(res) == 1) ? "" : "s");
		free(fieldMax);
		free(fieldNotNum);
		free((void *) fieldNames);
		if (usePipe)
		{
#ifdef WIN32
			_pclose(fout);
#else
			pclose(fout);

#ifdef ENABLE_THREAD_SAFETY
			/* we can't easily verify if EPIPE occurred, so say it did */
			if (sigpipe_masked)
				pq_reset_sigpipe(&osigset, sigpipe_pending, true);
#else
			pqsignal(SIGPIPE, oldsigpipehandler);
#endif   /* ENABLE_THREAD_SAFETY */
#endif   /* WIN32 */
		}
		if (po->html3 && !po->expanded)
			fputs("</table>\n", fout);
	}
}
Exemplo n.º 14
0
void alarms_history::on_pushButtonSave_clicked()
{
    /* Check USB key */
    if (USBCheck())
    {
        if (USBmount() == false)
        {
            LOG_PRINT(error_e, "Cannot mount the usb key\n");
            QMessageBox::critical(this,tr("USB error"), tr("Cannot mount the usb key"));
            return;
        }
        
        char srcfilename [MAX_LINE] = "";
        char dstfilename [MAX_LINE] = "";
        
        /* compose the source file name ans the destination file name */
        sprintf(srcfilename, "%s/%s", ALARMS_DIR, logFileList.at(_current).toAscii().data());
        sprintf(dstfilename, "%s/%s_%s",
                usb_mnt_point,
                QDateTime::currentDateTime().toString("yy_MM_dd_hh_mm_ss").toAscii().data(),
                logFileList.at(_current).toAscii().data());
        
        /* prepare the alarm filtered file */
        
        /* open the source alarm file */
        FILE * fp = fopen(srcfilename, "r");
        if (fp == NULL)
        {
            LOG_PRINT(error_e, "Cannot open '%s'\n", srcfilename);
            QMessageBox::critical(this,tr("USB error"), tr("Cannot open the alarm file '%1'").arg(srcfilename));
            return;
        }
        /* open the dest alarm file */
        FILE * fpout = fopen(dstfilename, "w");
        if (fpout == NULL)
        {
            LOG_PRINT(error_e, "Cannot open '%s'\n", dstfilename);
            QMessageBox::critical(this,tr("USB error"), tr("Cannot write the alarm file '%1'").arg(srcfilename));
            return;
        }
        
        char line[LINE_SIZE];
        char * p;
        /* read from source and filter the level an the type of alarm and dump the dest alarm file */
        while (fgets(line, LINE_SIZE, fp) != NULL)
        {
            /* type;level;tag;event;YYYY/MM/DD,HH:mm:ss;description */
            /* type */
            p = strtok(line, ";");
            if (p == NULL)
            {
                LOG_PRINT(info_e, "Skip empty line'%s'\n", line);
                continue;
            }
            /* skip the alarms */
            if (atoi(p) == ALARM && _alarm == false)
            {
                LOG_PRINT(info_e, "Skip alarm '%s'\n", line);
                continue;
            }
            /* skip the events */
            if (atoi(p) == EVENT && _event == false)
            {
                LOG_PRINT(info_e, "Skip event '%s'\n", line);
                continue;
            }
            /* level */
            p = strtok(NULL, ";");
            if (p == NULL)
            {
                LOG_PRINT(error_e, "Malformed log file [%s]\n", line);
                return;
            }
            /* skip the level */
            if (atoi(p) < _level)
            {
                LOG_PRINT(info_e, "Skip level '%d %d'\n", atoi(p), _level);
                continue;
            }
            fprintf(fpout, "%s", line);
        }
        fclose(fp);
        fclose(fpout);
        
        /* create the signature file */
        
        /* Open the command for reading. */
        sprintf(line, "%s %s", APP_SIGN, dstfilename);
        fp = popen(line, "r");
        if (fp == NULL) {
            LOG_PRINT(error_e,"Failed to run command '%s'\n", line );
            return;
        }
        
        char sign[LINE_SIZE];
        
        /* Read the output a line at a time - output it. */
        if (fscanf(fp, "%s", sign) > 0) {
            LOG_PRINT(info_e,"SIGN: '%s'\n", sign);
        }
        
        /* close */
        pclose(fp);
        
        if (sign[0] == '\0')
        {
            LOG_PRINT(error_e,"Failed read sign\n");
            QFile::remove(dstfilename);
            QMessageBox::critical(this,tr("USB error"), tr("Cannot create the signature '%1'").arg(line));
            USBumount();
            return;
        }
        
        sprintf(line, "%s.sign", dstfilename);
        fpout = fopen(line, "w");
        if (fpout == NULL)
        {
            LOG_PRINT(error_e, "Cannot open '%s'\n", line);
            QFile::remove(dstfilename);
            QMessageBox::critical(this,tr("USB error"), tr("Cannot create the signature '%1'").arg(line));
            USBumount();
            return;
        }
        fprintf(fpout, "%s\n", sign);
        fclose(fpout);
        
        /* zip the file, the sign file and delete them */
        if (zipAndSave(QStringList() << QString("%1.sign").arg(dstfilename) << QString(dstfilename), QString("%1.zip").arg(dstfilename)) == false)
        {
            QMessageBox::critical(this,tr("USB error"), tr("Cannot save the sip file '%1.zip'").arg(dstfilename));
            USBumount();
            return;
        }
        
        QFile::remove(dstfilename);
        QFile::remove(QString("%1.sign").arg(dstfilename));
        
        /* unmount USB key */
        USBumount();
        LOG_PRINT(info_e, "DOWNLOADED\n");
        QMessageBox::information(this,tr("USB info"), tr("File '%1' saved.").arg(dstfilename));
    }
}
Exemplo n.º 15
0
int main(int argc,char* argv[])
{
	XtAppContext app;
	int               sig_Number;
	int               sig_Signal[] =
	{
		SIGHUP,
		SIGINT,
		SIGQUIT,
		SIGILL,
		SIGTRAP,
#if defined(SIGIOT)
		SIGIOT,
#endif
		SIGABRT,
#if defined(SIGEMT)
		SIGEMT,
#endif
		SIGFPE,
		SIGBUS,
		SIGSEGV,
#if defined(SIGSYS)
		SIGSYS,
#endif
		SIGTERM,
#if defined(SIGXCPU)
		SIGXCPU,
#endif
#if defined(SIGXFSZ)
		SIGXFSZ,
#endif
#if defined(SIGDANGER)
		SIGDANGER,
#endif
		-1
	};
	Widget            app_App;
	Display*          dpy;
	Window            win_Root;
	XWindowAttributes attr_Win;
	XGCValues         gc_ValFore;
	XGCValues         gc_ValBack;
	GC                gc_GcFore;
	GC                gc_GcBack;
	XFontStruct*      font_Font;
	char*             font_List[] =
	{
		"-*-character-*-r-*-*-*-600-*-*-p-*-*-*",
		"-*-helvetica-*-r-*-*-*-600-*-*-p-*-*-*",
		"-*-lucida-*-r-*-*-*-600-*-*-p-*-*-*",
		"-*-*-*-r-*-sans-*-600-*-*-p-*-*-*",
		"-*-*-*-r-*-*-*-600-*-*-m-*-*-*",
		"-*-helvetica-*-r-*-*-*-240-*-*-p-*-*-*",
		"-*-lucida-*-r-*-*-*-240-*-*-p-*-*-*",
		"-*-*-*-r-*-sans-*-240-*-*-p-*-*-*",
		"-*-*-*-r-*-*-*-240-*-*-m-*-*-*",
		"fixed",
		NULL
	};
	int               font_Index;
	int               text_Length;
	int               text_X;
	int               text_Y;
	int               text_Width;
	int               text_Height;
	char*             text_List[XSUBLIM_TEXT_COUNT];
	int               text_Used[XSUBLIM_TEXT_COUNT];
	char              text_Text[XSUBLIM_TEXT_LENGTH+1];
	char*             text_Phrase;
	char*             text_Word;
	int               text_Index;
	int               text_Item;
	int               text_Count;
	struct
	{
		int outline_X;
		int outline_Y;
	}                 text_Outline[] =
	{
		{ -1,-1 },
		{  1,-1 },
		{ -1, 1 },
		{  1, 1 },
		{  0, 0 }
	};
	int               text_OutlineIndex;
	XImage*           image_Image = NULL;
	int               image_X = 0;
	int               image_Y = 0;
	int               image_Width = 0;
	int               image_Height = 0;
	int               arg_Count;
	int               arg_FlagCenter;
	int               arg_FlagOutline;
	int               arg_FlagScreensaver;
	int               arg_FlagRandom;
	int               arg_DelayShow;
	int               arg_DelayWord;
	int               arg_DelayPhraseMin;
	int               arg_DelayPhraseMax;
	char*             arg_Text;
	char*             arg_Source;

	/* Set-up ---------------------------------------------------------- */

	/* Catch signals */
	Xsublim_Sig_Last = -1;
	for (sig_Number = 0;sig_Signal[sig_Number] != -1;sig_Number++)
	{
		signal(sig_Number,xsublim_Sig_Catch);
	}

	/* Randomize -- only need to do this here because this program
           doesn't use the `screenhack.h' or `lockmore.h' APIs. */
# undef ya_rand_init
        ya_rand_init (0);

	/* Handle all the X nonsense */
#if defined(__sgi)
	SgiUseSchemes("none");
#endif
	for (arg_Count = 0;options[arg_Count].option != NULL;arg_Count++)
	{
		;
	}
	app_App = XtAppInitialize(&app,progclass,options,arg_Count,&argc,argv,
	 defaults,0,0);

        /* jwz */
        if (argc > 1)
          {
            int x = 18;
            int end = 78;
            int i;
            int count = (sizeof(options)/sizeof(*options))-1;
            fprintf(stderr, "Unrecognised option: %s\n", argv[1]);
            fprintf (stderr, "Options include: ");
            for (i = 0; i < count; i++)
              {
                char *sw = options [i].option;
                Bool argp = (options [i].argKind == XrmoptionSepArg);
                int size = strlen (sw) + (argp ? 6 : 0) + 2;
                if (x + size >= end)
                  {
                    fprintf (stderr, "\n\t\t ");
                    x = 18;
                  }
                x += size;
                fprintf (stderr, "%s", sw);
                if (argp) fprintf (stderr, " <arg>");
                if (i != count-1) fprintf (stderr, ", ");
              }
            fprintf (stderr, ".\n");
            exit (-1);
          }

	dpy = XtDisplay(app_App);
	XtGetApplicationNameAndClass(dpy,&progname,&progclass);
	win_Root = RootWindowOfScreen(XtScreen(app_App));
	XtDestroyWidget(app_App);

	/* Get the arguments */
	arg_FlagCenter = get_boolean_resource(dpy, XSUBLIM_ARG_CENTER,"Boolean");
	arg_FlagOutline = get_boolean_resource(dpy, XSUBLIM_ARG_OUTLINE,"Boolean");
	arg_FlagScreensaver = get_boolean_resource(dpy, XSUBLIM_ARG_SCREENSAVER,
	 "Boolean");
	arg_FlagRandom = get_boolean_resource(dpy, XSUBLIM_ARG_RANDOM,"Boolean");
	arg_DelayShow = get_integer_resource(dpy, XSUBLIM_ARG_DELAYSHOW,"Integer");
	arg_DelayWord = get_integer_resource(dpy, XSUBLIM_ARG_DELAYWORD,"Integer");
	arg_DelayPhraseMin = get_integer_resource(dpy, XSUBLIM_ARG_DELAYPHRASEMIN,
	 "Integer");
	arg_DelayPhraseMax = get_integer_resource(dpy, XSUBLIM_ARG_DELAYPHRASEMAX,
	 "Integer");
	if (arg_DelayPhraseMax < arg_DelayPhraseMin)
	{
		arg_DelayPhraseMax = arg_DelayPhraseMin;
	}

	/* Get the phrases */
	text_Index = 0;
	text_Item = 0;
	text_Count = 0;
	memset(text_Used,0,sizeof(text_Used));
	arg_Source = get_string_resource(dpy, XSUBLIM_ARG_FILE,"Filename");
	if (arg_Source != NULL)
	{
		FILE*       file_Fs;
		struct stat file_Stat;

		file_Fs = fopen(arg_Source,"rb");
		if (file_Fs == NULL)
		{
			fprintf(stderr,"%s: Could not open '%s'\n",progname,
			 arg_Source);
			exit(-1);
		}
		if (fstat(fileno(file_Fs),&file_Stat) != 0)
		{
			fprintf(stderr,"%s: Could not stat '%s'\n",progname,
			 arg_Source);
			exit(-1);
		}
		arg_Text = calloc(1,file_Stat.st_size+1);
		if (arg_Text != NULL)
		{
			if (fread(arg_Text,file_Stat.st_size,1,file_Fs) != 1)
			{
				fprintf(stderr,"%s: Could not read '%s'\n",
				 progname,arg_Source);
				exit(-1);
			}
		}
		fclose(file_Fs);
	}
	else
	{
		arg_Source = get_string_resource(dpy, XSUBLIM_ARG_PROGRAM,
		 "Executable");
		if (arg_Source != NULL)
		{
			char* exe_Command = calloc(1,strlen(arg_Source)+10);
			FILE* exe_Fs;

			if (exe_Command == NULL)
			{
				fprintf(stderr,
				 "%s: Could not allocate space for '%s'\n",
				 progname,arg_Source);
				exit(-1);
			}
			sprintf(exe_Command,"( %s ) 2>&1",arg_Source);

			exe_Fs = popen(exe_Command,"r");
			if (exe_Fs == NULL)
			{
				fprintf(stderr,"%s: Could not run '%s'\n",
				 progname,arg_Source);
				exit(-1);
			}
			arg_Text = calloc(1,XSUBLIM_PROGRAM_SIZE);
			if (arg_Text != NULL)
			{
				if (fread(arg_Text,1,XSUBLIM_PROGRAM_SIZE,
				 exe_Fs) <= 0)
				{
					fprintf(stderr,
					 "%s: Could not read output of '%s'\n",
					 progname,arg_Source);
					exit(-1);
				}
				if (
				 strstr(arg_Text,": not found") ||
				 strstr(arg_Text,": Not found") ||
				 strstr(arg_Text,": command not found") ||
				 strstr(arg_Text,": Command not found"))
				{
					fprintf(stderr,
					 "%s: Could not find '%s'\n",
					 progname,arg_Source);
					exit(-1);
				}
			}
			fclose(exe_Fs);
		}
		else
		{
			arg_Text =
			 get_string_resource(dpy, XSUBLIM_ARG_PHRASES,"Phrases");
			if (arg_Text != NULL)
			{
				arg_Text = strdup(arg_Text);
			}
		}
	}
	if (arg_Text != NULL)
	{
		while (((text_Phrase = strtok(arg_Text,"\n")) != NULL) &&
		 (text_Count < XSUBLIM_TEXT_COUNT))
		{
			arg_Text = NULL;
			text_List[text_Count] = text_Phrase;
			text_Count++;
		}
		text_List[text_Count] = NULL;
	}
	if (text_Count == 0)
	{
		fprintf(stderr,"%s: No text to display\n",progname);
		exit(-1);
	}

	/* Load the font */
	font_Font = load_font_retry(dpy,
	 get_string_resource(dpy, XSUBLIM_ARG_FONT,"Font"));
	font_Index = 0;
	while ((font_Font == NULL) && (font_List[font_Index] != NULL))
	{
		font_Font = load_font_retry(dpy,font_List[font_Index]);
		font_Index++;
	}
	if (font_Font == NULL)
	{
		fprintf(stderr,"%s: Couldn't load a font\n",progname);
		exit(-1);
	}

	/* Create the GCs */
	XGetWindowAttributes(dpy,win_Root,&attr_Win);
	gc_ValFore.font = font_Font->fid;
	gc_ValFore.foreground = get_pixel_resource(dpy,
                                                   attr_Win.colormap,
                                                   "foreground","Foreground");
	gc_ValFore.background = get_pixel_resource(dpy,
                                                   attr_Win.colormap,
                                                   "background","Background");
	gc_ValFore.subwindow_mode = IncludeInferiors;
	gc_GcFore = XCreateGC(dpy,win_Root,
	 (GCFont|GCForeground|GCBackground|GCSubwindowMode),&gc_ValFore);
	gc_ValBack.font = font_Font->fid;
	gc_ValBack.foreground = get_pixel_resource(dpy,
                                                   attr_Win.colormap,
                                                   "background","Background");
	gc_ValBack.background = get_pixel_resource(dpy,
                                                   attr_Win.colormap,
                                                   "foreground","Foreground");
	gc_ValBack.subwindow_mode = IncludeInferiors;
	gc_GcBack = XCreateGC(dpy,win_Root,
	 (GCFont|GCForeground|GCBackground|GCSubwindowMode),&gc_ValBack);

	/* Loop ------------------------------------------------------------ */
	while (Xsublim_Sig_Last == -1)
	{
		/* Once-per-phrase stuff ----------------------------------- */

		/* If we're waiting for a screensaver... */
		if (arg_FlagScreensaver != FALSE)
		{
			/* Find the screensaver's window */
			win_Root = xsublim_Ss_GetWindow(dpy);
			if (win_Root == 0)
			{
				usleep(30000000);
				continue;
			}
		}

		/* Pick the next phrase */
		if (arg_FlagRandom != FALSE)
		{
			text_Item = random()%text_Count;
			text_Index = 0;
		}
		while (text_Used[text_Item] != FALSE)
		{
			text_Index++;
			text_Item++;
			if (text_Index == text_Count)
			{
				text_Index = 0;
				memset(text_Used,0,sizeof(text_Used));
			}
			if (text_List[text_Item] == NULL)
			{
				text_Item = 0;
			}
		}
		text_Used[text_Item] = TRUE;
		strncpy(text_Text,text_List[text_Item],
		 XSUBLIM_TEXT_LENGTH);
		text_Phrase = text_Text;

		/* Run through the phrase */
		while (((text_Word = strtok(text_Phrase," \t")) != NULL) &&
		 (Xsublim_Sig_Last == -1))
		{
			text_Phrase = NULL;

			/* Once-per-word stuff ----------------------------- */

			/* Find the text's position */
			XGetWindowAttributes(dpy,win_Root,&attr_Win);
			text_Length = strlen(text_Word);
			text_Width = XTextWidth(font_Font,text_Word,
			 text_Length)+XSUBLIM_TEXT_OUTLINE*2;
			text_Height = font_Font->ascent+font_Font->descent+1+
			 XSUBLIM_TEXT_OUTLINE*2;
			if (arg_FlagCenter == FALSE)
			{
				text_X = random()%(attr_Win.width-text_Width);
				text_Y = random()%(attr_Win.height-
				 text_Height);
			}
			else
			{
				text_X = (attr_Win.width/2)-(text_Width/2);
				text_Y = (attr_Win.height/2)-(text_Height/2);
			}

			/* Find the image's position (and pad it out slightly,
			   otherwise bits of letter get left behind -- are
			   there boundry issues I don't know about?) */
			image_X = text_X-16;
			image_Y = text_Y;
			image_Width = text_Width+32;
			image_Height = text_Height;
			if (image_X < 0)
			{
				image_X = 0;
			}
			if (image_Y < 0)
			{
				image_Y = 0;
			}
			if (image_X+image_Width > attr_Win.width)
			{
				image_Width = attr_Win.width-image_X;
			}
			if (image_Y+image_Height > attr_Win.height)
			{
				image_Height = attr_Win.height-image_Y;
			}

			/* Influence people for our own ends --------------- */

			/* Grab the server -- we can't let anybody draw over
			   us */
			XSync(dpy,FALSE);
			XGrabServer(dpy);
			XSync(dpy,FALSE);

			/* Set up an error handler that ignores BadMatches --
			   since the screensaver can take its window away at
			   any time, any call that uses it might choke */
			Xsublim_Sh_Status = 0;
			Xsublim_Sh_Handler =
			 XSetErrorHandler(xsublim_Sh_Handler);

			/* Save the current background */
			image_Image = XGetImage(dpy,win_Root,image_X,
			 image_Y,image_Width,image_Height,~0L,ZPixmap);

			/* If we've successfully saved the background... */
			if (image_Image != NULL)
			{
				if (Xsublim_Sh_Status == 0)
				{
					/* Draw the outline */
					if (arg_FlagOutline != FALSE)
					{
						for (text_OutlineIndex = 0;
						 text_Outline[
						 text_OutlineIndex].outline_X
						 != 0;text_OutlineIndex++)
						{
							/* Y'know, eight
							   character tabs and
							   descriptive variable
							   names become
							   annoying at some
							   point... */
							XDrawString(
							 dpy,
							 win_Root,gc_GcBack,
							 text_X+text_Outline[
							 text_OutlineIndex].
							 outline_X*
							 XSUBLIM_TEXT_OUTLINE,
							 text_Y+
							 (font_Font->ascent)+
							 text_Outline[
							 text_OutlineIndex].
							 outline_Y*
							 XSUBLIM_TEXT_OUTLINE,
							 text_Word,
							 text_Length);
						}
					}

					/* Draw the word */
					XDrawString(dpy,win_Root,
					 gc_GcFore,text_X,
					 text_Y+(font_Font->ascent),text_Word,
					 text_Length);
				}
				if (Xsublim_Sh_Status == 0)
				{
					/* Wait a bit */
					XSync(dpy,FALSE);
					if (Xsublim_Sig_Last == -1)
					{
						usleep(arg_DelayShow);
					}
	
					/* Restore the background */
					XPutImage(dpy,win_Root,
					 gc_GcFore,image_Image,0,0,image_X,
					 image_Y,image_Width,image_Height);
				}

				/* Free the image */
				XDestroyImage(image_Image);
			}

			/* Restore the error handler, ungrab the server */
                        XSync(dpy,FALSE);
			XSetErrorHandler(Xsublim_Sh_Handler);
			XUngrabServer(dpy);
                        XSync(dpy,FALSE);

			/* Pause between words */
			if (Xsublim_Sig_Last == -1)
			{
				usleep(arg_DelayWord);
			}
		}

		/* Pause between phrases */
		if (Xsublim_Sig_Last == -1)
		{
			usleep(random()%(arg_DelayPhraseMax-
			 arg_DelayPhraseMin+1)+arg_DelayPhraseMin);
		}
	}

	/* Exit ------------------------------------------------------------ */
	for (sig_Number = 0;sig_Signal[sig_Number] != -1;sig_Number++)
	{
		signal(sig_Number,SIG_DFL);
	}
	kill(getpid(),Xsublim_Sig_Last);

	return 0;
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
  pthread_t timer_thread;
  pthread_t comms_thread;
  pthread_attr_t pthread_custom_attr;
  char buf[1024];
  FILE *f;
  int c;

  extern byte action;
  extern byte action_value;
  extern int act_after;

  if (argc == 1) {
    action = ACT_NONE;
    exitAfter = 10;
  } else if (argc == 5) {
    act_after = atoi(argv[1]);
    action = atoi(argv[2]);
    action_value = atoi(argv[3]);
    exitAfter = atoi(argv[4]);
  } else {
    fprintf(stderr, "Usage: ./master action_after action action_val exit\n");
    exit(1);
  }

  switch(fork()) {
  case -1:
    perror("Fork failed");
    exit(1);
  case 0:
    f = popen("./slave", "r");
    while(fgets(buf, 1024, f)) {
      printf(buf);
      fflush(stdout);
    }
    pclose(f);
    exit(1);
  }

  printf("Starting master\n");
  fflush(stdout);

  alarm(10);

  address = 0;

  rfd = open("0", O_RDONLY);
  wfd = open("1", O_WRONLY | O_NONBLOCK);

  pthread_attr_init(&pthread_custom_attr);
  
  pthread_create(&timer_thread, &pthread_custom_attr, timer, NULL);
  pthread_create(&comms_thread, &pthread_custom_attr, comms, NULL);

  comms_main();

  pthread_join(timer_thread, NULL);
  pthread_join(comms_thread, NULL);
  
  return 0;
}
Exemplo n.º 17
0
int dbf_show_records (DBF *dbf)
{
  int i,err=0;
  double cmp;
  int len;
  ui32 position;
  CONDITION *p;
  
  char cmd[256];
  char tmpname [L_tmpnam]="/tmp/dbf2txt-XXXXXX";
  FILE *fp;
  
  /* Set var_id */
  for (p=dbf->condition;p;p=p->next)
  {
    for (i=0;i<dbf->NumberOfFields;i++)
    {
      if ((xstrcmpi (dbf->sub_header[i]->FieldName,p->var))==0)
      {
        p->var_id=i;
        break;
      }
    }
    if (i==dbf->NumberOfFields)
    {
      printf ("field \'%s\' not found in archive dbf\n",p->var);
      err=-1;
    }
  }
  if (err)
    return err;


  if ((mkstemp(tmpname))<0)
  {
    perror ("mkstemp");
    return -1;
  }
  if ((fp=fopen (tmpname,"w"))==NULL)
  {
    printf ("Cannot open `%s`\n",tmpname);
    perror ("");
    return -1;
  }
    
  /* Applying conditions */
  dbf->NumberOfRecords=0;
  for (i=1;i<=dbf->header->NumberOfRecords;i++)
  {
    _dbf_load_record (dbf->fp_in, dbf->header, dbf->record, i, dbf->header->LengthOfOneDataRecord);
    if (_dbf_isdelete(dbf->record)>0)
      continue;
    
    p=dbf->condition;
    
    while (p)
    {
      position=char2ui32(dbf->sub_header[p->var_id]->DisplacementOfFieldInRecord);
      len=LengthOfField(dbf->sub_header[p->var_id]);
      if (_dbf_isnumeric(dbf->sub_header[p->var_id]))
        cmp=(strtod(dbf->record+position,NULL) - strtod(p->val,NULL));
      else
        cmp=(double)strncmp (dbf->record+position,p->val,strlen(p->val));
    
      if ( (p->op_id==EQ && cmp==0) || (p->op_id==LT && cmp<0) || 
           (p->op_id==LE && cmp<=0) || (p->op_id==GT && cmp>0) || 
           (p->op_id==GE && cmp>=0) || (p->op_id==NE && cmp!=0) )
        p=p->next;     
      else
        break;
      
    }
    if (p==NULL)
    {
      dbf->NumberOfRecords++;
      dbf_push_record (dbf, i, fp);
    }
  }
  fclose (fp);
  
  if (dbf->NumberOfRecords==0)
  {
    printf ("Record not found!\n");
    return 0;
  }

  sprintf (cmd,"LC_COLLATE=C sort %s -k2",tmpname);
  fp=popen (cmd, "r");
 
  err=dbf_dump (dbf,fp,tmpname);

  return err;
        
}
Exemplo n.º 18
0
/**
 * makecommonpart: make a common part for "mains.html" and "index.html"
 *
 *	@param[in]	title
 *	@param[in]	defines
 *	@param[in]	files
 *	@return	index	common part
 */
static char *
makecommonpart(const char *title, const char *defines, const char *files)
{
	FILE *ip;
	STRBUF *sb = strbuf_open(0);
	STRBUF *ib = strbuf_open(0);
	char buf[MAXFILLEN];
	const char *tips = "Go to the GLOBAL project page.";
	const char *_, *item;

	strbuf_puts(sb, title_begin);
	strbuf_puts(sb, title);
	strbuf_puts_nl(sb, title_end);
	strbuf_puts_nl(sb, poweredby_begin);
	strbuf_sprintf(sb, "Last updated %s%s\n", now(), br);
	if (Iflag) {
		snprintf(buf, sizeof(buf), "Powered by GLOBAL-%s.", get_version());
		strbuf_puts(sb, gen_href_begin_with_title_target(NULL, www, NULL, NULL, tips,"_top"));
		strbuf_puts(sb, gen_image(CURRENT, "pglobe", buf));
		strbuf_puts(sb, gen_href_end());
		strbuf_puts(sb, br);
	} else {
		strbuf_sprintf(sb, "Powered by %sGLOBAL-%s%s.%s\n",
			gen_href_begin_with_title_target(NULL, www, NULL, NULL, tips, "_top"),
			get_version(),
			gen_href_end(),
			br);
	}
	strbuf_puts_nl(sb, poweredby_end);
	strbuf_puts_nl(sb, hr);
	/*
	 * Print items according to the value of variable 'item_order'.
	 */
	for (item = item_order; *item; item++) {
		switch (*item) {
		case 'c':
			if (caution) {
				strbuf_puts_nl(sb, caution_begin);
				strbuf_sprintf(sb, "<font size='+2' color='red'>CAUTION</font>%s\n", br);
				strbuf_sprintf(sb, "This hypertext consists of %d files.\n", html_count);
				strbuf_puts_nl(sb, "Please don't download the whole hypertext using a hypertext copy tool.");
				strbuf_puts_nl(sb, "Our network cannot afford such traffic.");
				strbuf_puts_nl(sb, "Instead, you can generate the same thing in your computer using");
				strbuf_puts(sb, gen_href_begin_with_title_target(NULL, www, NULL, NULL, NULL, "_top"));
				strbuf_puts(sb, "GLOBAL source code tag system");
				strbuf_puts_nl(sb, gen_href_end());
				strbuf_puts_nl(sb, "Thank you.");
				strbuf_puts_nl(sb, caution_end);
				strbuf_sprintf(sb, "\n%s\n", hr);
			}
			break;
		case 's':
			if (fflag) {
				strbuf_puts(sb, makesearchpart(NULL));
				strbuf_puts_nl(sb, hr);
			}
			break;
		case 't':
			if (call_file || callee_file) {
				strbuf_puts(sb, header_begin);
				if (call_file) {
					strbuf_puts(sb, gen_href_begin(NULL, "call", normal_suffix, NULL));
					strbuf_puts(sb, title_call_tree);
					strbuf_puts(sb, gen_href_end());
				}
				if (call_file && callee_file)
					strbuf_puts(sb, " / ");
				if (callee_file) {
					strbuf_puts(sb, gen_href_begin(NULL, "callee", normal_suffix, NULL));
					strbuf_puts(sb, title_callee_tree);
					strbuf_puts(sb, gen_href_end());
				}
				strbuf_puts_nl(sb, header_end);
				strbuf_puts_nl(sb, hr);
			}
			break;
		case 'm':
			strbuf_sprintf(sb, "%sMAINS%s\n", header_begin, header_end);

			snprintf(buf, sizeof(buf), PQUOTE "%s --result=ctags-xid --encode-path=\" \t\" --nofilter=path %s" PQUOTE, quote_shell(global_path), main_func);
			ip = popen(buf, "r");
			if (!ip)
				die("cannot execute '%s'.", buf);
			strbuf_puts_nl(sb, gen_list_begin());
			while ((_ = strbuf_fgets(ib, ip, STRBUF_NOCRLF)) != NULL) {
				char fid[MAXFIDLEN];
				const char *ctags_x = parse_xid(_, fid, NULL);

				strbuf_puts_nl(sb, gen_list_body(SRCS, ctags_x, fid));
			}
			strbuf_puts_nl(sb, gen_list_end());
			if (pclose(ip) != 0)
				die("terminated abnormally '%s' (errno = %d).", buf, errno);
			strbuf_puts_nl(sb, hr);
			break;
		case 'd':
			if (aflag && !Fflag) {
				strbuf_puts(sb, header_begin);
				strbuf_puts(sb, title_define_index);
				strbuf_puts_nl(sb, header_end);
				strbuf_puts(sb, defines);
			} else {
				strbuf_puts(sb, header_begin);
				strbuf_puts(sb, gen_href_begin(NULL, "defines", normal_suffix, NULL));
				strbuf_puts(sb, title_define_index);
				strbuf_puts(sb, gen_href_end());
				strbuf_puts_nl(sb, header_end);
			}
			strbuf_puts_nl(sb, hr);
			break;
		case 'f':
			if (Fflag) {
				strbuf_puts(sb, header_begin);
				strbuf_puts(sb, gen_href_begin(NULL, "files", normal_suffix, NULL));
				strbuf_puts(sb, title_file_index);
				strbuf_puts(sb, gen_href_end());
				strbuf_puts_nl(sb, header_end);
			} else {
				strbuf_puts(sb, header_begin);
				strbuf_puts(sb, title_file_index);
				strbuf_puts_nl(sb, header_end);
				if (tree_view) {
					strbuf_puts_nl(sb, tree_control);
					strbuf_puts_nl(sb, tree_loading);
					if (tree_view_type) {
						strbuf_sprintf(sb, tree_begin_using, tree_view_type);
						strbuf_putc(sb, '\n');
					} else {
						strbuf_puts_nl(sb, tree_begin);
					}
				} else if (table_flist)
					strbuf_puts_nl(sb, flist_begin);
				else if (!no_order_list)
					strbuf_puts_nl(sb, list_begin);
				strbuf_puts(sb, files);
				if (tree_view)
					strbuf_puts_nl(sb, tree_end);
				else if (table_flist)
					strbuf_puts_nl(sb, flist_end);
				else if (!no_order_list)
					strbuf_puts_nl(sb, list_end);
				else
					strbuf_puts_nl(sb, br);
			}
			strbuf_puts_nl(sb, hr);
			break;
		default:
			warning("unknown item '%c'. (Ignored)", *item);
			break;
		}
	}
	strbuf_close(ib);

	return strbuf_value(sb);
	/* doesn't close string buffer */
}
int main(int argc, char *argv[]) {
    FILE *pipe;
    int args = 0;
    char buffer[256] = { 0 };
    char url_buffer[4096] = { 0 };
    char encoded_url_buffer[4096] = { 0 };
    conf_t conf = { { 0 }, { 0 }, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

    CURL *curl;
    CURLcode res;

    // check if debug is ON
    if(argc > 1) {
        if(strcmp(argv[1], "--debug") == 0) {
            DEBUG = 1;
        }
    }

    // get database configuration
    if(read_config(&conf)) {
        return 1;
    }

    // format beginning of URL
    strcat(encoded_url_buffer, conf.url);
    strcat(encoded_url_buffer, "?");

    if(DEBUG) {
        printf("System Info:\n\n");
    }

    if(conf.cpu_cores) {
        pipe = popen("cat /proc/cpuinfo | grep processor | wc -l", "r");
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        strcat(url_buffer, "cpu_cores=");
        strcat(url_buffer, buffer);
        args = 1;
        if(DEBUG) printf("cpu_cores = %s\n", buffer);
        fclose(pipe);
    }

    if(conf.cpu_load) {
        // save top output to tmp file
        pipe = popen("top -n 2 > /tmp/mor_top_tmp.txt", "r");

        // wait for 2 iterations to complete
        sleep(5);

        // read tmp file
        pipe = popen("cat /tmp/mor_top_tmp.txt | grep 'Cpu(s)' | tail -n+2 | sed 's/.*, *\\([0-9.]*\\)%\\id.*/\\1/' | awk '{print  100 - $5}'", "r");
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "cpu_load=");
        strcat(url_buffer, buffer);
        args = 1;
        if(DEBUG) printf("cpu_load = %s\n", buffer);
        fclose(pipe);

        // remove tpm file
        pipe = popen("rm -fr /tmp/mor_top_tmp.txt", "r");
        fclose(pipe);
    }

    if(conf.ram_total || conf.ram_free || conf.ram_used || conf.ram_buffers) {
        char var1[256];
        char var2[256];
        char var3[256];
        char var4[256];
        pipe = popen("free -k | grep -Po '\\d+' | head -n 5", "r");
        fscanf(pipe, "%s %s %s %s %s", var1, var2, var3, var4, var4);
        if(conf.ram_total) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_total=");
            strcat(url_buffer, var1);
            args = 1;
            if(DEBUG) printf("ram_total = %s\n", var1);
        }
        if(conf.ram_used) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_used=");
            strcat(url_buffer, var2);
            args = 1;
            if(DEBUG) printf("ram_used = %s\n", var2);
        }
        if(conf.ram_free) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_free=");
            strcat(url_buffer, var3);
            args = 1;
            if(DEBUG) printf("ram_free = %s\n", var3);
        }
        if(conf.ram_buffers) {
            if(args) strcat(url_buffer, "&");
            strcat(url_buffer, "ram_buffers=");
            strcat(url_buffer, var4);
            args = 1;
            if(DEBUG) printf("ram_buffers = %s\n", var4);
        }
        fclose(pipe);
    }

    if(conf.mysql) {
        pipe = popen("service mysqld status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "mysql=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("mysql = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("mysql = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.httpd) {
        pipe = popen("service httpd status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "httpd=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("httpd = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("httpd = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.asterisk) {
        pipe = popen("service asterisk status | grep -o 'running'", "r");;
        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "asterisk=");
        if(strcmp(buffer, "running") == 0) {
            strcat(url_buffer, "1");
            if(DEBUG) printf("asterisk = 1\n");
        } else {
            strcat(url_buffer, "0");
            if(DEBUG) printf("asterisk = 0\n");
        }
        args = 1;
        fclose(pipe);
    }

    if(conf.hdd) {
        char pipe_buffer[256] = { 0 };

        sprintf(pipe_buffer, "df -h %s | grep -Po '[0-9]+%%' | sed 's|%%||'", conf.file_system);

        pipe = popen(pipe_buffer, "r");

        fgets(buffer, 256, pipe);
        buffer[strlen(buffer) - 1] = 0;
        if(args) strcat(url_buffer, "&");
        strcat(url_buffer, "hdd=");
        strcat(url_buffer, buffer);
        if(DEBUG) printf("hdd = %s\n", buffer);
        args = 1;
        fclose(pipe);
    }

    if(args) {
        encode_url(url_buffer, encoded_url_buffer);

        if(DEBUG) {
            printf("\nHTTP Request:\n\n");
            printf("%s\n\n", encoded_url_buffer);
        } else {
            FILE *curl_resp = tmpfile();

            curl_global_init(CURL_GLOBAL_ALL);
            curl = curl_easy_init();
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl_resp);

            if(curl) {
                curl_easy_setopt(curl, CURLOPT_URL, encoded_url_buffer);
                res = curl_easy_perform(curl);
                if(res != CURLE_OK) {
                    fprintf(stderr, "cURL error %d\n", res);
                }
            } else {
                fprintf(stderr, "Cannot initiate cURL\n");
                return 1;
            }

            curl_easy_cleanup(curl);
            curl_global_cleanup();

            fclose(curl_resp);
        }
    }

    return 0;
}
Exemplo n.º 20
0
int main() 
{
  u32 	nbufsread;     	// the number of buffers read in
  char		*savebuf;       // the buffer to save 
  SysInfo		*systmp;
  ChannelInfo		*chtmp;
  EventBuffer		*event;
  DIOBuffer		*dio;
  PosBuffer		posbuf[1];
  char 		tmpstring[TMPSTRINGLEN+1];	// a temporary buffer 
  char 		filename[TMPSTRINGLEN+1];	// a temporary buffer 
  int			tmplen; 	// the length of the data in tmbbuf
  int 		tmp1, tmp2, diskfree;
  short		datatype;
  char 		*outfilename;	// the name of the file to save data to
  gzFile		outfile;	// the pointer for the output file
  int                 message;	// a temporary message variable
  int			messagedata[MAX_BUFFER_SIZE]; // message data can contain a sysinfo or channelinfo structure
  int			messagedatalen; // the length of the data in the message
  int			nspikes;
  int			savebufsize;     // the size of the input data buffer in bytes
  u32			tmpbufsize;			
  int 		error;
  int 		i, id;
  int			lastmessage;	// the last socket we got a message on
  int			tmpsize;
  int			closefile;	// 1 if the file is to be closed
  int			newdata;	// 1 if new data were received 
  FILE		*pipe;
  OpenFileMessage 	*ofm;

  sysinfo.acq = 0;
  sysinfo.diskon = 0;
  sysinfo.fileopen = 0;
  closefile = 0;
  outfile = NULL;

  /* set the type of program we are in for messaging */
  sysinfo.program_type = SPIKE_SAVE_DATA;

  sysinfo.statusfile == NULL;

  if (STATUSFILE == NULL) {
    /* open up the status file if it is not stderr*/
    gethostname(tmpstring,80);
    sprintf(filename, "spike_save_data_status_%s", tmpstring);
    if ((STATUSFILE = fopen(filename, "w")) == NULL) {
      fprintf(stderr, "spike_main: error opening status file\n");
      exit(-1);
    }
  }

  fprintf(STATUSFILE, "spike_save_data: starting messaging\n");
  if (StartNetworkMessaging(server_message, client_message, server_data, 
        client_data) < 0) {
    fprintf(STATUSFILE, "spike_save: Error establishing messaging\n");
    saveexit(1);
  }

  // we need to allocate enough space for a buffer of any type, so
  // we allocate a large buffer
  //savebuf = (char *) malloc(SAVE_BUF_SIZE);
  savebuf = (char *) malloc(1000000 * sizeof(char));

  while (1) { 
    newdata = 0;
    /* set up the initial list of file descriptors to watch */
    SetupFDList(&readfds, &maxfds, server_message, server_data);
    select(maxfds, &readfds, NULL, NULL, NULL);
    id = 0;
    /* check for incoming data */
    while ((i = netinfo.datainfd[id]) != -1) {
      if (FD_ISSET(server_data[i].fd, &readfds)) {
        /* check to see if the disk is on, and if not, get the message
         * and discard it. Note that this works for everyone except
         * spike_process_posdata, as it only sends data out when the
         * disk is on.  */
        if ((!sysinfo.diskon) && (i != SPIKE_PROCESS_POSDATA)) {
          message = GetMessage(server_data[i].fd, savebuf, &savebufsize, 1);
        }
        else {
          newdata = 1;
          tmpsize = 0;
          switch(i) {
            case SPIKE_DAQ: 
              /* get the data */
              message = GetMessage(server_data[SPIKE_DAQ].fd, savebuf, &savebufsize, 1);
              /* check to see if this is an event */
              if (message == EVENT) {
                event = (EventBuffer *) messagedata;
                datatype = EVENT_DATA_TYPE;
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }
                if ((tmpsize = gzwrite(outfile, event, sizeof(EventBuffer))) != sizeof(EventBuffer)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                }
              }
              else if (message == DIGITALIO_EVENT) {
                /* write the behav, the port, and the status */
                datatype = DIGITALIO_DATA_TYPE;
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }
                /* write out the data */
                if ((tmpsize = gzwrite(outfile, savebuf, savebufsize))
                    != savebufsize) {
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                  error = 1;
                }
              } 
              else {
                if (message == SPIKE_DATA) {
                  datatype = SPIKE_DATA_TYPE;
                }
                else if (message == CONTINUOUS_DATA) {
                  datatype = CONTINUOUS_DATA_TYPE;
                }
                /* write out the data type */
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }

                /* write out the data size */
                if ((tmpsize = gzwrite(outfile, &savebufsize, sizeof(int))) != sizeof(int)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);

                }

                /* write out the data */
                if ((tmpsize = gzwrite(outfile, savebuf, savebufsize)) != savebufsize) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);

                }
              }
              break;
            case SPIKE_PROCESS_POSDATA:
              /* get the position buffer */
              GetMessage(server_data[SPIKE_PROCESS_POSDATA].fd, 
                  savebuf, &savebufsize, 1);
              /* write out the data type */
              datatype = POSITION_DATA_TYPE;
              if ((tmpsize = gzwrite(outfile, &datatype, 
                      sizeof(short))) != sizeof(short)) {
                error = 1;
                fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

              }
              /* write out the data. Note the that first element of
               * the data is the size of the buffer, so we don't need
               * to*/
              //fprintf(stderr, "writing out %d position bytes \n", savebufsize);
              if ((tmpsize = gzwrite(outfile, savebuf, savebufsize))
                  != savebufsize) {
                fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                error = 1;
              }
              break;
            case SPIKE_MAIN: 
              /* get the event or digital IO event*/
              message = GetMessage(server_data[SPIKE_MAIN].fd, 
                  savebuf, &savebufsize, 0);
              if (message == EVENT) {
                event = (EventBuffer *) savebuf;
                datatype = EVENT_DATA_TYPE;
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }
                if ((tmpsize = gzwrite(outfile, event, sizeof(EventBuffer))) != sizeof(EventBuffer)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                }
              }
              else if (message == DIGITALIO_EVENT) {
                /* write the behav, the port, and the status */
                datatype = DIGITALIO_DATA_TYPE;
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }
                /* write out the data */
                if ((tmpsize = gzwrite(outfile, savebuf, savebufsize))
                    != savebufsize) {
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                  error = 1;
                }
              } 
              else if (message == TIME_CHECK) {
                /* write the time data */
                datatype = TIME_CHECK_DATA_TYPE;
                if ((tmpsize = gzwrite(outfile, &datatype, 
                        sizeof(short))) != sizeof(short)) {
                  error = 1;
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, sizeof(short));

                }
                /* write out the data */
                if ((tmpsize = gzwrite(outfile, savebuf, savebufsize))
                    != savebufsize) {
                  fprintf(STATUSFILE, "spike_save_data: writing error: %d written, %d tried\n", tmpsize, savebufsize);
                  error = 1;
                }
              }
              break;
          }
          if (error) {
            /* stop saving and send a SAVE_ERROR message */
            fprintf(STATUSFILE,"spike_save_data: Error in saving data\n");
            sysinfo.diskon = 0;
            SendMessage(client_message[SPIKE_MAIN].fd, SAVE_ERROR, NULL, 0);
          }
          lastmessage = i;
          break;
        }
      }
      id++;
    }
    id = 0;
    /* check for messages */
    while ((i = netinfo.messageinfd[id]) != -1) {
      if (FD_ISSET(server_message[i].fd, &readfds)) {
        message = GetMessage(server_message[i].fd,
            (char *) messagedata, &messagedatalen, 0);
        error = 0;
        switch(message) {
          case STOP_ACQUISITION:
            sysinfo.acq = 0;
            SendMessage(client_message[SPIKE_MAIN].fd, ACQUISITION_STOPPED, 
                NULL, 0);
            break;
          case START_ACQUISITION:
            sysinfo.acq = 1;
            SendMessage(client_message[SPIKE_MAIN].fd, ACQUISITION_STARTED, 
                NULL, 0);
            break;
          case START_SAVE:
            sysinfo.diskon = 1;
            SendMessage(client_message[SPIKE_MAIN].fd, 
                SAVE_STARTED, NULL, 0);
            break;
          case STOP_SAVE:
            sysinfo.diskon = 0;
            SendMessage(client_message[SPIKE_MAIN].fd, 
                SAVE_STOPPED, NULL, 0);
            break;
          case OPEN_FILE:
            /* we can get this message in the middle of saving 
             * data if the main program has determined that the 
             * current file size is too  large, so we need to 
             * close the current file if it is open */
            if (outfile != NULL)  gzclose(outfile);
            ofm = (OpenFileMessage *) messagedata;

            /* we will have already checked to make sure that the 
             * file can be opened */
            /* make sure the file name is correctly terminated */
            strncpy(sysinfo.datafilename, ofm->filename, 
                sizeof(sysinfo.datafilename));
            sysinfo.datafilename[sizeof(sysinfo.datafilename)-1] = '\0';
            if (ofm->type != OpenFileMessage::GZip) {
              sprintf(tmpstring, "file type is not GZip, but rather was: %d; defaulting to GZip!\n", (int)ofm->type);
              StatusMessage(tmpstring, client_message);
            }
            // build string to pass to gzopen specifying open more, 
            // compression level, etc
            snprintf(tmpstring, sizeof(tmpstring), "ab%u", 
                ofm->compression_level);
            sysinfo.use_compression = ofm->compression_level ? 
              true : false;
            sysinfo.compression_level = ofm->compression_level;
            outfile = gzopen(sysinfo.datafilename, tmpstring);
            if( Z_NULL == outfile) {
              fprintf(STATUSFILE, "gzopen() failed to open file: %s with options %s\n", sysinfo.datafilename, tmpstring);
            }
            else{
              fprintf(STATUSFILE, "gzopen() opened file: %s with options %s\n", sysinfo.datafilename, tmpstring);
              sysinfo.fileopen = 1;
            }     
            snprintf(tmpstring, sizeof(tmpstring), "df %s\n", 
                sysinfo.datafilename);
            diskfree = 0;
            if ((pipe = popen(tmpstring, "r")) == NULL) {
              sprintf(tmpstring, "Error opening pipe to check disk usage");
              StatusMessage(tmpstring, client_message);
            }
            else {
              fgets(tmpstring, TMPSTRINGLEN, pipe);
              fscanf(pipe, "%s%d%d%d", tmpstring, &tmp1, &tmp2, &diskfree);
            }
            /* convert KB to MB for diskfree */
            diskfree /= 1024;
            pclose(pipe);
            SendMessage(client_message[SPIKE_MAIN].fd, FILE_OPENED,
                (char *) &diskfree, sizeof(int));
            break;
          case CLOSE_FILE:
            closefile = 1;
            break;
          case SYSTEM_INFO:
            /* we don't need any systeminfo information in this
             * module */
            break;
          case EXIT:

            saveexit(0);		        
            break;
          default:
            break;
        }
      }
      id++;
    }
    /* close the file only if no new data came in on the last iteration of the for loop */
    if (closefile && !newdata) {
      gzclose(outfile);
      outfile = NULL;
      sysinfo.fileopen = 0;
      SendMessage(client_message[SPIKE_MAIN].fd, FILE_CLOSED, NULL, 0);
      closefile = 0;
    }
  }
  return 0;
}
Exemplo n.º 21
0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void ifb_printProcStatus (void)
{
	int		i, alive=0, dead=0;
#if 0
	FILE *fp;
	int state;
	char buff[MAXLINE];
	char proc_usr[8], proc_stime[8], proc_tmptime[16];
	int  proc_pid;
	char cmd[] = "ps -ef|grep DAPP=|awk '{ print $1, $2, $5}'";
    char *pos = NULL;
	int  pos_idx=0;
#endif
	if (displayQkeyFlag) {
		fprintf(stderr,"===================================================================================================\n");
		fprintf(stderr," SYSTEM OPERATION MODE : %s\n", ifb_getSysOperMode(loc_sadb->loc_system_dup.myLocalDupStatus));
		fprintf(stderr,"===================================================================================================\n");
		fprintf(stderr," Process    PID      STATUS  MSG_Q_KEY    VERSION  Process    PID      STATUS  MSG_Q_KEY    VERSION  \n");
		fprintf(stderr,"---------------------------------------------------------------------------------------------------");
	} else {
		fprintf(stderr,"===================================================================================================\n");
		fprintf(stderr," SYSTEM OPERATION MODE : %s\n", ifb_getSysOperMode(loc_sadb->loc_system_dup.myLocalDupStatus));
		fprintf(stderr,"===================================================================================================\n");
		fprintf(stderr," Process    PID      STATUS  START-TIME   VERSION  Process    PID      STATUS  START-TIME   VERSION  \n");
		fprintf(stderr,"---------------------------------------------------------------------------------------------------");
	}

	for (i=0; i<SYSCONF_MAX_APPL_NUM; i++)
	{
		if (!strcasecmp (confProcTbl[i].procName, ""))
			break;
		if (i%2==0) fprintf(stderr,"\n");
		if (confProcTbl[i].runCnt) {
			if (displayQkeyFlag) {
				if (confProcTbl[i].runCnt == 1)
					fprintf(stderr," %-10s %-8d ALIVE   0x%-10x %-8s", confProcTbl[i].procName,
							(int)confProcTbl[i].pid, confProcTbl[i].msgQkey, confProcTbl[i].procVersion);
				else
					fprintf(stderr," %-10s %-8d ALIVE(%d)0x%-10x %-8s", confProcTbl[i].procName,
							(int)confProcTbl[i].pid, confProcTbl[i].runCnt, confProcTbl[i].msgQkey, confProcTbl[i].procVersion);
			} else {
				if (confProcTbl[i].runCnt == 1)
					fprintf(stderr," %-10s %-8d ALIVE   %-12s %-8s", confProcTbl[i].procName,
							(int)confProcTbl[i].pid, confProcTbl[i].startTime, confProcTbl[i].procVersion);
				else
					fprintf(stderr," %-10s %-8d ALIVE(%d)%-12s %-8s", confProcTbl[i].procName,
							(int)confProcTbl[i].pid, confProcTbl[i].runCnt, confProcTbl[i].startTime, confProcTbl[i].procVersion);
			}
			alive += confProcTbl[i].runCnt;
		} else {
			if (displayQkeyFlag) {
				fprintf(stderr," %-10s -        DEAD    0x%-10x %-8s", confProcTbl[i].procName,
						confProcTbl[i].msgQkey, confProcTbl[i].procVersion);
			} else {
				fprintf(stderr," %-10s -        DEAD    -     -      %-8s", confProcTbl[i].procName, "-");
			}
			dead++;
		}
	}
#if 1
	/* SM/CM Process Status Management, by sjjeon */
	{
		int sm_pid,cm_pid, rv;
		char startTM[32];
		char version[]="R1.0.0";

		// SM PID, TIME 을 구한다.
		sm_pid = getProcessID("SMSERVER");
 		rv = getPidInfo(sm_pid, startTM);
 		if(rv >= 0){
			fprintf(stderr,"\n %-10s %-8d ALIVE   %-12s %-8s","SM",sm_pid, startTM, version);
			alive += 1;
		}
		else{
			fprintf(stderr,"\n %-10s -        DEAD    -      %-8s","SM", version);
			dead +=1;
 		}

		// CM PID, TIME 을 구한다.
 		memset(startTM,0x00,sizeof(startTM));
 		cm_pid = getProcessID("CM");
 		rv = getPidInfo(cm_pid, startTM);
 		if(rv >= 0){
			fprintf(stderr," %-10s %-8d ALIVE   %-12s %-8s","CM",cm_pid, startTM, version);
     		alive += 1;
 		}
 		else{
			fprintf(stderr," %-10s -        DEAD    -      %-8s","CM", version);
			dead +=1;
		}
	}
	
#else
	/* SM/CM Process Status Management, by june */
	fp = popen(cmd, "r");
	if (fp == NULL) {
		perror("erro : "); exit(0);
	}
	fprintf(stderr,"\n");
	while(fgets(buff, MAXLINE, fp) != NULL)
	{
		if( sscanf( &buff[0], "%s %d %s", proc_usr, &proc_pid, proc_tmptime)==3) {
//////////////////////////////////////////////////////////////////////////////////////////////////
			pos = strrchr(proc_tmptime, ':');
			if (pos != NULL) {
				pos_idx = pos - proc_tmptime;
				proc_tmptime[pos_idx] = '\0';
			}
			sprintf(proc_stime, "%s", proc_tmptime);
//////////////////////////////////////////////////////////////////////////////////////////////////
			if (!strncmp(proc_usr, "pcube", 5)) {
				strncpy(proc_stime, proc_tmptime, 5);
				if (smLiveCheck()==0) {
					fprintf(stderr," %-10s %-8d ALIVE         %-5s  %-8s", "SMSERVER", proc_pid, proc_stime, "R1.0.0");
					alive++;
				} else {
					fprintf(stderr," %-10s %-8d DEAD          %-5s  %-8s", "SMSERVER", proc_pid, proc_stime, "R1.0.0");
					dead++;
				}
			}
			if (!strncmp(proc_usr, "scmscm", 6)) {
				if (cmLiveCheck()==0) {
					fprintf(stderr," %-10s %-8d ALIVE         %-5s  %-8s", "CM", proc_pid, proc_stime, "R1.0.0");
					alive++;
				} else {
					fprintf(stderr," %-10s %-8d DEAD          %-5s  %-8s", "CM", proc_pid, proc_stime, "R1.0.0");
					dead++;
				}
			}
		}
	}

	state = pclose(fp);
#endif
	fprintf(stderr,"\n===================================================================================================\n");
	fprintf(stderr,"TOTAL:%d (ALIVE:%d, DEAD:%d)\n\n", alive+dead, alive, dead);

	return;

} //----- End of ifb_printProcStatus -----//
Exemplo n.º 22
0
/* Return full path to the current executable, use proc fs if
 * available.
 */
static ALLEGRO_PATH *get_executable_name(void)
{
   ALLEGRO_PATH *path;
   #ifdef ALLEGRO_HAVE_GETEXECNAME
   {
      const char *s = getexecname();
      if (s) {
         if (s[0] == '/') {   /* Absolute path */
            return al_create_path(s);
         }
         else {               /* Not an absolute path */
            path = _find_executable_file(s);
            if (path)
               return path;
         }
      }
   }
   #endif

   /* We need the PID in order to query procfs */
   pid_t pid = getpid();

   /* Try a Linux-like procfs */   
   /* get symolic link to executable from proc fs */
   char linkname[1024];
   char filename[1024];
   struct stat finfo;
   sprintf(linkname, "/proc/%d/exe", (int)pid);
   if (stat(linkname, &finfo) == 0) {
      int len = readlink(linkname, filename, sizeof(filename) - 1);
      if (len > -1) {
         filename[len] = '\0';
         return al_create_path(filename);
      }
   }

   /* Use System V procfs calls if available */
#ifdef ALLEGRO_HAVE_SV_PROCFS_H
   struct prpsinfo psinfo;
   int fd;
   sprintf(linkname, "/proc/%d/exe", (int)pid);
   fd = open(linkname, O_RDONLY);
   if (!fd == -1) {
      ioctl(fd, PIOCPSINFO, &psinfo);
      close(fd);
   
   /* Use argv[0] directly if we can */
#ifdef ALLEGRO_HAVE_PROCFS_ARGCV
      if (psinfo.pr_argv && psinfo.pr_argc) {
          path = _find_executable_file(psinfo.pr_argv[0]);
          if (path)
            return path;
      }
      else
#endif
      {
         /* Emulate it */
         /* We use the pr_psargs field to find argv[0]
          * This is better than using the pr_fname field because we need
          * the additional path information that may be present in argv[0]
          */
    
         /* Skip other args */
         char *s = strchr(psinfo.pr_psargs, ' ');
         if (s)
            s[0] = '\0';
         path = _find_executable_file(psinfo.pr_psargs);
         if (path)
            return path;
      }
   
      /* Try the pr_fname just for completeness' sake if argv[0] fails */
      path = _find_executable_file(psinfo.pr_fname);
      if (path)
         return path;
   }
#endif

   /* Last resort: try using the output of the ps command to at least find */
   /* the name of the file if not the full path */
   char command[1024];
   sprintf(command, "ps -p %d", (int)pid);
   FILE *pipe = popen(command, "r");
   if (pipe) {
      char* ret;
      /* The first line of output is a header */
      ret = fgets(linkname, sizeof(linkname), pipe);
      if(!ret)
         ALLEGRO_ERROR("Failed to read the name of the executable file.\n");
      
      /* The information we want is in the last column; find it */
      int len = strlen(linkname);
      while (linkname[len] != ' ' && linkname[len] != '\t')
         len--;

      /* The second line contains the info we want */
      ret = fgets(linkname, sizeof(linkname), pipe);
      if(!ret)
         ALLEGRO_ERROR("Failed to read the name of the executable file.\n");
      pclose(pipe);

      /* Treat special cases: filename between [] and - for login shell */
      if (linkname[len] == '-')
         len++;

      if (linkname[len] == '[' && linkname[strlen(linkname)] == ']') {
         len++;
         linkname[strlen(linkname)] = '\0';
      }         
      
      /* Now, the filename should be in the last column */
      _al_sane_strncpy(filename, linkname+len+1, strlen(linkname)-len+1);

      path = _find_executable_file(filename);
      if (path)
         return path;

      /* Just return the output from ps... */         
      return al_create_path(filename);
   }

   /* Give up; return empty string */
   return al_create_path("");
}
Exemplo n.º 23
0
//client connection
void respond(int n)
{
  char *result = (char *) malloc(sizeof(char) * 10000);// result return to client
  char *pure_path = (char *) malloc(sizeof(char) * 10000);// get path 
  char *buf = (char *) malloc(sizeof(char) * 10000);
  char *cmd1 = (char *) malloc(sizeof(char) * 1000);// command for 'ls -l'
  char *cmd2 = (char *) malloc(sizeof(char) * 1000);// command for 'cat '
  char *param = "/?param=";
  char *pos;
  char c;
  int index;
  FILE *file;// use pipeline
  struct stat s;// use to know if the path is a file or a directory

  char mesg[99999], *reqline[3], data_to_send[BYTES], path[99999], html[999];
  int rcvd, fd, bytes_read;

  memset( (void*)mesg, (int)'\0', 99999 );

  //rcvd=recv(clients[n], mesg, 99999, 0);
  rcvd=read(clients[n], mesg, 99999);

  if (rcvd<0)    // receive error
    fprintf(stderr,("recv() error\n"));
  else if (rcvd==0)    // receive socket closed
    fprintf(stderr,"Client disconnected upexpectedly.\n");
  else    // message received
    {
      printf("%s", mesg);
      reqline[0] = strtok (mesg, " \t\n");
      if ( strncmp(reqline[0], "GET\0", 4)==0 )
	{
	  reqline[1] = strtok (NULL, " \t");
	  reqline[2] = strtok (NULL, " \t\n");
	  if ( strncmp( reqline[2], "HTTP/1.0", 8)!=0 && strncmp( reqline[2], "HTTP/1.1", 8)!=0 )
	    {
	      write(clients[n], "HTTP/1.0 400 Bad Request\n", 25);
	    }
	  else
	    {
	      pos = strstr(reqline[1], param) + 8; //get 1st position when meet '/?param=', +8 means pass through until the real path. Ex: /home/ubuntu/syspro
	      
	      index = 0;
	      // get path(not include '/?param='), terminate when meet ' '
	      while ((c = *pos) != NULL) {
		pure_path[index++] = c;
		pos++;
	      }
	      pure_path[index] = '\n';
	     	      if (stat(pure_path, &s) == 0) {
		if (s.st_mode & S_IFDIR) {
		  printf("path is a directory\n");
		  strcat(cmd1, "ls -l ");//initialize comd1 as 'ls -l'
		  strcat(cmd1, pure_path);//now, it becomes, for example, "ls -l /home/ubuntu/"
		  file = popen(cmd1, "r");//execute command and open a pipeline
		  while (fgets(buf, 10000, file))
		    strcat(result, buf);//read and add content of the pipeline into result
		  pclose(file);
		  printf("%s\n", result);
		} else if (s.st_mode & S_IFREG) {
		  printf("path is a file\n");
		  strcat(cmd2, "cat ");//initialize comd2 as 'cat '
		  strcat(cmd2, pure_path);//now, it becomes, for example, "cat /home/ubuntu/syspro/f13.c"
		  file = popen(cmd2, "r");//excute command and open a pipeline
		  while (fgets(buf, 10000, file))
		    strcat(result, buf);//read and add content of the pipeline into result
		  pclose(file);
		  printf("%s\n", result);
		} else {
		  printf("something else!\n");
	        }
	      } else {
		strcat(result, "Error!\n");
		printf("wtf! Error!!\n");
	      }
	      write(clients[n], result,strlen(result));
	    }
	}
    }
  //Closing SOCKET
  shutdown (clients[n], SHUT_RDWR);      //All further send and recieve operations are DISABLED...
  close(clients[n]);
  clients[n]=-1;
  exit(0);
}
Exemplo n.º 24
0
static Boolean
Connect(Widget W)
{
    if (Host_Name(W) && strlen(Host_Name(W)) > 0 &&
        Host_Port(W) && strlen(Host_Port(W)) > 0)
    {
	if (!XtIsRealized(XtParent(W)))
	{
	    XtAddEventHandler(XtParent(W),
			      StructureNotifyMask,
			      False,
			      (XtEventHandler)DelayedConnect,
			      W);
	}
	else
	{
	    while (XtAppPending(XtWidgetToApplicationContext(XtParent(W))))
	    {
		XtAppProcessEvent(XtWidgetToApplicationContext(XtParent(W)), XtIMAll);
	    }
	    switch (Host_Type(W))
	    {
	    case XltHOST_CLIENT:
		if (strcmp(Host_Name(W), "-") == 0)
		{
		    Host_Fd(W) = fileno(stdin);
		}
		else
		{
		    Host_Fd(W) = SockOpen(Host_Name(W), Host_Port(W));
		}
		if (Host_Fd(W) >= 0)
		{
		    _XltHostCallbackStruct tmp;
		    String Name;
		    String Class;
		    FILE *xrdb;
		    String xrdb_command;
		    String base = "xrdb -merge -nocpp -display";

		    Host_InputId(W) = XtAppAddInput(XtWidgetToApplicationContext(W),
						    Host_Fd(W),
						    (XtPointer)XtInputReadMask,
						    (XtInputCallbackProc)InputHandler,
						    W);
		    xrdb_command = XtMalloc(strlen(base) + strlen(DisplayString(XtDisplay(XtParent(W)))) + 2);
		    sprintf(xrdb_command, "%s %s", base, DisplayString(XtDisplay(XtParent(W))));
		    xrdb = popen(xrdb_command, "w");
		    if (xrdb != NULL)
		    {
			XtGetApplicationNameAndClass(XtDisplay(XtParent(W)), &Name, &Class);
			fprintf(xrdb, "%s.Host: %s\n%s.Service: %s\n",
				Class,
				Host_Name(W),
				Class,
				Host_Port(W));
			pclose(xrdb);
		    }
		    XtFree(xrdb_command);
		    Host_Throttle(W) = False;
		    tmp.reason = XltCR_CONNECT;
		    XtCallCallbackList(W, Host_ConnectCallback(W), &tmp);
		}
		break;
	    case XltHOST_SERVER:
		Host_Fd(W) = Listen(Host_Port(W));
		if (Host_Fd(W) > 0)
		{
		    Host_InputId(W) = XtAppAddInput(XtWidgetToApplicationContext(W),
						    Host_Fd(W),
						    (XtPointer)XtInputReadMask,
						    (XtInputCallbackProc)ConnectionRequest,
						    W);
		}
		break;
	    default:
		fprintf(stderr, "%s: Unknown host type\n", XtName(W));
		break;
	    }
	}
    }
    else
    {
    }
    return (True);
}
Exemplo n.º 25
0
bool ExportCL(AudacityProject *project, bool stereo, wxString fName,
              bool selectionOnly, double t0, double t1, MixerSpec *mixerSpec)
{
   int rate = int(project->GetRate() + 0.5);
   wxWindow *parent = project;
   TrackList *tracks = project->GetTracks();
   
   wxString command = gPrefs->Read(wxT("/FileFormats/ExternalProgramExportCommand"), wxT("lame - '%f'"));
   command.Replace(wxT("%f"), fName);

   /* establish parameters */
   int channels = stereo ? 2 : 1;
   unsigned long totalSamples = (unsigned long)((t1 - t0) * rate + 0.5);
   unsigned long sampleBytes = totalSamples * channels * SAMPLE_SIZE(int16Sample);

   /* fill up the wav header */
   wav_header header;
   header.riffID[0] = 'R';
   header.riffID[1] = 'I';
   header.riffID[2] = 'F';
   header.riffID[3] = 'F';
   header.riffType[0] = 'W';
   header.riffType[1] = 'A';
   header.riffType[2] = 'V';
   header.riffType[3] = 'E';
   header.lenAfterRiff = sampleBytes + 32;

   header.fmtID[0]  = 'f';
   header.fmtID[1]  = 'm';
   header.fmtID[2]  = 't';
   header.fmtID[3]  = ' ';
   header.formatChunkLen = 16;
   header.formatTag      = 1;
   header.channels       = channels;
   header.sampleRate     = rate;
   header.bitsPerSample  = SAMPLE_SIZE(int16Sample) * 8;
   header.blockAlign     = header.bitsPerSample * header.channels;
   header.avgBytesPerSec = header.sampleRate * header.blockAlign;

   header.dataID[0] = 'd';
   header.dataID[1] = 'a';
   header.dataID[2] = 't';
   header.dataID[3] = 'a';
   header.dataLen   = sampleBytes;

   FILE *pipe = popen(OSFILENAME(command), "w");

   /* write the header */

   fwrite( &header, sizeof(wav_header), 1, pipe );

   sampleCount maxBlockLen = 44100 * 5;

   bool cancelling = false;

   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(selectionOnly, &numWaveTracks, &waveTracks);
   Mixer *mixer = new Mixer(numWaveTracks, waveTracks,
                            tracks->GetTimeTrack(),
                            t0, t1,
                            channels, maxBlockLen, true,
                            rate, int16Sample, true, mixerSpec);

   GetActiveProject()->ProgressShow(_("Export"),
      selectionOnly ?
      _("Exporting the selected audio using command-line encoder") :
      _("Exporting the entire project using command-line encoder"));

   while(!cancelling) {
      sampleCount numSamples = mixer->Process(maxBlockLen);

      if (numSamples == 0)
         break;
      
      samplePtr mixed = mixer->GetBuffer();

      char *buffer = new char[numSamples * SAMPLE_SIZE(int16Sample) * channels];
      wxASSERT(buffer);

      // Byte-swapping is neccesary on big-endian machines, since
      // WAV files are little-endian
#if wxBYTE_ORDER == wxBIG_ENDIAN
      {
         short *buffer = (short*)mixed;
         for( int i = 0; i < numSamples; i++ )
            buffer[i] = wxINT16_SWAP_ON_BE(buffer[i]);
      }
#endif

      fwrite( mixed, numSamples * channels * SAMPLE_SIZE(int16Sample), 1, pipe );

      int progressvalue = int (1000 * ((mixer->MixGetCurrentTime()-t0) /
                                       (t1-t0)));
      cancelling = !GetActiveProject()->ProgressUpdate(progressvalue);

      delete[]buffer;
   }
   GetActiveProject()->ProgressHide();

   delete mixer;

   pclose( pipe );

   return true;
}
Exemplo n.º 26
0
Arquivo: io.c Projeto: 10v/cmusphinx
FILE *fopen_comp (char *file, char *mode, int32 *ispipe)
{
    char command[16384];
    FILE *fp;
    int32 k, isgz;
    
    k = strlen (file);
    
#if (WIN32)
    *ispipe = (k > 3) &&
	((strcmp (file+k-3, ".gz") == 0) || (strcmp (file+k-3, ".GZ") == 0));
    isgz = *ispipe;
#else
    *ispipe = 0;
    isgz = 0;
    if ((k > 2) && ((strcmp (file+k-2, ".Z") == 0) || (strcmp (file+k-2, ".z") == 0))) {
	*ispipe = 1;
    } else {
	if ((k > 3) &&
	    ((strcmp (file+k-3, ".gz") == 0) || (strcmp (file+k-3, ".GZ") == 0))) {
	    *ispipe = 1;
	    isgz = 1;
	}
    }
#endif

    if (*ispipe) {
#if (WIN32)
	if (strcmp (mode, "r") == 0) {
	    sprintf (command, "gzip.exe -d -c %s", file);
	    if ((fp = _popen (command, mode)) == NULL) {
		E_ERROR_SYSTEM("_popen (%s,%s) failed\n", command, mode);
		return NULL;
	    }
	} else {
	    E_ERROR ("fopen_comp not implemented for mode = %s\n", mode);
	    return NULL;
	}
#else
	if (strcmp (mode, "r") == 0) {
	    if (isgz)
		sprintf (command, "gunzip -c %s", file);
	    else
		sprintf (command, "zcat %s", file);
	    
	    if ((fp = popen (command, mode)) == NULL) {
		E_ERROR_SYSTEM("popen (%s,%s) failed\n", command, mode);
		return NULL;
	    }
	} else if (strcmp (mode, "w") == 0) {
	    if (isgz)
		sprintf (command, "gzip > %s", file);
	    else
		sprintf (command, "compress -c > %s", file);
	    
	    if ((fp = popen (command, mode)) == NULL) {
		E_ERROR_SYSTEM("popen (%s,%s) failed\n", command, mode);
		return NULL;
	    }
	} else {
	    E_ERROR ("fopen_comp not implemented for mode = %s\n", mode);
	    return NULL;
	}
#endif
    } else {
        fp = fopen (file, mode);
    }

    return (fp);
}
Exemplo n.º 27
0
int
main(int argc, char **argv)
{
	char dbpath[MAXPATHLEN];
	char cwd[MAXPATHLEN];
	STRBUF *sb = strbuf_open(0);
	int optchar;
	int option_index = 0;
	STATISTICS_TIME *tim;

	/*
	 * Setup GTAGSCONF and GTAGSLABEL environment variable
	 * according to the --gtagsconf and --gtagslabel option.
	 */
	preparse_options(argc, argv);
	/*
	 * Get the project root directory.
	 */
	if (!vgetcwd(cwd, MAXPATHLEN))
		die("cannot get current directory.");
	canonpath(cwd);
	/*
	 * Load configuration file.
	 */
	openconf(cwd);
	configuration();
	setenv_from_config();
	{
		char *env = getenv("GTAGS_OPTIONS");
		if (env && *env)
			argv = prepend_options(&argc, argv, env);
	}
	/*
	 * Execute gtags_hook before the jobs.
	 */
	if (getconfs("gtags_hook", sb)) {
		char *p = serialize_options(argc, argv);
		set_env("GTAGS_COMMANDLINE", p);
		free(p);
		if (system(strbuf_value(sb)))
			fprintf(stderr, "gtags-hook failed: %s\n", strbuf_value(sb));
	}
	logging_arguments(argc, argv);
	while ((optchar = getopt_long(argc, argv, "cd:f:iIn:oOqvwse", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			/* already flags set */
			break;
		case OPT_CONFIG:
			show_config = 1;
			if (optarg)
				config_name = optarg;
			break;
		case OPT_GTAGSCONF:
		case OPT_GTAGSLABEL:
			/* These options are already parsed in preparse_options() */
			break;
		case OPT_SINGLE_UPDATE:
			iflag++;
			single_update = optarg;
			break;
		case OPT_ACCEPT_DOTFILES:
			accept_dotfiles = 1;
			break;
		case OPT_SKIP_UNREADABLE:
			skip_unreadable = 1;
			break;
		case 'c':
			cflag++;
			break;
		case 'd':
			dump_target = optarg;
			break;
		case 'f':
			file_list = optarg;
			break;
		case 'i':
			iflag++;
			break;
		case 'I':
			Iflag++;
			break;
		case 'o':
			/*
			 * Though the -o(--omit-gsyms) was removed, this code
			 * is left for compatibility.
			 */
			break;
		case 'O':
			Oflag++;
			break;
		case 'q':
			qflag++;
			break;
		case 'w':
			wflag++;
			break;
		case 'v':
			vflag++;
			break;
		default:
			usage();
			break;
		}
	}
	if (qflag) {
		vflag = 0;
		setquiet();
	}
	if (vflag)
		setverbose();
	if (wflag)
		set_langmap_wflag();
	if (show_version)
		version(NULL, vflag);
	if (show_help)
		help();

	argc -= optind;
        argv += optind;

	/* If dbpath is specified, -O(--objdir) option is ignored. */
	if (argc > 0)
		Oflag = 0;
	if (show_config) {
		openconf(setupdbpath(0) == 0 ? get_root() : NULL);
		if (config_name)
			printconf(config_name);
		else
			fprintf(stdout, "%s\n", getconfline());
		exit(0);
	} else if (dump_target) {
		/*
		 * Dump a tag file.
		 */
		DBOP *dbop = NULL;
		const char *dat = 0;
		int is_gpath = 0;

		if (!test("f", dump_target))
			die("file '%s' not found.", dump_target);
		if ((dbop = dbop_open(dump_target, 0, 0, DBOP_RAW)) == NULL)
			die("file '%s' is not a tag file.", dump_target);
		/*
		 * The file which has a NEXTKEY record is GPATH.
		 */
		if (dbop_get(dbop, NEXTKEY))
			is_gpath = 1;
		for (dat = dbop_first(dbop, NULL, NULL, 0); dat != NULL; dat = dbop_next(dbop)) {
			const char *flag = is_gpath ? dbop_getflag(dbop) : "";

			if (*flag)
				printf("%s\t%s\t%s\n", dbop->lastkey, dat, flag);
			else
				printf("%s\t%s\n", dbop->lastkey, dat);
		}
		dbop_close(dbop);
		exit(0);
	} else if (Iflag) {
#define REQUIRED_MKID_VERSION "4.5"
		char *p;

		if (!usable("mkid"))
			die("mkid not found.");
		if (read_first_line("mkid --version", sb))
			die("mkid cannot executed.");
		p = strrchr(strbuf_value(sb), ' ');
		if (p == NULL)
			die("invalid version string of mkid: %s", strbuf_value(sb));
		switch (check_version(p + 1, REQUIRED_MKID_VERSION)
#ifdef _WIN32
			| strcmp(p + 1, "3.2.99") == 0
#endif
			)  {
		case 1:		break;	/* OK */
		case 0:		die("mkid version %s or later is required.", REQUIRED_MKID_VERSION);
		default:	die("invalid version string of mkid: %s", strbuf_value(sb));
		}
	}

	/*
	 * If 'gtags.files' exists, use it as a file list.
	 * If the file_list other than "-" is given, it must be readable file.
	 */
	if (file_list == NULL && test("f", GTAGSFILES))
		file_list = GTAGSFILES;
	if (file_list && strcmp(file_list, "-")) {
		if (test("d", file_list))
			die("'%s' is a directory.", file_list);
		else if (!test("f", file_list))
			die("'%s' not found.", file_list);
		else if (!test("r", file_list))
			die("'%s' is not readable.", file_list);
	}
	/*
	 * Regularize the path name for single updating (--single-update).
	 */
	if (single_update) {
		static char regular_path_name[MAXPATHLEN];
		char *p = single_update;
		
#if _WIN32 || __DJGPP__
		for (; *p; p++)
			if (*p == '\\')
				*p = '/';
		p = single_update;
#define LOCATEFLAG MATCH_AT_FIRST|IGNORE_CASE
#else
#define LOCATEFLAG MATCH_AT_FIRST
#endif
		if (isabspath(p)) {
			char *q = locatestring(p, cwd, LOCATEFLAG);

			if (q && *q == '/')
				snprintf(regular_path_name, MAXPATHLEN, "./%s", q + 1);
			else
				die("path '%s' is out of the project.", p);

		} else {
			if (p[0] == '.' && p[1] == '/')
				snprintf(regular_path_name, MAXPATHLEN, "%s", p);
			else
				snprintf(regular_path_name, MAXPATHLEN, "./%s", p);
		}
		single_update = regular_path_name;
	}
	/*
	 * Decide directory (dbpath) in which gtags make tag files.
	 *
	 * Gtags create tag files at current directory by default.
	 * If dbpath is specified as an argument then use it.
	 * If the -i option specified and both GTAGS and GRTAGS exists
	 * at one of the candidate directories then gtags use existing
	 * tag files.
	 */
	if (iflag) {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (!gtagsexist(cwd, dbpath, MAXPATHLEN, vflag))
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	} else {
		if (argc > 0)
			realpath(*argv, dbpath);
		else if (Oflag) {
			char *objdir = getobjdir(cwd, vflag);

			if (objdir == NULL)
				die("Objdir not found.");
			strlimcpy(dbpath, objdir, sizeof(dbpath));
		} else
			strlimcpy(dbpath, cwd, sizeof(dbpath));
	}
	if (iflag && (!test("f", makepath(dbpath, dbname(GTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GRTAGS), NULL)) ||
		!test("f", makepath(dbpath, dbname(GPATH), NULL)))) {
		if (wflag)
			warning("GTAGS, GRTAGS or GPATH not found. -i option ignored.");
		iflag = 0;
	}
	if (!test("d", dbpath))
		die("directory '%s' not found.", dbpath);
	/*
	 * Start processing.
	 */
	if (accept_dotfiles)
		set_accept_dotfiles();
	if (skip_unreadable)
		set_skip_unreadable();
	if (vflag) {
		const char *config_path = getconfigpath();
		const char *config_label = getconfiglabel();

		fprintf(stderr, "[%s] Gtags started.\n", now());
		if (config_path)
			fprintf(stderr, " Using configuration file '%s'.\n", config_path);
		else {
			fprintf(stderr, " Using default configuration.\n");
			if (getenv("GTAGSLABEL"))
				fprintf(stderr, " GTAGSLABEL(--gtagslabel) ignored since configuration file not found.\n");
		}
		if (config_label)
			fprintf(stderr, " Using configuration label '%s'.\n", config_label);
		if (file_list)
			fprintf(stderr, " Using '%s' as a file list.\n", file_list);
	}
	/*
	 * initialize parser.
	 */
	if (vflag && gtags_parser)
		fprintf(stderr, " Using plug-in parser.\n");
	parser_init(langmap, gtags_parser);
	/*
	 * Start statistics.
	 */
	init_statistics();
	/*
	 * incremental update.
	 */
	if (iflag) {
		/*
		 * Version check. If existing tag files are old enough
		 * gtagsopen() abort with error message.
		 */
		GTOP *gtop = gtags_open(dbpath, cwd, GTAGS, GTAGS_MODIFY, 0);
		gtags_close(gtop);
		/*
		 * GPATH is needed for incremental updating.
		 * Gtags check whether or not GPATH exist, since it may be
		 * removed by mistake.
		 */
		if (!test("f", makepath(dbpath, dbname(GPATH), NULL)))
			die("Old version tag file found. Please remake it.");
		(void)incremental(dbpath, cwd);
		print_statistics(statistics);
		exit(0);
	}
	/*
	 * create GTAGS and GRTAGS
	 */
	createtags(dbpath, cwd);
	/*
	 * create idutils index.
	 */
	if (Iflag) {
		FILE *op;
		GFIND *gp;
		const char *path;

		tim = statistics_time_start("Time of creating ID");
		if (vflag)
			fprintf(stderr, "[%s] Creating indexes for idutils.\n", now());
		strbuf_reset(sb);
		/*
		 * Since idutils stores the value of PWD in ID file, we need to
		 * force idutils to follow our style.
		 */
#if _WIN32 || __DJGPP__
		strbuf_puts(sb, "mkid --files0-from=-");
#else
		strbuf_sprintf(sb, "PWD=%s mkid --files0-from=-", quote_shell(cwd));
#endif
		if (vflag)
			strbuf_puts(sb, " -v");
		strbuf_sprintf(sb, " --file=%s/ID", quote_shell(dbpath));
		if (vflag) {
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 1>&2");
		} else {
			strbuf_puts(sb, " >" NULL_DEVICE);
#ifdef __DJGPP__
			if (is_unixy())	/* test for 4DOS as well? */
#endif
			strbuf_puts(sb, " 2>&1");
		}
		if (debug)
			fprintf(stderr, "executing mkid like: %s\n", strbuf_value(sb));
		op = popen(strbuf_value(sb), "w");
		if (op == NULL)
			die("cannot execute '%s'.", strbuf_value(sb));
		gp = gfind_open(dbpath, NULL, GPATH_BOTH, 0);
		while ((path = gfind_read(gp)) != NULL) {
			fputs(path, op);
			fputc('\0', op);
		}
		gfind_close(gp);
		if (pclose(op) != 0)
			die("terminated abnormally '%s' (errno = %d).", strbuf_value(sb), errno);
		if (test("f", makepath(dbpath, "ID", NULL)))
			if (chmod(makepath(dbpath, "ID", NULL), 0644) < 0)
				die("cannot chmod ID file.");
		statistics_time_end(tim);
	}
	if (vflag)
		fprintf(stderr, "[%s] Done.\n", now());
	closeconf();
	strbuf_close(sb);
	print_statistics(statistics);

	return 0;
}
Exemplo n.º 28
0
static inline int
install_filter(char * intf, char * filter_text) {
  FILE *fp;
  int status;
  char fil[40];
  char cmd[1035];
  struct sock_filter * FILTER;
  int filter_len;

  //sprintf(cmd, "tcpdump -dd -i %s %s", intf, filter_text);
  sprintf(cmd, "tcpdump -ddd -i %s %s", intf, filter_text);
  printf("cmd: %s\n", cmd);

  /* Open the command for reading. */
  fp = popen(cmd, "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit;
  }


  /* Read the output a line at a time - output it. */
  fgets(fil, sizeof(fil)-1, fp);
  filter_len = atoi(fil);
  //printf("len: %d\n", filter_len);

  FILTER = (struct sock_filter *)(malloc(sizeof(struct sock_filter) * filter_len));

  //while (fgets(fil, sizeof(fil)-1, fp) != NULL) {
  int i = 0;
  for (i = 0; i < filter_len; i++) {
    struct sock_filter * filter_line = &FILTER[i];
    int n;
    char del = ' ';

    if (fgets(fil, sizeof(fil)-1, fp) == NULL) {
      printf("Error creating filter\n");
      exit(0);
    }

    //printf("%s", fil);
    n = atoi(strtok(fil, &del));
    //printf("val=%d  ", n);
    filter_line->code = (unsigned short)n;

    n = atoi(strtok(NULL, &del));
    //printf("val=%d  ", n);
    filter_line->jt = (unsigned char)n;

    n = atoi(strtok(NULL, &del));
    //printf("val=%d  ", n);
    filter_line->jf = (unsigned char)n;

    n = atoi(strtok(NULL, &del));
    //printf("val=%d  ", n);
    filter_line->k = (unsigned int)n;

    //printf("\n");
  }

  printf("created filter structure\n");

  /* close */
  pclose(fp);

  return 0;
}
//turns off the screen saver if there is one, enabling resumes normal operation
//(could sill have no screen saver)
bool CROSS_OS_DisableSleeps(bool disable)
{



    #ifdef Q_OS_WIN

        if(disable)
            SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED);
        else
            SetThreadExecutionState(ES_CONTINUOUS);


        //power options do nothing in windows 7/8 but should still help in 2000/xp
        static unsigned int timeoutLowPower;
        static unsigned int timeoutPowerOff;
        static unsigned int timeoutScreenSave;
        static bool was_disabled = false;

        if (disable)///disable
        {
            was_disabled = true;
            //save old values
            SystemParametersInfo(SPI_GETLOWPOWERTIMEOUT,   0, &(timeoutLowPower),   0);
            SystemParametersInfo(SPI_GETPOWEROFFTIMEOUT,   0, &(timeoutPowerOff),   0);
            SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &(timeoutScreenSave), 0);

            SystemParametersInfo(SPI_SETLOWPOWERTIMEOUT,   0, NULL, 0);
            SystemParametersInfo(SPI_SETPOWEROFFTIMEOUT,   0, NULL, 0);
            SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, 0, NULL, 0);
        }
        else
        {
            if(was_disabled)//only go back to original settings if
            {
                SystemParametersInfo(SPI_SETLOWPOWERTIMEOUT,   timeoutLowPower,   NULL, 0);
                SystemParametersInfo(SPI_SETPOWEROFFTIMEOUT,   timeoutPowerOff,   NULL, 0);
                SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, timeoutScreenSave, NULL, 0);
            }
        }


    #endif
    #ifdef Q_OS_MAC
       static ScreenSaverWaker GlobalWaker(NULL);
       if(disable)
           GlobalWaker.StartWaking();//will start waking the application and not let screensaver
                                    //turn on
       else
           GlobalWaker.StopWaking();
    #endif
    #ifdef Q_OS_LINUX
       static bool originalON;
       static bool found_orig = false;

       if(!found_orig)//if we dont know what the original is - find it.
       {

           FILE* f = popen("xset q", "r");
           if(f)
           {

               const int BUFFERSIZE = 1000;
               char Buff[BUFFERSIZE];
               QString Buffs;
               while( fgets(Buff,BUFFERSIZE,f))//while there is a string to read
               {
                   Buffs = QString(Buff);
                   Buffs = Buffs.trimmed();
                   //qDebug() << Buffs;
                   if(Buffs == "DPMS is Enabled")
                   {
                       qDebug() << "DPMS is Enabled";
                       originalON = true;
                       found_orig = true;
                       break;
                   }
                   if(Buffs == "DPMS is Disabled")
                   {
                       qDebug() << "DPMS is Disabled";
                       originalON = false;
                       found_orig = true;
                       break;
                   }

               }
           }
       }
       //should be second time we call.
       //if we know the original settings, act accourdingly
       if(found_orig)
       {
           if(disable)
           {
               system("xset -dpms");
           }
           else//revert
           {
               qDebug() << "Reverting DPMS Settings";
               if(originalON)
               {
                   qDebug() << "Setting DPMS Back To On";
                   system("xset +dpms");
               }
               else
               {
                   qDebug() << "Setting DPMS Back To Off";
                   system("xset -dpms");
               }
           }
       }
       else
       {
           qDebug() << "Unable to find dpms flag for power options!";

       }


    #endif

    return true;
}
Exemplo n.º 30
-1
int main(int argc, char *argv[])
{
	char c = 0;
	tomoyo_test_init();

	/* Test mount(). */
	{
		set_profile(3, "file::mount");
		show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 1);
		if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF &&
		    errno == EPERM)
			printf("OK: Permission denied.\n");
		else if (errno == ENODEV)
			printf("OK: No such device.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		set_profile(1, "file::mount");
		show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 0);
		if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF &&
		    errno == ENOMEM)
			printf("OK: Out of memory.\n");
		else if (errno == ENODEV)
			printf("OK: No such device.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		set_profile(3, "file::mount");
		show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 0);
		if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF &&
		    errno == ENOMEM)
			printf("OK: Out of memory.\n");
		else if (errno == ENODEV)
			printf("OK: No such device.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		fprintf(domain_fp, "delete allow_mount dev\\011name / "
			"fs\\011name 0\n");
		show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 1);
		if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF &&
		    errno == EPERM)
			printf("OK: Permission denied.\n");
		else if (errno == ENODEV)
			printf("OK: No such device.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		set_profile(1, "file::mount");
		show_prompt("mount(NULL, '/', 'tmpfs') ", 0);
		if (mount(NULL, "/", "tmpfs", 0, NULL))
			printf("BUG: %s\n", strerror(errno));
		else
			printf("OK: Success\n");
		set_profile(3, "file::mount");
		show_prompt("mount(NULL, '/', 'tmpfs') ", 0);
		if (mount(NULL, "/", "tmpfs", 0, NULL))
			printf("BUG: %s\n", strerror(errno));
		else
			printf("OK: Success\n");
		show_prompt("mount('anydev', '/', 'tmpfs') ", 0);
		if (mount("anydev", "/", "tmpfs", 0, NULL))
			printf("BUG: %s\n", strerror(errno));
		else
			printf("OK: Success\n");
		fprintf(domain_fp, "delete allow_mount <NULL> / tmpfs 0\n");
		fprintf(domain_fp, "allow_mount anydev / tmpfs 0\n");
		show_prompt("mount(NULL, '/', 'tmpfs') ", 0);
		if (mount(NULL, "/", "tmpfs", 0, NULL))
			printf("BUG: %s\n", strerror(errno));
		else
			printf("OK: Success\n");
		fprintf(domain_fp, "delete allow_mount anydev / tmpfs 0\n");
		set_profile(2, "file::mount");
		show_prompt("mount(NULL, NULL, 'tmpfs') ", 1);
		if (mount(NULL, NULL, "tmpfs", 0, NULL))
			printf("OK: %s\n", strerror(errno));
		else
			printf("BUG: Did not fail.\n");
		show_prompt("mount(NULL, NULL, NULL) ", 1);
		if (mount(NULL, NULL, NULL, 0, NULL))
			printf("OK: %s\n", strerror(errno));
		else
			printf("BUG: Did not fail.\n");
		show_prompt("mount('/', NULL, NULL) ", 1);
		if (mount("/", NULL, NULL, 0, NULL))
			printf("OK: %s\n", strerror(errno));
		else
			printf("BUG: Did not fail.\n");
		show_prompt("mount('/', NULL, 'tmpfs') ", 1);
		if (mount("/", NULL, "tmpfs", 0, NULL))
			printf("OK: %s\n", strerror(errno));
		else
			printf("BUG: Did not fail.\n");
		show_prompt("mount('/', '/', 'nonexistentfs') ", 1);
		if (mount("/", "/", "nonexistentfs", 0, NULL))
			printf("OK: %s\n", strerror(errno));
		else
			printf("BUG: Did not fail.\n");
		set_profile(0, "file::mount");
	}

	mkdir("/tmp/mount/", 0755);
	mkdir("/tmp/mount_bind/", 0755);
	mkdir("/tmp/mount_move/", 0755);

	/* Test mount(). */
	{
		static char buf[4096];
		char *dev_ram_path = canonicalize_file_name("/dev/ram0");
		if (!dev_ram_path)
			dev_ram_path = canonicalize_file_name("/dev/ram");
		if (!dev_ram_path) {
			dev_ram_path = "/dev/ram0";
			mknod(dev_ram_path, S_IFBLK, MKDEV(1, 0));
		}
		memset(buf, 0, sizeof(buf));
		{
			struct stat sbuf;
			FILE *fp = NULL;
			snprintf(buf, sizeof(buf) - 1, "zcat - > %s",
				 dev_ram_path);
			if (lstat(dev_ram_path, &sbuf) == 0 &&
			    S_ISBLK(sbuf.st_mode) && MAJOR(sbuf.st_rdev) == 1)
				fp = popen(buf, "w");
			if (fp) {
				if (fwrite(compressed_ext2_image_sample, 1,
				    sizeof(compressed_ext2_image_sample), fp) !=
				    sizeof(compressed_ext2_image_sample))
					err(1, "fwrite");
				pclose(fp);
			} else
				fprintf(stderr, "Can't write to %s .\n",
					dev_ram_path);
		}
		set_profile(3, "file::mount");

		/* Test standard case */
		show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for "
			    "'/tmp/mount/'", 1);
		if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == EOF &&
		    errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		/* Test device_name with pattern */
		snprintf(buf, sizeof(buf) - 1, "mount('%s', '/tmp/mount/', "
			 "'ext2') for '%s\\*'", dev_ram_path, dev_ram_path);
		show_prompt(buf, 1);
		if (mount(dev_ram_path, "/tmp/mount/", "ext2", MS_RDONLY, NULL)
		    == EOF && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		/* Test dir_name with pattern */
		show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for "
			    "'/tmp/\\?\\?\\?\\?\\?/'", 1);
		if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == EOF &&
		    errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		/* Test standard case */
		fprintf(domain_fp, "allow_mount none /tmp/mount/ tmpfs 0\n");
		show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for "
			    "'/tmp/mount/'", 0);
		if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		fprintf(domain_fp,
			"delete allow_mount none /tmp/mount/ tmpfs 0\n");

		/* Test device_name with pattern */
		fprintf(domain_fp, "allow_mount %s\\* /tmp/mount/ ext2 1\n",
			dev_ram_path);
		snprintf(buf, sizeof(buf) - 1, "mount('%s', '/tmp/mount/', "
			 "'ext2') for '%s\\*'", dev_ram_path, dev_ram_path);
		show_prompt(buf, 0);
		if (mount(dev_ram_path, "/tmp/mount/", "ext2", MS_RDONLY, NULL)
		    == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		fprintf(domain_fp, "delete allow_mount %s\\* "
			"/tmp/mount/ ext2 1\n", dev_ram_path);

		/* Test dir_name with pattern */
		fprintf(domain_fp,
			"allow_mount none /tmp/\\?\\?\\?\\?\\?/ tmpfs 0\n");
		show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for "
			    "'/tmp/\\?\\?\\?\\?\\?/'", 0);
		if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		fprintf(domain_fp, "delete allow_mount none "
			"/tmp/\\?\\?\\?\\?\\?/ tmpfs 0\n");

		set_profile(0, "file::mount");
		while (umount("/tmp/mount/") == 0)
			c++; /* Dummy. */
	}

	/* Test mount(). */
	{
		mount2("none", "/tmp/mount/", "tmpfs");
		set_profile(3, "file::mount");

		/* Test remount case */
		show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 1);
		if (mount("none", "/tmp/mount/", "tmpfs", MS_REMOUNT, NULL)
		    == EOF && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 1);
		if (mount(NULL, "/tmp/mount/", NULL, MS_REMOUNT, NULL) == EOF
		    && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));
		fprintf(domain_fp, "allow_mount something /tmp/mount/ "
			"--remount 0\n");
		show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 0);
		if (mount(NULL, "/tmp/mount/", NULL, MS_REMOUNT, NULL))
			printf("BUG: %s\n", strerror(errno));
		else
			printf("OK: Success.\n");
		fprintf(domain_fp, "delete allow_mount something /tmp/mount/ "
			"--remount 0\n");

		/* Test bind case */
		show_prompt("mount('/tmp/mount/', '/tmp/mount_bind/', "
			    "MS_BIND)", 1);
		if (mount("/tmp/mount/", "/tmp/mount_bind/", NULL, MS_BIND,
			  NULL) == EOF && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		/* Test move case */
		show_prompt("mount('/tmp/mount/', '/tmp/mount_move/', "
			    "MS_MOVE)", 1);
		if (mount("/tmp/mount/", "/tmp/mount_move/", NULL, MS_MOVE,
			  NULL) == EOF && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		/* Test remount case */
		fprintf(domain_fp,
			"allow_mount any /tmp/mount/ --remount 0\n");
		show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 0);
		if (mount("none", "/tmp/mount/", "tmpfs", MS_REMOUNT, NULL)
		    == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		fprintf(domain_fp, "delete allow_mount any /tmp/mount/ "
			"--remount 0\n");

		/* Test bind case */
		fprintf(domain_fp,
			"allow_mount /tmp/mount/ /tmp/mount_bind/ --bind 0\n");
		show_prompt("mount('/tmp/mount/', '/tmp/mount_bind', MS_BIND)",
			    0);
		if (mount("/tmp/mount/", "/tmp/mount_bind/", NULL, MS_BIND,
			  NULL) == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		set_profile(0, "file::mount");
		umount("/tmp/mount_bind/");
		fprintf(domain_fp, "delete allow_mount /tmp/mount/ "
			"/tmp/mount_bind/ --bind 0\n");

		/* Test move case */
		set_profile(3, "file::mount");
		fprintf(domain_fp, "allow_unmount /tmp/mount/\n");
		fprintf(domain_fp, "allow_mount /tmp/mount/ /tmp/mount_move/ "
			"--move 0\n");
		show_prompt("mount('/tmp/mount/', '/tmp/mount_move/', "
			    "MS_MOVE)", 0);
		if (mount("/tmp/mount/", "/tmp/mount_move/", NULL, MS_MOVE,
			  NULL) == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));
		set_profile(0, "file::mount");
		umount("/tmp/mount_move/");
		fprintf(domain_fp, "delete allow_unmount /tmp/mount/\n");
		fprintf(domain_fp, "delete allow_mount /tmp/mount/ "
			"/tmp/mount_move/ --move 0\n");

		while (umount("/tmp/mount/") == 0)
			c++; /* Dummy. */
	}

	/* Test umount(). */
	{
		/* Test standard case */
		fprintf(domain_fp, "allow_unmount /tmp/mount/\n");

		set_profile(0, "file::umount");
		mount2("none", "/tmp/mount/", "tmpfs");
		set_profile(3, "file::umount");
		show_prompt("umount('/tmp/mount/') for '/tmp/mount/'", 0);
		if (umount("/tmp/mount/") == 0)
			printf("OK\n");
		else
			printf("BUG: %s\n", strerror(errno));
		fprintf(domain_fp, "delete allow_unmount /tmp/mount/\n");

		set_profile(0, "file::umount");

		mount2("none", "/tmp/mount/", "tmpfs");
		set_profile(3, "file::umount");
		show_prompt("umount('/tmp/mount/') for '/tmp/mount/'", 1);
		if (umount("/tmp/mount/") == EOF && errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("FAILED: %s\n", strerror(errno));

		/* Test pattern */
		fprintf(domain_fp, "allow_unmount /tmp/\\?\\?\\?\\?\\?/\n");
		set_profile(0, "file::umount");
		mount2("none", "/tmp/mount/", "tmpfs");
		set_profile(3, "file::umount");
		show_prompt("umount('/tmp/mount/') for "
			    "'/tmp/\\?\\?\\?\\?\\?/'", 1);
		if (umount("/tmp/mount/") == 0)
			printf("OK\n");
		else
			printf("BUG: %s\n", strerror(errno));
		fprintf(domain_fp,
			"delete allow_unmount /tmp/\\?\\?\\?\\?\\?/\n");

		set_profile(0, "file::umount");
		while (umount("/tmp/mount/") == 0)
			c++; /* Dummy. */
	}

	/* Test chroot(). */
	{
		set_profile(3, "file::chroot");

		/* Test standard case */
		fprintf(domain_fp, "allow_chroot /tmp/mount/\n");
		show_prompt("chroot('/tmp/mount/') for '/tmp/mount/'", 0);
		fflush(stdout);
		if (fork() == 0) {
			if (chroot("/tmp/mount/") == 0)
				printf("OK\n");
			else
				printf("FAILED: %s\n", strerror(errno));
			fflush(stdout);
			_exit(0);
		}
		wait(NULL);
		fprintf(domain_fp, "delete allow_chroot /tmp/mount/\n");

		show_prompt("chroot('/tmp/mount/') for '/tmp/mount/'", 1);
		fflush(stdout);
		if (fork() == 0) {
			if (chroot("/tmp/mount/") == EOF && errno == EPERM)
				printf("OK: Permission denied.\n");
			else
				printf("BUG: %s\n", strerror(errno));
			fflush(stdout);
			_exit(0);
		}
		wait(NULL);

		/* Test pattern */
		fprintf(domain_fp, "allow_chroot /tmp/\\?\\?\\?\\?\\?/\n");
		show_prompt("chroot('/tmp/mount/') for "
			    "'/tmp/\\?\\?\\?\\?\\?/'", 0);
		fflush(stdout);
		if (fork() == 0) {
			if (chroot("/tmp/mount/") == 0)
				printf("OK\n");
			else
				printf("FAILED: %s\n", strerror(errno));
			fflush(stdout);
			_exit(0);
		}
		wait(NULL);
		fprintf(domain_fp,
			"delete allow_chroot /tmp/\\?\\?\\?\\?\\?/\n");

		set_profile(0, "file::chroot");
	}

	/* Test pivot_root(). */
	{
		int error;
		static char stack[8192];
		set_profile(3, "file::pivot_root");
		fprintf(domain_fp, "allow_pivot_root %s %s\n",
			 pivot_root_dir, proc_policy_dir);
		snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir,
			 proc_policy_dir);
		show_prompt(stack, 0);
		{
			const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child,
							  NULL);
			while (waitpid(pid, &error, __WALL) == EOF &&
			       errno == EINTR)
				c++; /* Dummy. */
		}
		errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1;
		if (errno == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));

		fprintf(domain_fp, "delete allow_pivot_root %s %s\n",
			pivot_root_dir, proc_policy_dir);
		snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir,
			 proc_policy_dir);
		show_prompt(stack, 1);
		{
			const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child,
							  NULL);
			while (waitpid(pid, &error, __WALL) == EOF &&
			       errno == EINTR)
				c++; /* Dummy. */
		}
		errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1;
		if (errno == EPERM)
			printf("OK: Permission denied.\n");
		else
			printf("BUG: %s\n", strerror(errno));

		set_profile(2, "file::pivot_root");
		snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir,
			 proc_policy_dir);
		show_prompt(stack, 0);
		{
			const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child,
							  NULL);
			while (waitpid(pid, &error, __WALL) == EOF &&
			       errno == EINTR)
				c++; /* Dummy. */
		}
		errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1;
		if (errno == 0)
			printf("OK\n");
		else
			printf("FAILED: %s\n", strerror(errno));

		set_profile(0, "file::pivot_root");

	}

	rmdir("/tmp/mount_move/");
	rmdir("/tmp/mount_bind/");
	rmdir("/tmp/mount/");

	clear_status();
	return 0;
}