Esempio n. 1
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData) {
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

   strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
  DIR *testDir = opendir(szPath);
  if (testDir) {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0) {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

        if (strFiles == "*.*")
           strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();

  int status;
  regex_t re;
  if (regcomp(&re, strFiles, REG_EXTENDED|REG_NOSUB) != 0) {
    return(INVALID_HANDLE_VALUE);
  }

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0) {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    status = regexec(&re, strComp.c_str(), (size_t) 0, NULL, 0);
    if (status == 0) {
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    }
    free(namelist[n]);
  }

  if (namelist)
    free(namelist);

  regfree(&re);

  if (pHandle->m_FindFileResults.size() == 0) {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
Esempio n. 2
0
int top_main(int argc, char **argv)
{
	status_t *statuslist;
	struct dirent **namelist;
	int opt, num, interval, lines;
#if defined BB_FEATURE_AUTOWIDTH && defined BB_FEATURE_USE_TERMIOS
	struct winsize win = { 0, 0, 0, 0 };
#endif
	/* Default update rate is 5 seconds */
	interval = 5;
	/* Default to 25 lines - 5 lines for status */
	lines = 25 - 5;

	/* do normal option parsing */
	while ((opt = getopt(argc, argv, "d:")) > 0) {
	    switch (opt) {
		case 'd':
		    interval = atoi(optarg);
		    break;
		default:
		    show_usage();
	    }
	}

#if defined BB_FEATURE_AUTOWIDTH && defined BB_FEATURE_USE_TERMIOS
	ioctl(fileno(stdout), TIOCGWINSZ, &win);
	if (win.ws_row > 4)
	    lines = win.ws_row - 5;
#endif
	
	/* change to proc */
	if (chdir("/proc") < 0) {
		perror_msg_and_die("chdir('/proc')");
	}
	
	/* read process IDs for all the processes from the procfs */
	num = scandir(".", &namelist, filter_pids, num_sort);
	if (num < 0) {
		perror_msg_and_die("scandir('/proc')");
	}
	if (lines > num) {
		lines = num;
	}

	/* read command line for each of the processes */
	statuslist = read_info(num, namelist);
	if (!statuslist) {
		return EXIT_FAILURE;
	}

	while (1) {
		/* read status for each of the processes */
		read_status(num, statuslist);

		/* display status */
		display_status(lines, statuslist);
		
		sleep(interval);
	}
	
	free(statuslist);
	return EXIT_SUCCESS;
}
Esempio n. 3
0
//TODO: append matches to some data structure instead of just printing them out
// then there can be sweet summaries of matches/files scanned/time/etc
int search_dir(pcre *re, const char* path, const int depth) {
    //TODO: don't just die. also make max depth configurable
    if(depth > MAX_SEARCH_DEPTH) {
        log_err("Search depth greater than %i, giving up.", depth);
        exit(1);
    }
    struct dirent **dir_list = NULL;
    struct dirent *dir = NULL;
    int results = 0;

    FILE *fp = NULL;
    int f_len;
    size_t r_len;
    char *buf = NULL;
    int rv = 0;
    char *dir_full_path = NULL;
    size_t path_length = 0;

    results = scandir(path, &dir_list, &ignorefile_filter, &alphasort);
    if (results > 0) {
        for (int i = 0; i < results; i++) {
            dir = dir_list[i];
            path_length = (size_t)(strlen(path) + strlen(dir->d_name) + 2); // 2 for slash and null char
            dir_full_path = malloc(path_length);
            dir_full_path = strncpy(dir_full_path, path, path_length);
            dir_full_path = strncat(dir_full_path, "/", path_length);
            dir_full_path = strncat(dir_full_path, dir->d_name, path_length);
            load_ignore_patterns(dir_full_path);
            free(dir);
            free(dir_full_path);
        }
    }
    free(dir_list);

    results = scandir(path, &dir_list, &filename_filter, &alphasort);
    if (results == 0)
    {
        log_debug("No results found");
        free(dir_list);
        return(0);
    }
    else if (results == -1) {
        log_err("Error opening directory %s", path);
        return(0);
    }

    for (int i=0; i<results; i++) {
        dir = dir_list[i];
        // XXX: this is copy-pasted from about 30 lines above
        path_length = (size_t)(strlen(path) + strlen(dir->d_name) + 2); // 2 for slash and null char
        dir_full_path = malloc(path_length);
        dir_full_path = strncpy(dir_full_path, path, path_length);
        dir_full_path = strncat(dir_full_path, "/", path_length);
        dir_full_path = strncat(dir_full_path, dir->d_name, path_length);

        log_debug("dir %s type %i", dir_full_path, dir->d_type);
        //TODO: scan files in current dir before going deeper
        if (dir->d_type == DT_DIR && opts.recurse_dirs) {
            log_debug("searching dir %s", dir_full_path);
            rv = search_dir(re, dir_full_path, depth + 1);
            goto cleanup;
            continue;
        }
        fp = fopen(dir_full_path, "r");
        if (fp == NULL) {
            log_err("Error opening file %s. Skipping...", dir_full_path);
            goto cleanup;
            continue;
        }

        rv = fseek(fp, 0, SEEK_END);
        if (rv != 0) {
            log_err("Error fseek()ing file %s. Skipping...", dir_full_path);
            goto cleanup;
        }

        f_len = ftell(fp); //TODO: behave differently if file is HUGE. on 32 bit, anything > 2GB will screw up this program
        if (f_len == 0) {
            log_debug("file is empty. skipping");
            goto cleanup;
        }

        rewind(fp);
        buf = (char*) malloc(sizeof(char) * f_len + 1);
        r_len = fread(buf, 1, f_len, fp);
        buf[r_len] = '\0';
        int buf_len = (int)r_len;

        int buf_offset = 0;
        int offset_vector[MAX_MATCHES_PER_FILE * 2]; //XXXX
        int rc = 0;
        char *match_start = NULL;
        char *match_end = NULL;
        int first_match = 1;
        // In my profiling, most of the execution time is spent in this pcre_exec
        while(buf_offset < buf_len && (rc = pcre_exec(re, NULL, buf, r_len, buf_offset, 0, offset_vector, sizeof(offset_vector))) >= 0 ) {
            log_debug("Match found. File %s, offset %i bytes.", dir_full_path, offset_vector[0]);
            match_start = buf + offset_vector[0];
            match_end = buf + offset_vector[1];
            buf_offset = offset_vector[1];
            print_match(dir_full_path, buf, match_start, match_end, first_match);
            first_match = 0;
        }

        free(buf);

        cleanup:
        if (fp != NULL) {
            fclose(fp);
        }
        free(dir);
        free(dir_full_path);
    }

    free(dir_list);
    return(0);
}
Esempio n. 4
0
static char * lhaMenu(void)
{
  struct  dirent **namelist;
  int N,i,width;
  char * menutxt=NULL;
  void*h;
 
  void (*getpdfsetlist)(char* s, size_t len)=NULL;

  if(!dataPath) return NULL;
  h=dlopen(NULL,RTLD_NOW); 
  getpdfsetlist=dlsym(h,"lhapdf_getpdfsetlist_");
  if(!getpdfsetlist) getpdfsetlist=dlsym(h,"_lhapdf_getpdfsetlist_");
 
  if(getpdfsetlist)
  {  char buff[10000];
     char *ch1,*ch2;
     getpdfsetlist(buff,10000);
     for(i=9999; i>=0 && buff[i]==' '; i--) ;
     buff[i+1]=0;
     i=strlen(buff);
     
     width=0; N=0;
     ch1=ch2=buff;
     if(ch1[0]==0) return NULL;
     for(;ch2!=buff+i; ch1=ch2+1,N++)
     {  ch2=strchr(ch1,' ');
        if(ch2==NULL) ch2=buff+i;
        if(ch2-ch1>width) width=ch2-ch1;   
     }
     
     menutxt=malloc(N*(width+2)+2);
     N=0;
     menutxt[0]=width+2; 
     for(ch1=buff;ch1; ch1=strchr(ch1,' '),N++)
    {  char name[50];
       while(ch1[0]==' ') ch1++;
       sscanf(ch1,"%s",name);
       sprintf(menutxt+1+N*(width+2)," %-*.*s ",width,width,name);
    }
    return menutxt;  
  } 
  
  
  N=scandir(dataPath, &namelist,filter ,alphasort);   
  if(N<=0) return NULL;
                              
  for(i=0,width=0;i<N;i++) 
  {  int l= strlen(namelist[i]->d_name);
     if(width<l) width=l;
  }
  menutxt=malloc(N*(width+1)+2);
  menutxt[0]=width+1; menutxt[1]=0;
  for(i=0;i<N;i++)
  {
    sprintf(menutxt+1+(width+1)*i," %-*.*s",width,width,namelist[i]->d_name);
    free(namelist[i]);
  }
  free(namelist);
  menutxt[N*(width+1)+1]=0;
  return menutxt;
}  
int
populate_entries( struct pci_system * p )
{
    struct dirent ** devices = NULL;
    int n;
    int i;
    int err = 0;


    n = scandir( SYS_BUS_PCI, & devices, scan_sys_pci_filter, alphasort );
    if ( n > 0 ) {
	p->num_devices = n;
	p->devices = calloc( n, sizeof( struct pci_device_private ) );

	if (p->devices != NULL) {
	    for (i = 0 ; i < n ; i++) {
		uint8_t config[48];
		pciaddr_t bytes;
		unsigned dom, bus, dev, func;
		struct pci_device_private *device =
			(struct pci_device_private *) &p->devices[i];


		sscanf(devices[i]->d_name, "%04x:%02x:%02x.%1u",
		       & dom, & bus, & dev, & func);

		device->base.domain = dom;
		device->base.bus = bus;
		device->base.dev = dev;
		device->base.func = func;


		err = pci_device_linux_sysfs_read(& device->base, config, 0,
						  48, & bytes);
		if ((bytes == 48) && !err) {
		    device->base.vendor_id = (uint16_t)config[0]
			+ ((uint16_t)config[1] << 8);
		    device->base.device_id = (uint16_t)config[2]
			+ ((uint16_t)config[3] << 8);
		    device->base.device_class = (uint32_t)config[9]
			+ ((uint32_t)config[10] << 8)
			+ ((uint32_t)config[11] << 16);
		    device->base.revision = config[8];
		    device->base.subvendor_id = (uint16_t)config[44]
			+ ((uint16_t)config[45] << 8);
		    device->base.subdevice_id = (uint16_t)config[46]
			+ ((uint16_t)config[47] << 8);
		}

		if (err) {
		    break;
		}
	    }
	}
	else {
	    err = ENOMEM;
	}
    }

    for (i = 0; i < n; i++)
	free(devices[i]);
    free(devices);

    if (err) {
	free(p->devices);
	p->devices = NULL;
    }

    return err;
}
Esempio n. 6
0
void
clean_q(struct printer *pp)
{
	char *cp, *cp1, *lp;
	struct dirent **queue;
	size_t linerem;
	int didhead, i, n, nitems, rmcp;

	cln_queuecnt++;

	didhead = 0;
	if (generic_qselect == QSEL_BYNAME) {
		printf("%s:\n", pp->printer);
		didhead = 1;
	}

	lp = line;
	cp = pp->spool_dir;
	while (lp < &line[sizeof(line) - 1]) {
		if ((*lp++ = *cp++) == 0)
			break;
	}
	lp[-1] = '/';
	linerem = sizeof(line) - (lp - line);

	cln_foundcore = 0;
	seteuid(euid);
	nitems = scandir(pp->spool_dir, &queue, doselect, sortq);
	seteuid(uid);
	if (nitems < 0) {
		if (!didhead) {
			printf("%s:\n", pp->printer);
			didhead = 1;
		}
		printf("\tcannot examine spool directory\n");
		return;
	}
	if (cln_foundcore) {
		if (!didhead) {
			printf("%s:\n", pp->printer);
			didhead = 1;
		}
		printf("\t** found a core file in %s !\n", pp->spool_dir);
	}
	if (nitems == 0)
		return;
	if (!didhead)
		printf("%s:\n", pp->printer);
	if (cln_debug) {
		printf("\t** ----- Sorted list of files being checked:\n");
		i = 0;
		do {
			cp = queue[i]->d_name;
			printf("\t** [%3d] = %s\n", i, cp);
		} while (++i < nitems);
		printf("\t** ----- end of sorted list\n");
	}
	i = 0;
	do {
		cp = queue[i]->d_name;
		rmcp = 0;
		if (*cp == 'c') {
			/*
			 * A control file.  Look for matching data-files.
			 */
			/* XXX
			 *  Note the logic here assumes that the hostname
			 *  part of cf-filenames match the hostname part
			 *  in df-filenames, and that is not necessarily
			 *  true (eg: for multi-homed hosts).  This needs
			 *  some further thought...
			 */
			n = 0;
			while (i + 1 < nitems) {
				cp1 = queue[i + 1]->d_name;
				if (*cp1 != 'd' || strcmp(cp + 3, cp1 + 3))
					break;
				i++;
				n++;
			}
			if (n == 0) {
				rmcp = 1;
			}
		} else if (*cp == 'e') {
			/*
			 * Must be an errrs or email temp file.
			 */
			rmcp = 1;
		} else {
			/*
			 * Must be a df with no cf (otherwise, it would have
			 * been skipped above) or an rf or tf file (which can
			 * always be removed if it is old enough).
			 */
			rmcp = 1;
		}
		if (rmcp) {
			if (strlen(cp) >= linerem) {
				printf("\t** internal error: 'line' overflow!\n");
				printf("\t**   spooldir = %s\n", pp->spool_dir);
				printf("\t**   cp = %s\n", cp);
				return;
			}
			strlcpy(lp, cp, linerem);
			unlinkf(line);
		}
     	} while (++i < nitems);
}
Esempio n. 7
0
int load_plugin(const char *dir, const char* plugname) {
	struct stat statbuf;
	struct dirent **namelist;
	int n, ret;
	char *full_path, full_name[264];
	DIR *plugindir;

	ret		= 0;
	full_path	= NULL;
	plugin_list	= NULL;

	if (strlen(plugname) > 265) {
		fprintf(stderr, "  Error - Plugin name exceeds maximum length of 256 charakters: %s\n", plugname);
		return(-1);
	}

	/* plugin directory must be configured */
	if (!dir) {
		fprintf(stderr, "  Error - Plugin directory not set while trying to load plugin %s.\n", plugname);
		exit(EXIT_FAILURE);
	}

	if ((plugindir = opendir(dir)) == NULL) {
		fprintf(stderr, "  Error - Unable to open plugin directory: %m.\n");
		exit(EXIT_FAILURE);
	}
	
	DEBUG_FPRINTF(stdout, "  Looking for plugin %s in %s\n", plugname, dir);
	if ((n = scandir(dir, &namelist, 0, alphasort)) < 0) {
		fprintf(stderr, "  Error - Unable to scan plugin directory: %m.\n");
		return(-1);
	} else while(n--) {
		stat(namelist[n]->d_name, &statbuf);

		/* assemble full name */
		memset(full_name, 0, 264);
		strncpy(full_name, "htm_", 4);
		strncpy(&full_name[4], plugname, strlen(plugname));
		strncpy(&full_name[4+strlen(plugname)], ".so", 3);

		if ((ret = fnmatch(full_name, namelist[n]->d_name, 0)) == 0) {
			/* found the plugin */
			if ((full_path = (char *) malloc(strlen(dir) + strlen(namelist[n]->d_name) + 2)) == NULL) {
				perror("  Error - Unable to allocate memory");
				exit(EXIT_FAILURE);
			}
			snprintf(full_path, strlen(dir)+strlen(namelist[n]->d_name)+2, "%s/%s", dir, namelist[n]->d_name);
			DEBUG_FPRINTF(stdout, "  Plugin found: %s\n", full_path);
			config_plugin(full_path);
			free(full_path);
			free(namelist[n]);
			break;
		}
		free(namelist[n]);
	}
	closedir(plugindir);
	if (ret != 0) {
		fprintf(stderr, "  Error - Unable to load plugin %s: %m.\n", full_name);
		exit(EXIT_FAILURE);
	}
	free(namelist);
	
	return(1);
}
Esempio n. 8
0
int recursive_delete(const char *d, const char *file, bool delfiles)
{
	int n=-1;
	int ret=RECDEL_OK;
	struct dirent **dir;
	struct stat statp;
	char *directory=NULL;

	if(!file)
	{
		if(!(directory=prepend_s(d, "", 0))) return RECDEL_ERROR;
	}
	else if(!(directory=prepend_s(d, file, strlen(file))))
	{
		log_out_of_memory(__FUNCTION__);
		return RECDEL_ERROR;
	}

	if(lstat(directory, &statp))
	{
		// path does not exist.
		free(directory);
		return RECDEL_OK;
	}

	if((n=scandir(directory, &dir, 0, 0))<0)
	{
		logp("scandir %s: %s\n", directory, strerror(errno));
		free(directory);
		return RECDEL_ERROR;
	}
	while(n--)
	{
		char *fullpath=NULL;
		if(dir[n]->d_ino==0
		  || !strcmp(dir[n]->d_name, ".")
		  || !strcmp(dir[n]->d_name, ".."))
			{ free(dir[n]); continue; }
		if(!(fullpath=prepend_s(directory,
			dir[n]->d_name, strlen(dir[n]->d_name))))
				break;

		if(is_dir(fullpath))
		{
			int r;
			if((r=recursive_delete(directory,
				dir[n]->d_name, delfiles))==RECDEL_ERROR)
			{
				free(fullpath);
				break;
			}
			// do not overwrite ret with OK if it previously
			// had ENTRIES_REMAINING
			if(r==RECDEL_ENTRIES_REMAINING) ret=r;
		}
		else if(delfiles)
		{
			if(unlink(fullpath))
			{
				logp("unlink %s: %s\n",
					fullpath, strerror(errno));
				ret=RECDEL_ENTRIES_REMAINING;
			}
		}
		else
		{
			ret=RECDEL_ENTRIES_REMAINING;
		}
		free(fullpath);
		free(dir[n]);
	}
	if(n>0)
	{
		ret=RECDEL_ERROR;
		for(; n>0; n--) free(dir[n]);
	}
	free(dir);

	if(ret==RECDEL_OK && rmdir(directory))
	{
		logp("rmdir %s: %s\n", directory, strerror(errno));
		ret=RECDEL_ERROR;
	}
	free(directory);
	return ret;
}
Esempio n. 9
0
int getComList(char *ttylist)
{
	int retval = 0;
	struct dirent **namelist;
	struct serial_struct serinfo;
	char devicedir[1024];
	char devfile[256];
	char driver[64];
	int n = 0, nn, fd;

	ttylist[0] = '\0';
	if ((nn = scandir(SYSDIR, &namelist, NULL, NULL)) > 0)
	{
		while (n < nn) 
		{
			if (strcmp(namelist[n]->d_name,"..") && strcmp(namelist[n]->d_name,".")) 
			{

				// Construct full absolute file path
				sprintf(devicedir, "%s%s", SYSDIR, namelist[n]->d_name);

				// Get the device driver
				get_driver(devicedir, driver);
				if (strlen(driver) > 0)
				{
					// Non empty drivers might be ok
					//printf("Device: /dev/%s, Driver: %s\n", namelist[n]->d_name, driver);
					sprintf(devfile, "/dev/%s", namelist[n]->d_name);					

					if (strstr(driver, "8250") != NULL)
					{
						// Check serial8250-devices separeately
						if ((fd = open(devfile, O_RDWR | O_NONBLOCK | O_NOCTTY)) >= 0) 
						{
							// If device open
							if (ioctl(fd, TIOCGSERIAL, &serinfo) == 0) 
							{
								// If can get get serial_info
								if (serinfo.type != PORT_UNKNOWN)
								{
									// If device type is no PORT_UNKNOWN we accept the port
									//printf("Device 8250 has port, accepted\n");
									strcat(ttylist, "|");
									strcat(ttylist, devfile);
								}
							}
							close(fd);
						}
					} 
					else
					{
						// whatever has a driver and is not serial8250 is sure good
						strcat(ttylist, "|");
						strcat(ttylist, devfile);
					}
				}
			}
			free(namelist[n]);
			n++;
		}
		free(namelist);	
	}
	return (retval);	
}
Esempio n. 10
0
/* include a file or directory */
void include_file(YYLTYPE *yylloc, const char *name) {
  struct stat st;
  struct dirent **namelist;
  char *fn;
  int n;

  struct sourceposition *pos;

  pos = make_sourcepos(yylloc);

  if (stat(name, &st)) {
    if (errno == ENOENT &&
        (index(name, '*') != NULL || index(name, '?') != NULL ||
         index(name, '[') != NULL)) {
      /* Globbing fiesta! */
      glob_t glob_buf;
      if (glob(name, 0, NULL, &glob_buf) != 0) {
        filter_error(pos, "failed to glob \"%s\": %s", name, strerror(errno));
      } else {
        /* We go through the list of files backwards, because
         * step_into_include_file() creates a stack of all the
         * files processed and then works on them in a LIFO
         * fashion -- which would make all of our rules files
         * go backwards.  Since I can't wrap my head around
         * why that is, exactly, I'm hacking it up with
         * this instead.  Fixination appreciated.
         */
        for (n = glob_buf.gl_pathc - 1; n >= 0; n--) {
          if (stat(glob_buf.gl_pathv[n], &st)) {
            filter_error(pos, "stat failed on globbed \"%s\": %s",
                         glob_buf.gl_pathv[n], strerror(errno));
          } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
            if (sourcefile_push(pos, glob_buf.gl_pathv[n])) {
              filtergen_in = current_srcfile->f;
              filtergen_lineno = current_srcfile->lineno;
              // yycolumn = current_srcfile->column;
              if (!filtergen_in) {
                filter_error(pos, "failed to open %s", glob_buf.gl_pathv[n]);
              } else {
                filtergen_push_buffer_state(
                    filtergen__create_buffer(filtergen_in, YY_BUF_SIZE));
              }
            }
          }
        }
      }

      globfree(&glob_buf);
    } else {
      filter_error(pos, "stat failed on \"%s\": %s", name, strerror(errno));
    }
  } else {
    if (S_ISDIR(st.st_mode)) {
      char *b = strdup(name);
      char *base = basename(b);

      if (strcmp("/", base) == 0) {
        filter_error(pos, "cannot include / path; skipping");
        free(b);
        return;
      }
      free(b);

      if ((n = scandir(name, &namelist, NULL, alphasort)) < 0) {
        filter_error(pos, "scandir failed on \"%s\": %s", name,
                     strerror(errno));
      } else {
        while (n--) {
          /* FIXME: assumes d_name */
          if (namelist[n]->d_name[0] == '.') {
            free(namelist[n]);
            continue;
          }
          if (asprintf(&fn, "%s/%s", name, namelist[n]->d_name) < 0) {
            filter_error(
                NULL, "internal error: asprintf failed constructing pathname "
                      "for included file \"%s\"",
                namelist[n]->d_name);
            free(fn);
          } else {
            include_file(yylloc, fn);
            free(fn);
          }
          free(namelist[n]);
        }
        free(namelist);
      }
    } else {
      if (sourcefile_push(pos, name)) {
        filtergen_in = current_srcfile->f;
        filtergen_lineno = current_srcfile->lineno;
        //        yycolumn = current_srcfile->column;
        if (!filtergen_in) {
          filter_error(pos, "failed to open %s", name);
        } else {
          filtergen_push_buffer_state(
              filtergen__create_buffer(filtergen_in, YY_BUF_SIZE));
        }
      }
    }
  }
}
Esempio n. 11
0
int main(
  int argc,
  char **argv
)
#endif
{
  int fd;
  int i;
  int status;
  off_t off;
  struct dirent *d_not;
  struct dirent **namelist;
  struct stat s;


  printf( "\n\n*** READDIR TEST ***\n" );

  printf( "\nchdir to the root directory\n" );
  status = chdir( "/" );
  printf( "chdir() status : %d\n\n", status );

  printf( "\nCreating a series of directories under /\n" );
  i=0;
  while ( strcmp(dnames[i], "END") != 0 )
  {
     status = mkdir( dnames[i], 0x1c0 );
     printf("Creating directory: %s      %d %d   ", dnames[i], status, errno );
     if ( errno == 0 )
        printf(" Success\n");
     else
        printf(" Failure\n");

     i++;
  }

  /*
   * Create files under many and open the directory.
   */

  printf("Create a lot of files\n");
  status = mkdir( "/many", 0x1c0 );
  status = chdir( "/many" );
  for (i = 0; i<44; i++) {
    printf("Create %s\n", many_files[i]);
    fd = open (many_files[i], O_CREAT, S_IRWXU);
    close (fd);
  }
  printf("Open /many and print the directory\n");
  directory_not = opendir( "/many" );
  printdir ( directory_not );
  d_not = readdir( directory_not );

  printf("open /b/myfile\n");
  fd = open ("/b/my_file", O_CREAT, S_IRWXU);
  rtems_test_assert( fd != -1 );
  close (fd);

  printf("scandir a file status: ");
  status = scandir(
     "/b/my_file",
     &namelist,
     select1,
     NULL
  );
  printf("%d\n", status);

  printf("Open /b/new_file\n");
  fd  = open( "/b/new_file", O_CREAT, S_IRWXU );
  rtems_test_assert( fd != -1 );

  printf("fcntl F_SETFD should return 0\n");
  status = fcntl( fd, F_SETFD, 1 );
  rtems_test_assert( status == 0 );

  printf("fcntl F_SETFD should return 1\n");
  status = fcntl( fd, F_GETFD, 1 );
  rtems_test_assert( status == 1 );

#if 0
  printf("fcntl F_DUPFD should return 0\n");
  status = fcntl( fd, F_DUPFD, 0 );
  rtems_test_assert ( status == 0 );
#else
  printf("fcntl F_DUPFD should return 0 -- skip until implemented\n");
#endif

  printf("fcntl F_GETFL returns current flags\n");
  status = fcntl( fd, F_GETFL, 1 );
  printf("fcntl F_GETFL returned 0x%x\n", status );
  rtems_test_assert( status != -1 );

  printf("fcntl F_SETFL to add O_APPEND and O_NONBLOCK\n");
  status = fcntl( fd, F_SETFL, O_APPEND|O_NONBLOCK );
  rtems_test_assert ( status != -1 );

  printf("fcntl F_GETFL return current flags to see changes\n");
  status = fcntl( fd, F_GETFL, 1 );
  printf("fcntl F_GETFL returned 0x%x\n", status );
  rtems_test_assert( status != -1 );

  printf("fcntl F_GETLK should return -1\n");
  status = fcntl( fd, F_GETLK, 1 );
  rtems_test_assert ( status == -1 );

  printf("fcntl F_SETLK should return -1\n");
  status = fcntl( fd, F_SETLK, 1 );
  rtems_test_assert ( status == -1 );

  printf("fcntl F_SETLKW should return -1\n");
  status = fcntl( fd, F_SETLKW, 1 );
  rtems_test_assert ( status == -1 );

  printf("fcntl F_SETOWN should return -1\n");
  status = fcntl( fd, F_SETOWN, 1 );
  rtems_test_assert ( status == -1 );

  printf("fcntl F_GETOWN should return -1\n");
  status = fcntl( fd, F_GETOWN, 1 );
  rtems_test_assert ( status == -1 );

  printf("fcntl invalid argument should return -1\n");
  status = fcntl( fd, 0xb, 1 );
  printf("Status %d\n",status);
  rtems_test_assert( status == -1 );

  printf("opendir and readdir /b/myfile\n");
  directory_not = opendir ("/b/my_file");
  d_not = readdir(directory_not);

  printf("opendir and readdir\n");
  directory_not = opendir ("/a");
  d_not = readdir (directory_not);

  printf("chdir to /b/myfile\n");
  status = chdir ("/b/my_file");
  rtems_test_assert (status == -1);

  printf( "\nPerforming stat of directory /\n");
  status = stat( "/", &s );
  printf("status for stat : %d, size of directory: %" PRIdoff_t "\n\n", status, s.st_size);

  puts( "\nOpen and print directory /" );
  directory = opendir("/");
  rtems_test_assert( directory );
  printdir(directory);

  printf("\nmkdir /d/my_dir\n");
  status = mkdir( "/d/my_dir", 0x1c0 );
  printf("Open /d/my_dir\n");
  directory_not = opendir( "/d/my_dir" );
  rtems_test_assert( directory_not );

  printf( "remove /d/my_dir.\n" );
  status = rmdir( "/d/my_dir" );
  rtems_test_assert( status == 0 );

  printf( "close /d/my_dir.\n" );
  closedir( directory_not );

  printf( "\nOpening directory /c\n" );
  directory2 = opendir("/c");

  rtems_test_assert( directory2 );

  printdir(directory2);
  status = closedir( directory2 );

  printf( "\nOpening directory /c/y\n" );
  directory3 = opendir("/c/y");
  rtems_test_assert( directory3 );
  printdir(directory3);
  status = closedir( directory3 );

  printf( "\nLSEEK to the start of the open directory\n" );
  lseek( directory->dd_fd, 0, SEEK_SET );
  printdir(directory);

  lseek( directory->dd_fd, 0, SEEK_CUR );

  lseek( directory->dd_fd, 0, SEEK_END );

  lseek( directory->dd_fd, 0, -99 );

  printf( "\nRewinding directory\n" );
  rewinddir( directory );
  printdir(directory);

#if 0
  /* Newlib's implementation does not check for NULL */
  printf( "Send rewinddir a NULL pointer\n");
  rewinddir( NULL );
#endif

  printf( "\nSeek directory\n" );
  printf( "telldir() should report only sizeof(struct dirent) increments \n" );
  printf( "in position. Sizeof(struct dirent): %ld\n",
                          (unsigned long) sizeof(struct dirent) );
  rewinddir( directory );
  for( off=0 ; off<=200 ; off=off + sizeof(struct dirent) / 4 ) {
    seekdir( directory, off );
    printf(
       "seeked to %2d -- currently at %2d\n",
       (int)off,
       (int)telldir(directory)
    );
  }

  printf( "Send seekdir a NULL pointer\n");
  seekdir( NULL, off );

  printf( "\nClosing directory\n" );
  status = closedir( directory );

  printf( "\nSCANDIR TEST\n");
  printf( "\nselection rule 1\n");
  printf( "scanning for any entry under directory /c\n\n");
  status = scandir(
     "/c",
     &namelist,
     select1,
     NULL
  );
  printf("\nscandir status: %d\n", status );
  for ( i=0; i<status; i++)
  {
     printf("Selected Node Name: %s\n", namelist[i]->d_name );
  }

  printf( "\nselection rule 2\n");
  printf( "scanning for any entry under directory /c whose name = y\n\n");
  status = scandir(
     "/c",
     &namelist,
     select2,
     NULL
  );
  printf("\nscandir status: %d\n", status );
  for ( i=0; i<status; i++)
  {
     printf("Selected Node Name: %s\n", namelist[i]->d_name );
  }

  printf( "\nSCANDIR with sorting\n" );
  printf( "\nselection rule 1\n");
  printf( "scanning for any entry under directory /c\n");
  printf( "sort in ascending order\n\n");
  status = scandir(
     "/c",
     &namelist,
     select1,
     compare_ascending
  );
  printf("\nscandir status: %d\n", status );
  for ( i=0; i<status; i++)
  {
     printf("Selected and Sorted Node Name: %s\n", namelist[i]->d_name );
  }


  printf( "\nSCANDIR with sorting\n" );
  printf( "\nselection rule 1\n");
  printf( "scanning for any entry under directory /c\n");
  printf( "sort in descending order\n\n");
  status = scandir(
     "/c",
     &namelist,
     select1,
     compare_descending
  );
  printf("scandir status: %d\n", status );
  for ( i=0; i<status; i++)
  {
     printf("Selected and Sorted Node Name: %s\n", namelist[i]->d_name );
  }

  test_across_mount();
  printf( "\n\n*** END OF READDIR TEST ***\n" );
  rtems_test_exit(0);
}
Esempio n. 12
0
int cgiMain() {

  static char      title[256]        = "";
  static char   subtitle[256]        = "";
         char      sorting[16]       = "desc";
         time_t    now               = time(NULL);
         time_t    start             = time(NULL);
         time_t    expiration        = time(NULL);
         double    available_secs    = 0;
         double    remaining_secs    = 0;
  struct dirent    **certstore_files = NULL;
         int       pagenumber        = 1;
         int       certcounter       = 0;
         int       tempcounter       = 0;
         int       pagecounter       = 0;
         int       dispcounter       = 0;
         int       dispmaxlines      = 0;
         int       certvalidity      = 0;
         div_t     disp_calc;
         div_t     oddline_calc;
         double    percent           = 0;

         cert                        = X509_new();
         certsubject                 = X509_NAME_new();
	 char      **form_data       = NULL;  /* string array for query data */

  /* get the current time */
  now = time(NULL);

/* ------------------------------------------------------------------------- *
 * If we are called without arguments, we display the cert search criteria   *
 * ------------------------------------------------------------------------- */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    int_error("Error: Could not retrieve CGI form data.");
  if(form_data[0] == NULL) {

    start_tm = *gmtime(&now);

    snprintf(title, sizeof(title), "Search existing Certificates");
    pagehead(title);
    fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"get\">");
    fprintf(cgiOut, "<table>");

    /* Search for Subject String */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Name</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"dn\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Distinguished Name Field:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<select name=\"field\">");
    fprintf(cgiOut, "<option value=\"countryName\">Country</option>");
    fprintf(cgiOut, "<option value=\"stateOrProvinceName\">State</option>");
    fprintf(cgiOut, "<option value=\"localityName\">Location</option>");
    fprintf(cgiOut, "<option value=\"organizationName\">Organisation</option>");
    fprintf(cgiOut, "<option value=\"organizationalUnitName\">Department</option>");
    fprintf(cgiOut, "<option value=\"emailAddress\">E-Mail Addr</option>");
    fprintf(cgiOut, "<option selected=\"selected\" value=\"commonName\">Common Name</option>");
    fprintf(cgiOut, "<option value=\"surname\">Surname</option>");
    fprintf(cgiOut, "<option value=\"givenName\">Given Name</option>");
    fprintf(cgiOut, "</select>");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Search String<br />[20 chars max]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"15\" name=\"dnvalue\" value=\"changeme.com\" />");
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that have the given string in the selected DN field. ");
    fprintf(cgiOut, "The search is case sensitive, so results for country=us can be different from country=US and country=Us.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Expiration Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Expiration Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"exp\" name=\"search\" checked=\"checked\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Expiration Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"exp_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"exp_starttime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[default 90 days]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the future: 86400s/d*90d=7776000s */
    expiration = now + 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"exp_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"exp_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that expire(d) between the selected start and end date. ");
    fprintf(cgiOut, "By default, the search is pre-set to find certificates that expire in the next 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Enabled Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Creation Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"ena\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Enabled Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the past: 86400s/d*90d=7776000s */
    expiration = now - 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"ena_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"ena_starttime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[default now]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"ena_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"ena_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that become valid between the selected start and end date. ");
    fprintf(cgiOut, "By default, the search is pre-set to show certificates created in the past 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Revocation Date */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Revocation Date</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"rev\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Revocation Date is<br />between Start Date:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    /* set second time 3 months (90 days) into the past: 86400s/d*90d=7776000s */
    expiration = now - 7776000;
    expiration_tm = *gmtime(&expiration);
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"rev_startdate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &expiration_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"rev_starttime\" value=\"%s\"/>", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Date<br />[now]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    strftime(membio_buf, sizeof(membio_buf), "%d.%m.%Y", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"9\" name=\"rev_enddate\" value=\"%s\" /> ", membio_buf);
    strftime(membio_buf, sizeof(membio_buf), "%H:%M", &start_tm);
    fprintf(cgiOut, "<input type=\"text\" size=\"3\" name=\"rev_endtime\" value=\"%s\" />", membio_buf);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates that have been revoked between the selected start and end date. ");
    fprintf(cgiOut, " By default, the search is pre-set to show certificates revoked in the past 3 months.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    /* Search for Serial Number */
    fprintf(cgiOut, "<tr><th colspan=\"5\">Search by Serial Number</th></tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"cnt\" rowspan=\"2\">\n");
    fprintf(cgiOut, "<input type=\"radio\" value=\"ser\" name=\"search\" />");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "Serial Number is<br />between Start Serial:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"14\" name=\"startserial\" ");
    fprintf(cgiOut, "value=\"%s\" style=\"text-align:right;\" />", startserstr);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"type\">\n");
    fprintf(cgiOut, "and End Serial<br />[max 10e11]:");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "<td class=\"center\">\n");
    fprintf(cgiOut, "<input type=\"text\" size=\"14\" name=\"endserial\" ");
    fprintf(cgiOut, "value=\"%s\" style=\"text-align:right;\" />", endserstr);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"desc\" colspan=\"4\">\n");
    fprintf(cgiOut, "Search for certificates whose serial number is between the given ");
    fprintf(cgiOut, "start and end serial number in decimal format. To find a particular certificate, set start and end serial to be equal.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");

    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th colspan=\"5\">");
    fprintf(cgiOut, "<input type=\"submit\" value=\"Search Certificates\" />");
    fprintf(cgiOut, "</th>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
    fprintf(cgiOut, "</form>\n");
    pagefoot();

  }
  else {
  
  /* ------------------------------------------------------------------- *
   * check if we got the CGI form data                                   *
   * --------------------------------------------------------------------*/
    if ( cgiFormString("search", search, sizeof(search))
                                                     != cgiFormSuccess )
      int_error("Error retrieving CGI form search type.");
    else {
      if (strcmp(search, "dn") == 0) {
        if ( cgiFormString("field", field, sizeof(field))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form DN search field information.");

        if ( cgiFormString("dnvalue", dnvalue, sizeof(dnvalue))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form DN search dnvalue information.");
        snprintf(title, sizeof(title), "Search Certs by Subject");
        snprintf(subtitle, sizeof(subtitle), "Certificates with DN %s=%s", field, dnvalue);
      }
      else if (strcmp(search, "exp") == 0) {
        if ( cgiFormString("exp_startdate", exp_startdate, sizeof(exp_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration start date.");

        if ( cgiFormString("exp_starttime", exp_starttime, sizeof(exp_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration start time.");

        if ( cgiFormString("exp_enddate", exp_enddate, sizeof(exp_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration end date.");

        if ( cgiFormString("exp_endtime", exp_endtime, sizeof(exp_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form expiration end time.");

        strncat(exp_startstr, exp_startdate, sizeof(exp_startstr)-1);
        strncat(exp_startstr, " ", 1); /* add a space between date and time */
        strncat(exp_startstr, exp_starttime, sizeof(exp_startstr)-strlen(exp_startstr)-1);
        strncat(exp_endstr, exp_enddate, sizeof(exp_endstr)-1);
        strncat(exp_endstr, " ", 1); /* add a space between date and time */
        strncat(exp_endstr, exp_endtime, sizeof(exp_endstr)-strlen(exp_endstr)-1);
        snprintf(title, sizeof(title), "Search Certs by Expiration");
        snprintf(subtitle, sizeof(subtitle), "Certificates with expiration between %s and %s", exp_startstr, exp_endstr);
      }
      else if (strcmp(search, "ena") == 0) {
        if ( cgiFormString("ena_startdate", ena_startdate, sizeof(ena_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start date.");

        if ( cgiFormString("ena_starttime", ena_starttime, sizeof(ena_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start time.");

        if ( cgiFormString("ena_enddate", ena_enddate, sizeof(ena_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end date.");

        if ( cgiFormString("ena_endtime", ena_endtime, sizeof(ena_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end time.");

        strncat(ena_startstr, ena_startdate, sizeof(ena_startstr)-1);
        strncat(ena_startstr, " ", 1); /* add a space between date and time */
        strncat(ena_startstr, ena_starttime, sizeof(ena_startstr)-strlen(ena_startstr)-1);
        strncat(ena_endstr, ena_enddate, sizeof(ena_endstr)-1);
        strncat(ena_endstr, " ", 1); /* add a space between date and time */
        strncat(ena_endstr, ena_endtime, sizeof(ena_endstr)-strlen(ena_endstr)-1);
        snprintf(title, sizeof(title), "Search Certs by Start Date");
        snprintf(subtitle, sizeof(subtitle), "Certificates with start date between %s and %s", ena_startstr, ena_endstr);
      }
      else if (strcmp(search, "rev") == 0) {
        if ( cgiFormString("rev_startdate", rev_startdate, sizeof(rev_startdate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start date.");

        if ( cgiFormString("rev_starttime", rev_starttime, sizeof(rev_starttime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable start time.");

        if ( cgiFormString("rev_enddate", rev_enddate, sizeof(rev_enddate))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end date.");

        if ( cgiFormString("rev_endtime", rev_endtime, sizeof(rev_endtime))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form enable end time.");

        strncat(rev_startstr, rev_startdate, sizeof(rev_startstr)-1);
        strncat(rev_startstr, " ", 1); /* add a space between date and time */
        strncat(rev_startstr, rev_starttime, sizeof(rev_startstr)-strlen(rev_startstr)-1);
        strncat(rev_endstr, rev_enddate, sizeof(rev_endstr)-1);
        strncat(rev_endstr, " ", 1); /* add a space between date and time */
        strncat(rev_endstr, rev_endtime, sizeof(rev_endstr)-strlen(rev_endstr)-1);
        snprintf(title, sizeof(title), "Search Revoked Certificates");
        snprintf(subtitle, sizeof(subtitle), "Certificates revoked between %s and %s", rev_startstr, rev_endstr);
      }
      else if (strcmp(search, "ser") == 0) {
        if ( cgiFormString("startserial", startserstr, sizeof(startserstr))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form start serial value.");

        if ( cgiFormString("endserial", endserstr, sizeof(endserstr))
                                                     != cgiFormSuccess )
        int_error("Error retrieving CGI form end serial value.");
        snprintf(title, sizeof(title), "Search Certs by Serial Number");
        snprintf(subtitle, sizeof(subtitle), "Certificates with serial number between %s and %s", startserstr, endserstr);
      }
      else int_error("Error CGI form retrieving a valid search type.");
    }

/* -------------------------------------------------------------------------- *
 * We got CGI arguments, first we get a list of .pem files from the cert dir  *
 * ---------------------------------------------------------------------------*/
  certcounter = scandir(CACERTSTORE, &certstore_files, file_select, hexsort);
  // It can happen that our search does not return any certs. This is not an error.
  //if(certcounter<=0) int_error("Error: No certificate files found.");

/* -------------------------------------------------------------------------- *
 * calculate how many pages we get with MAXCERTDISPLAY                         *
 * ---------------------------------------------------------------------------*/

  if(certcounter<=MAXCERTDISPLAY) pagecounter = 1;
  else {
    disp_calc = div(certcounter, MAXCERTDISPLAY);
    /* if the count of certs divided by MAXCERTDISPLAY has no remainder */
    if(disp_calc.rem == 0) pagecounter = disp_calc.quot;
    /* with a remainder, we must prepare an extra page for the rest */
    else pagecounter = disp_calc.quot +1;
  }

/* -------------------------------------------------------------------------- *
 * Check if we have been subsequently called with a pagenumber & sort request *
 * ---------------------------------------------------------------------------*/

  if(cgiFormInteger("page", &pagenumber, 1) == cgiFormSuccess)
    if(pagenumber > pagecounter || pagenumber <=0)
      int_error("Error: Page does not exist.");

  if(cgiFormString("sort", sorting, sizeof(sorting)) != cgiFormSuccess)
      strncpy(sorting, "desc", sizeof(sorting));

/* -------------------------------------------------------------------------- *
 * now we know how many certs we have in total and we can build the page(s).  *
 * For every MAXCERTDISPLAY certs we start a new page and cycle through by    *
 * calling ourself with the requested certs in range.                         *
 * ---------------------------------------------------------------------------*/

  if(strcmp(sorting, "asc") == 0) {

    if(certcounter <= MAXCERTDISPLAY) {
       dispmaxlines = certcounter;
       tempcounter = 0;
    }
    else
      if(pagenumber == pagecounter &&
             ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) {

        tempcounter = (pagecounter * MAXCERTDISPLAY) - MAXCERTDISPLAY;
        dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
      }
      else {

        tempcounter = (pagenumber * MAXCERTDISPLAY) - MAXCERTDISPLAY;
        dispmaxlines = MAXCERTDISPLAY;
      }
  }

  if(strcmp(sorting, "desc") == 0) {

    if(certcounter <= MAXCERTDISPLAY) {
       dispmaxlines = certcounter;
       tempcounter = certcounter;
    }
    else
      if(pagenumber == pagecounter &&
             ( pagecounter * MAXCERTDISPLAY) - certcounter != 0) {

        tempcounter = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
        dispmaxlines = certcounter - ((pagecounter-1) * MAXCERTDISPLAY);
      }
      else {

       tempcounter = certcounter - (pagenumber*MAXCERTDISPLAY) + MAXCERTDISPLAY;
       dispmaxlines = MAXCERTDISPLAY;
      }
  }

/* -------------------------------------------------------------------------- *
 * start the html output                                                      *
 * ---------------------------------------------------------------------------*/

  pagehead(title);

  //debugging only:
  //printf("Number of certs: %d\n", certcounter);
  //printf("Num tempcounter: %d\n", tempcounter);
  //printf("Number of pages: %d\n", pagecounter);
  //printf("Div Quotient: %d\n", disp_calc.quot);
  //printf("Div Remainder: %d\n", disp_calc.rem);
  //fprintf(cgiOut, "</BODY></HTML>\n");
  //exit(0);

/* -------------------------------------------------------------------------- *
 * start the form output                                                      *
 * ---------------------------------------------------------------------------*/

   fprintf(cgiOut, "<h3>%s</h3>\n", subtitle);
   fprintf(cgiOut, "<p></p>\n");
   fprintf(cgiOut, "<table>\n");
   fprintf(cgiOut, "<tr>\n");
   fprintf(cgiOut, "<th width=\"20\">");
   fprintf(cgiOut, "#");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"495\">");
   fprintf(cgiOut, "Certificate Subject Information");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"60\" colspan=\"2\">");
   fprintf(cgiOut, "Expires");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "<th width=\"65\">");
   fprintf(cgiOut, "Action");
   fprintf(cgiOut, "</th>\n");
   fprintf(cgiOut, "</tr>\n");

  /* if our search did not return any certs, we display a note instead */
  if(certcounter<=0) {
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"even\" colspan=\"5\">");
    fprintf(cgiOut, "Could not find any certificates for the given search criteria.");
    fprintf(cgiOut, "</td>\n");
    fprintf(cgiOut, "</tr>\n");
  }

  for(dispcounter=0; dispcounter < dispmaxlines; dispcounter++) {

    /* zero certificate values and flags */
    certvalidity = 0;
    percent = 0;
    available_secs = 0;
    remaining_secs = 0;
    cert = X509_new();
    certsubject = X509_NAME_new();

    if(strcmp(sorting, "desc") == 0) tempcounter--;

    snprintf(certfilestr, sizeof(certfilestr), "%s/%s",
                           CACERTSTORE, certstore_files[tempcounter]->d_name);

    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th rowspan=\"2\">");
    fprintf(cgiOut, "%d", tempcounter+1);
    fprintf(cgiOut, "</th>\n");

    oddline_calc = div(tempcounter+1, 2);
    if(oddline_calc.rem)
      fprintf(cgiOut, "<td rowspan=\"2\" class=\"odd\">");
    else
      fprintf(cgiOut, "<td rowspan=\"2\" class=\"even\">");

    if ( (certfile = fopen(certfilestr, "r")) != NULL) {
      PEM_read_X509(certfile, &cert, NULL, NULL);

      /* ---------------------------------------------------------- *
       * Display the subject data. Use the UTF-8 flag to show       *
       * Japanese Kanji. This also needs the separator flag to work *
       * ---------------------------------------------------------- */
      certsubject = X509_get_subject_name(cert);
      X509_NAME_print_ex_fp(cgiOut, certsubject, 0,
         ASN1_STRFLGS_UTF8_CONVERT|XN_FLAG_SEP_CPLUS_SPC);

      /* store certificate start date for later eval */
      start_date = X509_get_notBefore(cert);

      /* store certificate expiration date for later eval */
      expiration_date = X509_get_notAfter(cert);

      /* check the start and end dates in the cert */
      if (X509_cmp_current_time (X509_get_notBefore (cert)) >= 0)
        /* flag the certificate as not valid yet */
        certvalidity = 0;
      else
      if (X509_cmp_current_time (X509_get_notAfter (cert)) <= 0)
        /* flag the certificate as expired */
        certvalidity = 0;
      else 
        /* flag the certificate is still valid */
        certvalidity = 1;

      fclose(certfile);
    }
    else 
       fprintf(cgiOut, "Error: Can't open certificate file %s for reading.",
                                                                 certfilestr);
    fprintf(cgiOut, "</td>\n");

    if(certvalidity == 0) {

      /* expiration bar display column */
      fprintf(cgiOut, "<th rowspan=\"2\">\n");
      fprintf(cgiOut, "<table class=\"led\">\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "</table>\n");
      fprintf(cgiOut, "</th>\n");

      /* remaining days before expiration column */
      fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">");
      fprintf(cgiOut, "Inval.<br />/Expd");
      fprintf(cgiOut, "</th>\n");
    }

    if(certvalidity == 1) {

      /* ------ START get the certificate lifetime in seconds ------ */
      /* copy the start date into a string */
      membio = BIO_new(BIO_s_mem());
      ASN1_TIME_print(membio, start_date);
      BIO_gets(membio, membio_buf, sizeof(membio_buf));
      BIO_free(membio);

      /* parse the start date string into a time struct */
      memset (&start_tm, '\0', sizeof(start_tm));
      strptime(membio_buf, "%h %d %T %Y %z", &start_tm);
      start = mktime(&start_tm);

      /* ------ START get the certificate remaining time in seconds ------ */
      /* copy the expiration date into a string */
      membio = BIO_new(BIO_s_mem());
      ASN1_TIME_print(membio, expiration_date);
      BIO_gets(membio, membio_buf, sizeof(membio_buf));
      BIO_free(membio);
  
      /* parse the expiration date string into a time struct */
      memset (&expiration_tm, '\0', sizeof(expiration_tm));
      strptime(membio_buf, "%h %d %T %Y %z", &expiration_tm);
  
      /* get the current time */
      expiration = mktime(&expiration_tm);
  
      /* get the time difference between expiration time and current time */
      remaining_secs = difftime(expiration, now);
      /* ------ END get the certificate remaining time in seconds ------ */

      /* get the time difference between start and expiration time */
      available_secs = difftime(expiration, start);
      /* ------ END get the certificate lifetime in seconds ------ */
  
      /* ------ START calculate percentage of lifetime left ------ */
      /* remaining_secs *100                                       */
      /* ------------------- = X, rounded down with floor()        */
      /* available_secs                                            */
      percent = floor((remaining_secs*100)/available_secs);
      /* ------ END calculate percentage of lifetime left   ------ */
  
      /* expiration bar display column */
      fprintf(cgiOut, "<th rowspan=\"2\">");
      fprintf(cgiOut, "<table class=\"led\">\n");
      if (percent >= 90) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#00FF00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 80) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#00FF33></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 70) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#99FF33></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 60) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FFFF00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 50) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FFCC00></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 40) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF9900></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 30) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF6600></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 20) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF3300></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      if (percent >= 10) fprintf(cgiOut, "  <tr><td class=\"led\" bgcolor=#FF0000></td></tr>\n");
      else fprintf(cgiOut, "  <tr><td class=\"led-off\"></td></tr>\n");
      fprintf(cgiOut, "</table>\n");
      fprintf(cgiOut, "</th>");
  
      /* remaining days before expiration column */
      //fprintf(cgiOut, membio_buf);
      if (percent < 10) fprintf(cgiOut, "<th class=\"exnok\" rowspan=\"2\">\n");
      else fprintf(cgiOut, "<th class=\"exok\" rowspan=\"2\">\n");
      if(floor(remaining_secs/63072000) > 0) fprintf(cgiOut, "%.f<br />years", remaining_secs/31536000);
      else if(floor(remaining_secs/86400) > 0 ) fprintf(cgiOut, "%.f<br />days", remaining_secs/86400);
      else if(floor(remaining_secs/3600) > 0 ) fprintf(cgiOut, "%.f<br />hours", remaining_secs/3600);
      else if(floor(remaining_secs/60) > 0 ) fprintf(cgiOut, "%.f<br />mins", remaining_secs/60);
      else fprintf(cgiOut, "%.f<br />secs", remaining_secs);
      fprintf(cgiOut, "</th>\n");
    }

    /* action column */
    fprintf(cgiOut, "<th>");
    fprintf(cgiOut, "<form action=\"getcert.cgi\" method=\"post\">\n");
    fprintf(cgiOut, "<input type=\"hidden\" name=\"cfilename\" ");
    fprintf(cgiOut, "value=\"%s\" />\n", certstore_files[tempcounter]->d_name);
    fprintf(cgiOut, "<input type=\"hidden\" name=\"format\" value=\"pem\" />\n");
    fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Detail\" />\n");
    fprintf(cgiOut, "</form>\n");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th>");
    fprintf(cgiOut, "<form action=\"getcert.cgi\" method=\"post\">\n");
    fprintf(cgiOut, "<input type=\"hidden\" name=\"cfilename\" ");
    fprintf(cgiOut, "value=\"%s\" />\n", certstore_files[tempcounter]->d_name);
    fprintf(cgiOut, "<input type=\"hidden\" name=\"format\" value=\"text\" />\n");
    fprintf(cgiOut, "<input class=\"getcert\" type=\"submit\" value=\"Renew\" />\n");
    fprintf(cgiOut, "</form>");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");

    if(strcmp(sorting, "asc") == 0) tempcounter++;
  }


  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th colspan=\"5\">");
  fprintf(cgiOut, "Total # of certs: %d | ", certcounter);
  fprintf(cgiOut, "Page %d of %d", pagenumber, pagecounter);
  fprintf(cgiOut, "</th>");
  fprintf(cgiOut, "</tr>");
  fprintf(cgiOut, "</table>\n");

  fprintf(cgiOut, "<p></p>\n");

  fprintf(cgiOut, "<table>\n");

  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th>");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" ");
  fprintf(cgiOut, "value=\"desc\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" name=\"sort\"");
  fprintf(cgiOut, " value=\"Latest Certs first\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  fprintf(cgiOut, "<th>");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"sort\" ");
  fprintf(cgiOut, "value=\"asc\">\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" name=\"sort\"");
  fprintf(cgiOut, " value=\"Oldest Certs first\">");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // filler 1
  fprintf(cgiOut, "<th width=\"15\">");
  fprintf(cgiOut, "&nbsp;");
  fprintf(cgiOut, "</th>\n");

  // goto page 1
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&lt;&lt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page before
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  tempcounter = 0;
  if(pagenumber > 1) tempcounter = pagenumber - 1;
  else tempcounter = 1;
  fprintf(cgiOut, "%d", tempcounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&lt; 1\">");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page after
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  tempcounter = 0;
  if(pagecounter > pagenumber) tempcounter = pagenumber + 1;
  else tempcounter = pagecounter;
  fprintf(cgiOut, "%d", tempcounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"1 &gt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto last page
  fprintf(cgiOut, "<th width=\"5\">");
  fprintf(cgiOut, "<form action=\"certsearch.cgi\" method=\"post\">");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"page\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input type=\"submit\" value=\"&gt;&gt;\" />");
  fprintf(cgiOut, "</form>");
  fprintf(cgiOut, "</th>\n");

  // goto page number
  fprintf(cgiOut, "<th width=\"120\">\n");
  fprintf(cgiOut, "<form class=\"setpage\" action=\"certsearch.cgi\" method=\"post\">\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"certcounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", certcounter);
  fprintf(cgiOut, "\" />\n");
  fprintf(cgiOut, "<input type=\"hidden\" name=\"pagecounter\" ");
  fprintf(cgiOut, "value=\"");
  fprintf(cgiOut, "%d", pagecounter);
  fprintf(cgiOut, "\" />\n");
  resubmit();
  fprintf(cgiOut, "<input class=\"goto\" type=\"submit\" value=\"Goto\" />\n");
  fprintf(cgiOut, "&nbsp; &nbsp;");
  fprintf(cgiOut, "<input class=\"page\" type=\"text\" name=\"page\" ");
  fprintf(cgiOut, "value=\"%d\" />\n", pagecounter);
  fprintf(cgiOut, "</form>\n");
  fprintf(cgiOut, "</th>\n");

  fprintf(cgiOut, "</tr>\n");
  fprintf(cgiOut, "</table>\n");

/* ---------------------------------------------------------------------------*
 * end the html output                                                        *
 * ---------------------------------------------------------------------------*/

  pagefoot();
}
  return(0);
}
Esempio n. 13
0
int destroy_instance_backing (ncInstance * instance, int do_destroy_files)
{
    int ret = OK;
    int total_prereqs = 0;
    char path [MAX_PATH];
    virtualMachine * vm = &(instance->params);
    
    // find and detach iSCSI targets, if any
    for (int i=0; i<EUCA_MAX_VBRS && i<vm->virtualBootRecordLen; i++) {
        virtualBootRecord * vbr = &(vm->virtualBootRecord[i]);
        if (vbr->locationType==NC_LOCATION_IQN) {
            if (disconnect_iscsi_target (vbr->resourceLocation)) {
                logprintfl(EUCAERROR, "[%s] error: failed to disconnect iSCSI target attached to %s\n", instance->instanceId, vbr->backingPath);
            } 
        }
    }

    // see if instance directory is there (sometimes startup fails before it is created)
    set_path (path, sizeof (path), instance, NULL);
    if (check_path (path))
        return ret;

    // to ensure that we are able to delete all blobs, we chown files back to 'eucalyptus'
    // (e.g., libvirt on KVM on Maverick chowns them to libvirt-qemu while
    // VM is running and then chowns them to root after termination)
    set_path (path, sizeof (path), instance, "*");
    if (diskutil_ch (path, EUCALYPTUS_ADMIN, NULL, BACKING_FILE_PERM)) {
        logprintfl (EUCAWARN, "[%s] error: failed to chown files before cleanup\n", instance->instanceId);
    }

    if (do_destroy_files) {
        char work_regex [1024]; // {userId}/{instanceId}/.*
        set_id2 (instance, "/.*", work_regex, sizeof (work_regex));

        if (blobstore_delete_regex (work_bs, work_regex) == -1) {
            logprintfl (EUCAERROR, "[%s] error: failed to remove some artifacts in %s\n", instance->instanceId, path);
        }

        // remove the known leftover files
        unlink (instance->xmlFilePath);
        unlink (instance->libvirtFilePath);
        unlink (instance->consoleFilePath);
        if (strlen (instance->floppyFilePath)) {
            unlink (instance->floppyFilePath);
        }
        set_path (path, sizeof (path), instance, "instance.checkpoint");
        unlink (path);
        for (int i=0; i < EUCA_MAX_VOLUMES; ++i) {
            ncVolume * volume = &instance->volumes[i];
            snprintf (path, sizeof (path), EUCALYPTUS_VOLUME_XML_PATH_FORMAT, instance->instancePath, volume->volumeId);
            unlink (path);
        }
        // bundle instance will leave additional files
        // let's delete every file in the directory
        struct dirent **files;
        int n = scandir(instance->instancePath, &files, 0, alphasort);
        char toDelete[MAX_PATH];
        if (n>0){
            while (n--) {
               struct dirent *entry = files[n];
               if( entry !=NULL && strncmp(entry->d_name, ".",1)!=0 && strncmp(entry->d_name, "..", 2)!=0){
                    snprintf(toDelete, MAX_PATH, "%s/%s", instance->instancePath, entry->d_name);
                    unlink(toDelete);
                    free(entry);
               }
            }
            free(files);
        }
    }
   
    // Finally try to remove the directory.
    // If either the user or our code introduced
    // any new files, this last step will fail.
    set_path (path, sizeof (path), instance, NULL);
    if (rmdir (path) && do_destroy_files) {
        logprintfl (EUCAWARN, "[%s] warning: failed to remove backing directory %s\n", instance->instanceId, path);
    }
    
    return ret;
}
Esempio n. 14
0
void UDirectory::update()
{
	if(exists(path_))
	{
		std::string lastName;
		bool endOfDir = false;
		if(iFileName_ != fileNames_.end())
		{
			//Record the last file name
			lastName = *iFileName_;
		}
		else if(fileNames_.size())
		{
			lastName = *fileNames_.rbegin();
			endOfDir = true;
		}
		fileNames_.clear();
#ifdef WIN32
		WIN32_FIND_DATA fileInformation;
	#ifdef UNICODE
		wchar_t * pathAll = createWCharFromChar((path_+"\\*").c_str());
		HANDLE hFile  = ::FindFirstFile(pathAll, &fileInformation);
		delete [] pathAll;
	#else
		HANDLE hFile  = ::FindFirstFile((path_+"\\*").c_str(), &fileInformation);
	#endif
		if(hFile != INVALID_HANDLE_VALUE)
		{
			do
			{
	#ifdef UNICODE
				char * fileName = createCharFromWChar(fileInformation.cFileName);
				fileNames_.push_back(fileName);
				delete [] fileName;
	#else
				fileNames_.push_back(fileInformation.cFileName);
	#endif
			} while(::FindNextFile(hFile, &fileInformation) == TRUE);
			::FindClose(hFile);
			std::vector<std::string> vFileNames = uListToVector(fileNames_);
			std::sort(vFileNames.begin(), vFileNames.end(), sortCallback);
			fileNames_ = uVectorToList(vFileNames);
		}
#else
		int nameListSize;
		struct dirent ** nameList = 0;
		nameListSize =	scandir(path_.c_str(), &nameList, 0, sortCallback);
		if(nameList && nameListSize>0)
		{
			for (int i=0;i<nameListSize;++i)
			{
				fileNames_.push_back(nameList[i]->d_name);
				free(nameList[i]);
			}
			free(nameList);
		}
#endif

		//filter extensions...
		std::list<std::string>::iterator iter = fileNames_.begin();
		bool valid;
		while(iter!=fileNames_.end())
		{
			valid = false;
			if(extensions_.size() == 0 &&
			   iter->compare(".") != 0 &&
			   iter->compare("..") != 0)
			{
				valid = true;
			}
			for(unsigned int i=0; i<extensions_.size(); ++i)
			{
				if(UFile::getExtension(*iter).compare(extensions_[i]) == 0)
				{
					valid = true;
					break;
				}
			}
			if(!valid)
			{
				iter = fileNames_.erase(iter);
			}
			else
			{
				++iter;
			}
		}
		iFileName_ = fileNames_.begin();
		if(!lastName.empty())
		{
			bool found = false;
			for(std::list<std::string>::iterator iter=fileNames_.begin(); iter!=fileNames_.end(); ++iter)
			{
				if(lastName.compare(*iter) == 0)
				{
					found = true;
					iFileName_ = iter;
					break;
				}
			}
			if(endOfDir && found)
			{
				++iFileName_;
			}
			else if(endOfDir && fileNames_.size())
			{
				iFileName_ = --fileNames_.end();
			}
		}
	}
}
Node::Node(string name) throw (myExceptions){
    int shmid, datagramport = -1, streamport, identifier, count;
    char folder[100];
    struct dirent **files;
    struct data *d;
    myExceptions e;
    
    if ((shmid = shmget(KEY, 200, 0666)) == -1) {
        
        shmid = shmget(KEY, 200, 0666 | IPC_CREAT);
        if ((d = (struct data*)shmat(shmid, 0, 0)) == NULL) {
            perror("attach");
            e.setmsg("Error in shared memory attachment");
            throw e;
        }
        
        d->portlist[0][0] = 10000; d->portlist[0][1] = 1;
        d->portlist[1][0] = 10002; d->portlist[1][1] = 0;
        d->portlist[2][0] = 10004; d->portlist[2][1] = 0;
        d->portlist[3][0] = 10006; d->portlist[3][1] = 0;
        d->portlist[4][0] = 10008; d->portlist[4][1] = 0;
        d->portlist[5][0] = 10010; d->portlist[5][1] = 0;
        d->portlist[6][0] = 10012; d->portlist[6][1] = 0;
        d->portlist[7][0] = 10014; d->portlist[7][1] = 0;
        d->portlist[8][0] = 10016; d->portlist[8][1] = 0;
        d->portlist[9][0] = 10018; d->portlist[9][1] = 0;
        d->port = datagramport = 10000;
        strcpy(d->name, (char*)name.c_str());
    }
    else {
        
        if ((d = (struct data*)shmat(shmid, 0, 0)) == NULL) {
            perror("attach");
            e.setmsg("Error in shared memory attachment");
            throw e;
        }
        for (int i = 0; i < 10; ++i) {
            if (d->portlist[i][1] == 0) {
                datagramport = d->portlist[i][0];
                d->portlist[i][1] = 1;
                break;
            }
        }
    }
    
    streamport = datagramport + 1;
    identifier = dohash(datagramport);
    enode = address(dohash(d->port), d->port, d->name);
    node = address(identifier, datagramport, name);
    datagram = Connect(DATAGRAM, datagramport);
    stream = Connect(STREAM, streamport);
    
    sprintf(folder, "/Users/Sabyasachee/%d", datagramport);
    strcat(folder, "shared");
    if (access(folder, F_OK) != 0) {
        if (mkdir(folder, 0777) == -1) {
            perror("mkdir");
            e.setmsg("Error in creating directory");
            throw e;
        }
    }
    
    count = scandir(folder, &files, file_select, alphasort);
    
    for (int i = 0; i < count; ++i) {
        filelist.push_back(files[i]->d_name);
    }
    state = NEW;
    shmdt(d);
    
}
Esempio n. 16
0
/**
 * Return number of log files in a dir and the name of the oldest file.
 * @param indata, see gnolfh_in_t
 * @param outdata, char *oldest_file
 * @param max_outsize, Max size for oldest_file string
 * 
 * @return int, number of logfiles or -1 if error
 */
int get_number_of_log_files_hdl(void *indata, void *outdata, size_t max_outsize)
{
	struct dirent **namelist;
	int n, old_date = -1, old_time = -1, old_ind = -1, files, i, failed = 0;
	char path[PATH_MAX];
	gnolfh_in_t *params_in;
	char *oldest_file;
	int rc = 0;
	
	TRACE_ENTER();
	
	params_in = (gnolfh_in_t *) indata;
	oldest_file = (char *) outdata;
	
	/* Initialize the filter */
	n = snprintf(file_prefix, SA_MAX_NAME_LENGTH, "%s", params_in->file_name);
	if (n >= SA_MAX_NAME_LENGTH) {
		rc = -1;
		LOG_WA("file_prefix > SA_MAX_NAME_LENGTH");
		goto done_exit;
	}

	n = snprintf(path, PATH_MAX, "%s/%s",
			params_in->logsv_root_dir, params_in->pathName);
	if (n >= PATH_MAX) {
		LOG_WA("path > PATH_MAX");
		rc = -1;
		goto done_exit;
	}

	files = n = scandir(path, &namelist, filter_func, alphasort);
	if (n == -1 && errno == ENOENT) {
		rc = 0;
		goto done_exit;
	}

	if (n < 0) {
		LOG_WA("scandir:%s - %s", strerror(errno), path);
		rc = -1;
		goto done_exit;
	}
	
	if (n == 0) {
		rc = files;
		goto done_exit;
	}

	while (n--) {
		TRACE_3("%s", namelist[n]->d_name);
		if (check_oldest(namelist[n]->d_name, params_in->file_name,
				 strlen(params_in->file_name), &old_date, &old_time)) {
			old_ind = n;
		} else {
			failed++;	/* wrong format */
		}
	}
	if (old_ind != -1) {
		TRACE_1("oldest: %s", namelist[old_ind]->d_name);
		n = snprintf(oldest_file, max_outsize, "%s/%s",
				path, namelist[old_ind]->d_name);
		if (n >= max_outsize) {
			LOG_WA("oldest_file > max_outsize");
			rc = -1;
			goto done_free;
		} else {
			rc = (files - failed);
		}
	} else {
		TRACE("Only file/files with wrong format found");
	}

done_free:
	/* Free scandir allocated memory */
	for (i = 0; i < files; i++)
		free(namelist[i]);
	free(namelist);

done_exit:	
	TRACE_LEAVE();
	return rc;
}
Esempio n. 17
0
/*----------------------------------------------------------------------------------------------------------------------*/
void DisplayFiles()
{
GtkWidget *HBox,*But,*Label;
struct dirent **NameList;
gchar LStr[LONG_TEXT_FIELD+5],DStr[LONG_TEXT_FIELD+8],FullPath[NAME_MAX+255+5];
struct stat StatBuf;
gint i,N,NRow,Row,Col;
GList *Node;

if (FileX->N)                                                                 //Get rid of the existing table elements
   {
   Node=g_list_last(GTK_TABLE(FileX->Table)->children);      //Glist is in reverse order! So this is the first element
   for (i=0;i<FileX->N;++i) { gtk_widget_destroy(((GtkTableChild *)Node->data)->widget); Node=g_list_previous(Node); }
   }

N=scandir(FileX->Path,&NameList,NULL,alphasort);
for (i=0,FileX->N=0;i<N;++i)                                                    //First collect the subdirectory names
    { 
    if (FileX->N==MAX_DIR_ENTRIES) continue;                        //Terminate the list if there are too many entries
    if (NameList[i]->d_name[0]=='.') continue;                                              //Avoid hidden directories
    sprintf(FullPath,"%s%c%s",FileX->Path,'/',NameList[i]->d_name);
    stat(FullPath,&StatBuf);
    if (S_ISDIR(StatBuf.st_mode)) { strcpy(FileX->Names[FileX->N],NameList[i]->d_name); ++FileX->N; }
    }
for (i=0,FileX->Files=0;i<N;++i)                                    //Now collect files names that match the file type
    { 
    if (FileX->N==MAX_DIR_ENTRIES) continue;                        //Terminate the list if there are too many entries
    if (NameList[i]->d_name[0]=='.') continue;                                                    //Avoid hidden files
    sprintf(FullPath,"%s%c%s",FileX->Path,'/',NameList[i]->d_name);
    stat(FullPath,&StatBuf);
    if ( S_ISREG(StatBuf.st_mode) &&  FileFilter(NameList[i]->d_name,FileX->Mask) ) 
         { strcpy(FileX->Names[FileX->N],NameList[i]->d_name); ++FileX->N; ++FileX->Files; }
    }

NRow=FileX->N/3+((FileX->N%3)>0);
gtk_table_resize(GTK_TABLE(FileX->Table),NRow,3);
for (Row=0;Row<NRow;++Row) for (Col=0;Col<3;++Col)                   //Populate the table to display folders and files
   {
   i=3*Row+Col; if (i>=FileX->N) continue;
   But=gtk_button_new(); gtk_widget_set_usize(GTK_WIDGET(But),152,0);
   gtk_table_attach(GTK_TABLE(FileX->Table),But,Col,Col+1,Row,Row+1,GTK_FILL,GTK_SHRINK,0,0);
   gtk_signal_connect(GTK_OBJECT(But),"button_press_event",GTK_SIGNAL_FUNC(FSelect),GINT_TO_POINTER(i));
   HBox=gtk_hbox_new(FALSE,0); gtk_container_add(GTK_CONTAINER(But),HBox);
   sprintf(FullPath,"%s%c%s",FileX->Path,'/',FileX->Names[i]);
   stat(FullPath,&StatBuf);
   if (S_ISDIR(StatBuf.st_mode))                                                                   //It is a directory
      {
      SetStyleRecursively(But,FolderStyle);
      AbbreviateFileName(LStr,FileX->Names[i],20); sprintf(DStr,"[%s]",LStr);
      Label=gtk_label_new(DStr); SetStyleRecursively(Label,FolderStyle);
      gtk_box_pack_start(GTK_BOX(HBox),Label,FALSE,FALSE,3);
      }
   else                                                                            //It is a file of matching file type 
      {
      SetStyleRecursively(But,FileStyle);
      AbbreviateFileName(LStr,FileX->Names[i],20);
      Label=gtk_label_new(LStr); SetStyleRecursively(Label,FileStyle);
      gtk_box_pack_start(GTK_BOX(HBox),Label,FALSE,FALSE,0);
      }
   }
if (N>-1) free(NameList);
gtk_widget_show_all(FileX->Table);
}
Esempio n. 18
0
File: fs.c Progetto: Denysslav/node
static int uv__fs_readdir_filter(struct dirent* dent) {
#else
static int uv__fs_readdir_filter(const struct dirent* dent) {
#endif
  return strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0;
}


/* This should have been called uv__fs_scandir(). */
static ssize_t uv__fs_readdir(uv_fs_t* req) {
  struct dirent **dents;
  int saved_errno;
  size_t off;
  size_t len;
  char *buf;
  int i;
  int n;

  n = scandir(req->path, &dents, uv__fs_readdir_filter, alphasort);

  if (n == -1 || n == 0)
    return n;

  len = 0;

  for (i = 0; i < n; i++)
    len += strlen(dents[i]->d_name) + 1;

  buf = malloc(len);

  if (buf == NULL) {
    errno = ENOMEM;
    n = -1;
    goto out;
  }

  off = 0;

  for (i = 0; i < n; i++) {
    len = strlen(dents[i]->d_name) + 1;
    memcpy(buf + off, dents[i]->d_name, len);
    off += len;
  }

  req->ptr = buf;

out:
  saved_errno = errno;
  {
    for (i = 0; i < n; i++)
      free(dents[i]);
    free(dents);
  }
  errno = saved_errno;

  return n;
}


static ssize_t uv__fs_readlink(uv_fs_t* req) {
  ssize_t len;
  char* buf;

  len = pathconf(req->path, _PC_PATH_MAX);

  if (len == -1) {
#if defined(PATH_MAX)
    len = PATH_MAX;
#else
    len = 4096;
#endif
  }

  buf = malloc(len + 1);

  if (buf == NULL) {
    errno = ENOMEM;
    return -1;
  }

  len = readlink(req->path, buf, len);

  if (len == -1) {
    free(buf);
    return -1;
  }

  buf[len] = '\0';
  req->ptr = buf;

  return 0;
}
Esempio n. 19
0
File: link.c Progetto: EmisFR/burp
int recursive_hardlink(const char *src, const char *dst, struct conf **confs)
{
	int n=-1;
	int ret=0;
	struct dirent **dir;
	char *tmp=NULL;
	char *fullpatha=NULL;
	char *fullpathb=NULL;
	//logp("in rec hl: %s %s\n", src, dst);
	if(!(tmp=prepend_s(dst, "dummy"))) return -1;
	if(mkpath(&tmp, dst))
	{
		logp("could not mkpath for %s\n", tmp);
		free_w(&tmp);
		return -1;
	}
	free_w(&tmp);

	if((n=scandir(src, &dir, 0, 0))<0)
	{
		logp("recursive_hardlink scandir %s: %s\n",
			src, strerror(errno));
		return -1;
	}
	while(n--)
	{
		struct stat statp;
		if(dir[n]->d_ino==0
		  || !strcmp(dir[n]->d_name, ".")
		  || !strcmp(dir[n]->d_name, ".."))
			{ free(dir[n]); continue; }
		free_w(&fullpatha);
		free_w(&fullpathb);
		if(!(fullpatha=prepend_s(src, dir[n]->d_name))
		  || !(fullpathb=prepend_s(dst, dir[n]->d_name)))
			break;

#ifdef _DIRENT_HAVE_D_TYPE
// Faster evaluation on most systems.
		if(dir[n]->d_type==DT_DIR)
		{
			if(recursive_hardlink(fullpatha, fullpathb, confs))
				break;
		}
		else
#endif
		// Otherwise, we have to do an lstat() anyway, because we
		// will need to check the number of hardlinks in do_link().
		if(lstat(fullpatha, &statp))
		{
			logp("could not lstat %s\n", fullpatha);
		}
		else if(S_ISDIR(statp.st_mode))
		{
			if(recursive_hardlink(fullpatha, fullpathb, confs))
				break;
		}
		else
		{
			//logp("hardlinking %s to %s\n", fullpathb, fullpatha);
			if(write_status(CNTR_STATUS_SHUFFLING, fullpathb,
				get_cntr(confs))
			  || do_link(fullpatha, fullpathb, &statp, confs,
				0 /* do not overwrite target */))
				break;
		}
		free(dir[n]);
	}
	if(n>0)
	{
		ret=-1;
		for(; n>0; n--) free(dir[n]);
	}
	free(dir);

	free_w(&fullpatha);
	free_w(&fullpathb);

	return ret;
}
void directory_listing(void *data,int sock)
{
    struct dirent **namelist;
    struct stat buf;
    int i,n,ret=0,j=0,f_size=0;

    char dir_req[100],list[200],l_modi_GMT[75],l_modi_GMT_2[75],*ptr,*ptr2,file_size[30];
    strcpy(dir_req,data);

    ptr=strstr(dir_req,"index.html");

    if(ptr!=NULL)
    {
	while(ptr[j]!='\0')
	{
	  ptr[j]='\0';
	  j++;
	}
    }

	n = scandir(dir_req, &namelist, 0, alphasort);
	if (n <= 0)
	  {
//	    perror("scandir");
	      send(sock, "NOT FOUND", sizeof(char)*9, 0);
	  }
	else 
	{    
	  for (i = 0; i < n; i++) 
	    {
	      if((namelist[i]->d_name)[0]=='.')
		continue;
	      
	      memset(list,0,sizeof(char)*200);
	      memset(file_size,0,sizeof(char)*30);

	      strcpy(list,namelist[i]->d_name);
	      ptr2=namelist[i]->d_name;
	      ret = stat(ptr2, &buf); 		//check if file present
	      if(ret==0)
		{	
			f_size=buf.st_size;
			sprintf(file_size ,"%d",f_size);
			printf("file_size is %s ",file_size);
			strcpy(l_modi_GMT,asctime(gmtime(&(buf.st_mtime))));
			strncpy(l_modi_GMT_2,l_modi_GMT,strlen(l_modi_GMT)-5);
		}
		
		strcat(list,"\t");
		strcat(list,l_modi_GMT_2);
		strcat(list,"\t");
		strcat(list,file_size);
		strcat(list,"\0");

		send(sock, list, sizeof(char)*strlen(list), 0);
		send(sock, "\n", sizeof(char)*1, 0);
		  free(namelist[i]);
	    }
	  strcpy(q2->head->status,"200");        
	free(namelist);
	}
}
Esempio n. 21
0
/*
  Show and process a file selection dialog.
  Returns path/name user selected or NULL if user canceled
  input: zip_path = pointer's pointer to buffer to contain file path
  within a selected zip file, or NULL if browsing zip files is disallowed.
  bAllowNew: TRUE if the user is allowed to insert new file names.
*/
char* SDLGui_FileSelect(const char *path_and_name, char **zip_path, bool bAllowNew)
{
	struct dirent **files = NULL;
	char *pStringMem;
	char *retpath;
	char *home, *path, *fname;          /* The actual file and path names */
	bool reloaddir = TRUE;              /* Do we have to reload the directory file list? */
	int retbut;
	int oldcursorstate;
	int selection = -1;                 /* The actual selection, -1 if none selected */
	char *zipfilename;                  /* Filename in zip file */
	char *zipdir;
	bool browsingzip = FALSE;           /* Are we browsing an archive? */
	zip_dir *zipfiles = NULL;
	SDL_Event sdlEvent;

	ypos = 0;
	refreshentries = TRUE;
	entries = 0;

	/* Allocate memory for the file and path name strings: */
	pStringMem = malloc(4 * FILENAME_MAX);
	path = pStringMem;
	fname = pStringMem + FILENAME_MAX;
	zipdir = pStringMem + 2 * FILENAME_MAX;
	zipfilename = pStringMem + 3 * FILENAME_MAX;
	zipfilename[0] = 0;
	fname[0] = 0;
	path[0] = 0;

	SDLGui_CenterDlg(fsdlg);
	if (bAllowNew)
	{
		fsdlg[SGFSDLG_FILENAME].type = SGEDITFIELD;
		fsdlg[SGFSDLG_FILENAME].flags |= SG_EXIT;
	}
	else
	{
		fsdlg[SGFSDLG_FILENAME].type = SGTEXT;
		fsdlg[SGFSDLG_FILENAME].flags &= ~SG_EXIT;
	}

	/* Prepare the path and filename variables */
	if (path_and_name && path_and_name[0])
	{
		strncpy(path, path_and_name, FILENAME_MAX);
		path[FILENAME_MAX-1] = '\0';
	}
	if (!File_DirExists(path))
	{
		File_SplitPath(path, path, fname, NULL);
		if (!(File_DirExists(path) || getcwd(path, FILENAME_MAX)))
		{
			perror("SDLGui_FileSelect: non-existing path and CWD failed");
			return NULL;
		}
	}

	File_MakeAbsoluteName(path);
	File_MakeValidPathName(path);
	File_ShrinkName(dlgpath, path, DLGPATH_SIZE);
	File_ShrinkName(dlgfname, fname, DLGFNAME_SIZE);

	/* Save old mouse cursor state and enable cursor */
	oldcursorstate = SDL_ShowCursor(SDL_QUERY);
	if (oldcursorstate == SDL_DISABLE)
		SDL_ShowCursor(SDL_ENABLE);

	do
	{
		if (reloaddir)
		{
			files = files_free(files);

			if (browsingzip)
			{
				files = ZIP_GetFilesDir(zipfiles, zipdir, &entries);
			}
			else
			{
				/* Load directory entries: */
				entries = scandir(path, &files, 0, alphasort);
			}
			
			/* Remove hidden files from the list if necessary: */
			if (!(fsdlg[SGFSDLG_SHOWHIDDEN].state & SG_SELECTED))
			{
				DlgFileSelect_RemoveHiddenFiles(files);
			}

			if (entries < 0)
			{
				fprintf(stderr, "SDLGui_FileSelect: Path not found.\n");
				free(pStringMem);
				return NULL;
			}

			/* reload always implies refresh */
			reloaddir = FALSE;
			refreshentries = TRUE;
		}/* reloaddir */

		/* Update the file name strings in the dialog? */
		if (refreshentries)
		{
			if (!DlgFileSelect_RefreshEntries(files, path, browsingzip))
			{
				free(pStringMem);
				return NULL;
			}
			refreshentries = FALSE;
		}

		/* Show dialog: */
		retbut = SDLGui_DoDialog(fsdlg, &sdlEvent);

		/* Has the user clicked on a file or folder? */
		if (retbut>=SGFSDLG_ENTRY1 && retbut<=SGFSDLG_ENTRY16 && retbut-SGFSDLG_ENTRY1+ypos<entries)
		{
			char *tempstr;
			
			tempstr = malloc(FILENAME_MAX);
			if (!tempstr)
			{
				perror("Error while allocating temporary memory in SDLGui_FileSelect()");
				free(pStringMem);
				return NULL;
			}

			if (browsingzip == TRUE)
			{
				if (!strcat_maxlen(tempstr, FILENAME_MAX,
						   zipdir, files[retbut-SGFSDLG_ENTRY1+ypos]->d_name))
				{
					fprintf(stderr, "SDLGui_FileSelect: Path name too long!\n");
					free(pStringMem);
					return NULL;
				}
				/* directory? */
				if (File_DoesFileNameEndWithSlash(tempstr))
				{
					/* handle the ../ directory */
					if (strcmp(files[retbut-SGFSDLG_ENTRY1+ypos]->d_name, "../") == 0)
					{
						/* close the zip file */
						if (strcmp(tempstr, "../") == 0)
						{
							/* free zip file entries */
							ZIP_FreeZipDir(zipfiles);
							zipfiles = NULL;
							/* Copy the path name to the dialog */
							File_ShrinkName(dlgpath, path, DLGPATH_SIZE);
							browsingzip = FALSE;
						}
						else
						{
							/* remove "../" and previous dir from path */
							File_PathShorten(tempstr, 2);
							correct_zip_root(tempstr);
							strcpy(zipdir, tempstr);
							File_ShrinkName(dlgpath, zipdir, DLGPATH_SIZE);
						}
					}
					else /* not the "../" directory */
					{
						strcpy(zipdir, tempstr);
						File_ShrinkName(dlgpath, zipdir, DLGPATH_SIZE);
					}
					reloaddir = TRUE;
					/* Copy the path name to the dialog */
					selection = -1;                /* Remove old selection */
					zipfilename[0] = '\0';
					dlgfname[0] = 0;
					ypos = 0;
				}
				else
				{
					/* not dir, select a file in the zip */
					selection = retbut-SGFSDLG_ENTRY1+ypos;
					strcpy(zipfilename, files[selection]->d_name);
					File_ShrinkName(dlgfname, zipfilename, DLGFNAME_SIZE);
				}

			}
			else /* not browsingzip */
			{
				if (!strcat_maxlen(tempstr, FILENAME_MAX,
						   path, files[retbut-SGFSDLG_ENTRY1+ypos]->d_name))
				{
					fprintf(stderr, "SDLGui_FileSelect: Path name too long!\n");
					free(pStringMem);
					return NULL;
				}
				if (File_DirExists(tempstr))
				{
					File_HandleDotDirs(tempstr);
					File_AddSlashToEndFileName(tempstr);
					/* Copy the path name to the dialog */
					File_ShrinkName(dlgpath, tempstr, DLGPATH_SIZE);
					strcpy(path, tempstr);
					reloaddir = TRUE;
					selection = -1;                /* Remove old selection */
					dlgfname[0] = 0;
					ypos = 0;
				}
				else if (ZIP_FileNameIsZIP(tempstr) && zip_path != NULL)
				{
					/* open a zip file */
					zipfiles = ZIP_GetFiles(tempstr);
					if (zipfiles != NULL && browsingzip == FALSE)
					{
						selection = retbut-SGFSDLG_ENTRY1+ypos;
						strcpy(fname, files[selection]->d_name);
						File_ShrinkName(dlgfname, fname, DLGFNAME_SIZE);
						browsingzip = TRUE;
						zipdir[0] = '\0'; /* zip root */
						File_ShrinkName(dlgpath, zipdir, DLGPATH_SIZE);
						reloaddir = TRUE;
						ypos = 0;
					}

				}
				else
				{
					/* Select a file */
					selection = retbut-SGFSDLG_ENTRY1+ypos;
					strcpy(fname, files[selection]->d_name);
					File_ShrinkName(dlgfname, fname, DLGFNAME_SIZE);
				}

			} /* not browsingzip */

			free(tempstr);
		}
		else    /* Has the user clicked on another button? */
		{
			switch(retbut)
			{
			case SGFSDLG_UPDIR:                 /* Change path to parent directory */

				if (browsingzip)
				{
					/* close the zip file? */
					if (!zipdir[0])
					{
						/* free zip file entries */
						ZIP_FreeZipDir(zipfiles);
						browsingzip = FALSE;
						zipfiles = NULL;
						File_ShrinkName(dlgpath, path, DLGPATH_SIZE);
					}
					else
					{
						/* remove last dir from zipdir path */
						File_PathShorten(zipdir, 1);
						correct_zip_root(zipdir);
						File_ShrinkName(dlgpath, zipdir, DLGPATH_SIZE);
						zipfilename[0] = '\0';
					}
				}  /* not a zip file: */
				else
				{
					File_PathShorten(path, 1);
					File_ShrinkName(dlgpath, path, DLGPATH_SIZE);
				}
				reloaddir = TRUE;
				break;

			case SGFSDLG_HOMEDIR:               /* Change to home directory */
				home = getenv("HOME");
				if (home == NULL)
					break;
				if (browsingzip)
				{
					/* free zip file entries */
					ZIP_FreeZipDir(zipfiles);
					zipfiles = NULL;
					browsingzip = FALSE;
				}
				strcpy(path, home);
				File_AddSlashToEndFileName(path);
				File_ShrinkName(dlgpath, path, DLGPATH_SIZE);
				reloaddir = TRUE;
				break;

			case SGFSDLG_ROOTDIR:               /* Change to root directory */
				if (browsingzip)
				{
					/* free zip file entries */
					ZIP_FreeZipDir(zipfiles);
					zipfiles = NULL;
					browsingzip = FALSE;
				}
				path[0] = PATHSEP; path[1] = '\0';
				strcpy(dlgpath, path);
				reloaddir = TRUE;
				break;
			case SGFSDLG_UP:                    /* Scroll up */
				DlgFileSelect_ScrollUp();
				SDL_Delay(10);
				break;
			case SGFSDLG_DOWN:                  /* Scroll down */
				DlgFileSelect_ScrollDown();
				SDL_Delay(10);
				break;
			case SGFSDLG_FILENAME:              /* User entered new filename */
				strcpy(fname, dlgfname);
				break;
			case SGFSDLG_SHOWHIDDEN:            /* Show/hide hidden files */
				reloaddir = TRUE;
				ypos = 0;
				break;
			case SDLGUI_UNKNOWNEVENT:
				DlgFileSelect_HandleSdlEvents(&sdlEvent);
				break;
			} /* switch */
      
			if (reloaddir)
			{
				/* Remove old selection */
				selection = -1;
				fname[0] = 0;
				dlgfname[0] = 0;
				ypos = 0;
			}
		} /* other button code */


	} /* do */
	while (retbut!=SGFSDLG_OKAY && retbut!=SGFSDLG_CANCEL
	       && retbut!=SDLGUI_QUIT && retbut != SDLGUI_ERROR && !bQuitProgram);

	if (oldcursorstate == SDL_DISABLE)
		SDL_ShowCursor(SDL_DISABLE);

	files_free(files);

	if (browsingzip)
	{
		/* free zip file entries */
		ZIP_FreeZipDir(zipfiles);
		zipfiles = NULL;
	}

	if (retbut == SGFSDLG_OKAY)
	{
		if (zip_path)
			*zip_path = zip_get_path(zipdir, zipfilename, browsingzip);
		retpath = File_MakePath(path, fname, NULL);
	}
	else
		retpath = NULL;
	free(pStringMem);
	return retpath;
}
PatchMgr::PatchMgr()
{
	// load patches
#ifdef WIN32
	Log.Notice("PatchMgr", "Loading Patches...");
	char Buffer[MAX_PATH*10];
	char Buffer2[MAX_PATH*10];
	char Buffer3[MAX_PATH*10];

	WIN32_FIND_DATA fd;
	HANDLE fHandle;
	MD5Hash md5;
	Patch * pPatch;
	DWORD size,sizehigh;
	HANDLE hFile;
	uint32 srcversion;
	char locality[5];
	uint32 i;

	if(!GetCurrentDirectory(MAX_PATH*10, Buffer))
		return;

	strcpy(Buffer2,Buffer);
	strcat(Buffer, "\\ClientPatches\\*.*");
	fHandle = FindFirstFile(Buffer, &fd);
	if(fHandle == INVALID_HANDLE_VALUE)
		return;

	do 
	{
		snprintf(Buffer3,MAX_PATH*10,"%s\\ClientPatches\\%s",Buffer2,fd.cFileName);
		if(sscanf(fd.cFileName,"%4s%u.", locality, &srcversion) != 2)
			continue;

		hFile = CreateFile(Buffer3, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, NULL);
		if(hFile == INVALID_HANDLE_VALUE)
			continue;

		Log.Notice("PatchMgr", "Found patch for b%u locale `%s`.", srcversion,locality);
		pPatch = new Patch;
		size = GetFileSize(hFile, &sizehigh);
		pPatch->FileSize = size;
		pPatch->Data = new uint8[size];
		pPatch->Version = srcversion;
		for(i = 0; i < 4; ++i)
			pPatch->Locality[i] = static_cast<char>(tolower(locality[i]));
		pPatch->Locality[4] = 0;
		pPatch->uLocality = *(uint32*)pPatch->Locality;

		if(pPatch->Data== NULL)
		{
			// shouldn't really happen
			delete pPatch;
			CloseHandle(hFile);
			continue;
		}

		// read the whole file
		ASSERT(ReadFile(hFile, pPatch->Data, pPatch->FileSize, &size, NULL));
		ASSERT(size == pPatch->FileSize);

		// close the handle, no longer needed
		CloseHandle(hFile);

		// md5hash the file
		md5.Initialize();
		md5.UpdateData(pPatch->Data, pPatch->FileSize);
		md5.Finalize();
		memcpy(pPatch->MD5, md5.GetDigest(), MD5_DIGEST_LENGTH);
		
		// add the patch to the patchlist
		m_patches.push_back(pPatch);

	} while(FindNextFile(fHandle,&fd));
	FindClose(fHandle);
#else
	/* 
	 *nix patch loader
	 */
	Log.Notice("PatchMgr", "Loading Patches...");
	char Buffer[MAX_PATH*10];
	char Buffer2[MAX_PATH*10];
	char Buffer3[MAX_PATH*10];

	struct dirent ** list;
	int filecount;
	int read_fd;
	MD5Hash md5;
	Patch * pPatch;
	int size;
	uint32 srcversion;
	char locality[5];
	uint32 i;
	struct stat sb;

	strcpy(Buffer, "./ClientPatches");
	strcpy(Buffer2,Buffer);

	filecount = scandir("./ClientPatches", &list, 0, 0);
	if(filecount <= 0 || list== NULL)
	{
		Log.Error("PatchMgr", "No patches found.");
		return;
	}

	while(filecount--)
	{
		snprintf(Buffer3,MAX_PATH*10,"./ClientPatches/%s",list[filecount]->d_name);
		if(sscanf(list[filecount]->d_name,"%4s%u.", locality, &srcversion) != 2)
			continue;

		read_fd = open(Buffer3, O_RDONLY);
		if(read_fd <= 0)
		{
			printf("Cannot open %s\n", Buffer3);
			continue;
		}

		if(fstat(read_fd, &sb) < 0)
		{
			printf("Cannot stat %s\n", Buffer3);
			continue;
		}

		Log.Notice("PatchMgr", "Found patch for b%u locale `%s` (%u bytes).", srcversion,locality, sb.st_size);
		pPatch = new Patch;
		size = sb.st_size;
		pPatch->FileSize = size;
		pPatch->Data = new uint8[size];
		pPatch->Version = srcversion;
		for(i = 0; i < 4; ++i)
			pPatch->Locality[i] = tolower(locality[i]);
		pPatch->Locality[4] = 0;
		pPatch->uLocality = *(uint32*)pPatch->Locality;

		if(pPatch->Data== NULL)
		{
			// shouldn't really happen
			delete pPatch;
			close(read_fd);
			continue;
		}

		// read the whole file
		ASSERT(read(read_fd, pPatch->Data, size) == size);

		// close handle
		close(read_fd);

		// md5hash the file
		md5.Initialize();
		md5.UpdateData(pPatch->Data, pPatch->FileSize);
		md5.Finalize();
		memcpy(pPatch->MD5, md5.GetDigest(), MD5_DIGEST_LENGTH);

		// add the patch to the patchlist
		m_patches.push_back(pPatch);
		free(list[filecount]);
	}
	free(list);
#endif
}
Esempio n. 23
0
//
// denis - BaseFileSearchDir
// Check single paths for a given file with a possible extension
// Case insensitive, but returns actual file name
//
std::string BaseFileSearchDir(std::string dir, std::string file, std::string ext, std::string hash = "")
{
    std::string found;

    if(dir[dir.length() - 1] != PATHSEPCHAR)
        dir += PATHSEP;

    std::transform(hash.begin(), hash.end(), hash.begin(), toupper);
    std::string dothash = ".";
    if(hash.length())
        dothash += hash;
    else
        dothash = "";

    // denis - list files in the directory of interest, case-desensitize
    // then see if wanted wad is listed
#ifdef UNIX
    struct dirent **namelist = 0;
    int n = scandir(dir.c_str(), &namelist, 0, alphasort);

    for(int i = 0; i < n && namelist[i]; i++)
    {
        std::string d_name = namelist[i]->d_name;

        M_Free(namelist[i]);

        if(!found.length())
        {
            if(d_name == "." || d_name == "..")
                continue;

            std::string tmp = d_name;
            std::transform(tmp.begin(), tmp.end(), tmp.begin(), toupper);

            if(file == tmp || (file + ext) == tmp || (file + dothash) == tmp || (file + ext + dothash) == tmp)
            {
                std::string local_file = (dir + d_name).c_str();
                std::string local_hash = W_MD5(local_file.c_str());

                if(!hash.length() || hash == local_hash)
                {
                    found = d_name;
                }
                else if(hash.length())
                {
                    Printf (PRINT_HIGH, "WAD at %s does not match required copy\n", local_file.c_str());
                    Printf (PRINT_HIGH, "Local MD5: %s\n", local_hash.c_str());
                    Printf (PRINT_HIGH, "Required MD5: %s\n\n", hash.c_str());
                }
            }
        }
    }

    M_Free(namelist);
#else
    std::string all_ext = dir + "*";
    //all_ext += ext;

    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(all_ext.c_str(), &FindFileData);
    DWORD dwError = GetLastError();

    if (hFind == INVALID_HANDLE_VALUE)
    {
        Printf (PRINT_HIGH, "FindFirstFile failed for %s\n", all_ext.c_str());
        Printf (PRINT_HIGH, "GetLastError: %d\n", dwError);
        return "";
    }

    do
    {
        if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            continue;

        std::string tmp = FindFileData.cFileName;
        std::transform(tmp.begin(), tmp.end(), tmp.begin(), toupper);

        if(file == tmp || (file + ext) == tmp || (file + dothash) == tmp || (file + ext + dothash) == tmp)
        {
            std::string local_file = (dir + FindFileData.cFileName).c_str();
            std::string local_hash = W_MD5(local_file.c_str());

            if(!hash.length() || hash == local_hash)
            {
                found = FindFileData.cFileName;
                break;
            }
            else if(hash.length())
            {
                Printf (PRINT_HIGH, "WAD at %s does not match required copy\n", local_file.c_str());
                Printf (PRINT_HIGH, "Local MD5: %s\n", local_hash.c_str());
                Printf (PRINT_HIGH, "Required MD5: %s\n\n", hash.c_str());
            }
        }
    } while(FindNextFile(hFind, &FindFileData));

    dwError = GetLastError();

    // Note: As documented, FindNextFile sets ERROR_NO_MORE_FILES as the error
    // code, but when this function "fails" it does not set it we have to assume
    // that it completed successfully (this is actually  bad practice, because
    // it says in the docs that it does not set ERROR_SUCCESS, even though
    // GetLastError returns 0) WTF DO WE DO?!
    if(dwError != ERROR_SUCCESS && dwError != ERROR_NO_MORE_FILES)
        Printf (PRINT_HIGH, "FindNextFile failed. GetLastError: %d\n", dwError);

    FindClose(hFind);
#endif

    return found;
}
Esempio n. 24
0
int SDLEngine::Run(void*)
{
  std::cout << "input folder: " << input_folder << std::endl;
  bool gray = false;
  fcount = scandir(input_folder.c_str(), &filelist, ppm_select, alphasort);
  if (fcount <= 0)
  {
    fcount = scandir(input_folder.c_str(), &filelist, pgm_select, alphasort);
    gray = true;
  }
  if (fcount <= 0)
  {
    std::cout << "There are no .ppm or .pgm files in this folder! Maybe you have to convert the images first e.g. using" << std::endl
      << "  mogrify -format ppm *.jpg" << std::endl;
    return 0;
  }
  std::cout << "found " << fcount << " files" << std::endl;
  char filename[255];
  sprintf(filename, "%s/init.txt", input_folder.c_str());
  std::ifstream aStream(filename);
  if(!aStream || aStream.eof())
  {
    std::cout << "please create the file \"" << filename << "\" specifying the initial bounding box (x1,y1,x2,y2)" << std::endl;
    return 0;
  }
  char line[255];
  int x1,y1,x2,y2,imgid, width,height;
  std::vector<ObjectBox> boxes;
  while(aStream.getline(line,255))
  {
    x1 = y1 = x2 = y2 = imgid = 0;
    int i = 0;
    for(;line[i] >= '0' && line[i] <= '9'; i++)
      x1 = x1*10 + (line[i] - '0');
    for(i++;line[i] >= '0' && line[i] <= '9'; i++)
      y1 = y1*10 + (line[i] - '0');
    for(i++;line[i] >= '0' && line[i] <= '9'; i++)
      x2 = x2*10 + (line[i] - '0');
    for(i++;line[i] >= '0' && line[i] <= '9'; i++)
      y2 = y2*10 + (line[i] - '0');
    if(line[i] == ',')
      for(i++;line[i] >= '0' && line[i] <= '9'; i++)
        imgid = imgid*10 + (line[i] - '0'); 
    ObjectBox b = {(float)x1,(float)y1,(float)(x2-x1),(float)(y2-y1),imgid};
    boxes.push_back(b);
  }
  aStream.close();
    
  std::cout << "output folder: " << output_folder << std::endl;
  DIR * dir = opendir(output_folder.c_str());
  if (dir == 0)
  {
    std::cout << "\tdoes not exist -> try to create it" << std::endl;
    if(system(("mkdir "+output_folder).c_str()))
    {
      std::cout << "\t failed to create directory" << std::endl;
      return 0;
    }
  }
  closedir(dir);

  sprintf(filename, "%s/%s", input_folder.c_str(), filelist[0]->d_name);
  int z;
  unsigned char* dummy = gray ? readFromPGM<unsigned char>(filename, width, height) :
                                readFromPPM<unsigned char>(filename, width, height, z);
  delete[] dummy;
    
  // Initialize MultiObjectTLD
  MOTLDSettings s(gray ? COLOR_MODE_GRAY : COLOR_MODE_RGB);
  // s.bbMin = 18;
  MultiObjectTLD p(width, height, s);
  std::vector<ObjectBox> addBoxes;
  std::vector<ObjectBox>::iterator boxIt = boxes.begin();

  if(ivScreen != NULL)
    SDL_FreeSurface(ivScreen);
  ivScreen = SDL_SetVideoMode( width, height, 0, SDL_HWSURFACE | SDL_DOUBLEBUF); // | SDL_RESIZABLE
  SDL_WM_SetCaption("MultiObjectTLD", 0 );

  sprintf(filename, "%s/output.txt", output_folder.c_str());
  std::ofstream outStream(filename);  

  for (int i=0; i < fcount && (!MAX_FILE_NUMBER || i<MAX_FILE_NUMBER); ++i)
  {
    // first load the image
    sprintf(filename, "%s/%s", input_folder.c_str(), filelist[i]->d_name);
    int xS, yS, z;
    unsigned char* img = gray ? readFromPGM<unsigned char>(filename, xS, yS) :
                                readFromPPM<unsigned char>(filename, xS, yS, z);
    // then process it with MultiObjectTLD
    p.processFrame(img);
    
    while(boxIt != boxes.end() && boxIt->objectId == i)
    {
      addBoxes.push_back(*boxIt);
      boxIt++;
    }
    if(addBoxes.size() > 0){
      p.addObjects(addBoxes);
      addBoxes.clear();
    }
    
    // and save debug image to file
    sprintf(filename, "%s/%s", output_folder.c_str(), filelist[i]->d_name);
    p.writeDebugImage(img,filename);
    displaymax = i;

    // print current box to output file
    if(p.getValid())
    {
      ObjectBox b = p.getObjectBox();
      if(i > 0)
        outStream << std::endl;
      outStream << b.x << "," << b.y << "," << (b.x + b.width) << "," << (b.y + b.height);
    }
    else
      outStream << std::endl << "NaN,NaN,NaN,NaN";
    delete[] img;
    if(ivQuit)
      break;
  }
  outStream.close();
  std::cout << "MultiObjectTLD finished!" << std::endl;
  return 0;
}
Esempio n. 25
0
static size_t write_fru(char *eeprom)
{
	gint result;
	const char *serial, *file;
	char *ser_num, *filename;
	time_t frutime;
	FILE *fp = NULL;
	size_t i;
	time_t tmp;
	struct tm *tmp2;
	char buf[256];
	int j, n;
	struct dirent **namelist;
	GtkListStore *store;

	n = scandir(FRU_FILES, &namelist, 0, alphasort);
	/* No fru files, don't bother */
	if (n < 0) {
		printf("didn't find FRU_Files in %s at %s(%s)\n", FRU_FILES, __FILE__, __func__);
		return 0;
	}

	g_object_set(dialogs.serial_num, "secondary_text", eeprom, NULL);

	filename = g_malloc(PATH_MAX);
	ser_num = malloc(128);
	memset(ser_num, 0, 128);

	fp = fopen(".serialnum", "r");
	if (fp) {
		i = fread(ser_num, 1, 128, fp);
		if (!ferror(fp) && (i == 128 || feof(fp)))
			gtk_entry_set_text(GTK_ENTRY(serial_num), (const gchar*)&ser_num[1]);
		fclose(fp);
	}

	store = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(fru_file_list)));
	gtk_list_store_clear(store);

	for (j = 0; j < n; j++) {
		if (namelist[j]->d_type == DT_REG && str_endswith(namelist[j]->d_name, ".bin"))
			gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(fru_file_list), namelist[j]->d_name);
		free(namelist[j]);
	}
	free(namelist);

	gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(fru_file_list), "Other...");

	gtk_combo_box_set_active(GTK_COMBO_BOX(fru_file_list), ser_num[0]);
	free(ser_num);

	frutime = mins_since_jan_1_1996();
	tmp = min2date(frutime);
	tmp2 = gmtime(&tmp);

	strftime(buf, sizeof(buf), "%a %b %d %H:%M %Y", tmp2);

	gtk_entry_set_text(GTK_ENTRY(fru_date), buf);

get_serial_and_file:
	result = gtk_dialog_run(GTK_DIALOG(dialogs.serial_num));

	i = 0;
	switch (result) {
		case GTK_RESPONSE_OK:
			serial = gtk_entry_get_text(GTK_ENTRY(serial_num));
			if (strlen(serial) == 0) {
				create_blocking_popup(GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
					"", "Serial number required");
				goto get_serial_and_file;
			}

			file = gtk_combo_box_get_active_text(GTK_COMBO_BOX(fru_file_list));

			if (strncmp(file, "Other...", 8) != 0) {
				snprintf(filename, PATH_MAX, FRU_FILES "%s", file);
			} else {
				/* manually choose fru file */
				GtkWidget *dialog;

				dialog = gtk_file_chooser_dialog_new("Select FRU file",
							GTK_WINDOW(dialogs.serial_num),
							GTK_FILE_CHOOSER_ACTION_OPEN,
							GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
							GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
							NULL);

				if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
					filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
				}
				gtk_widget_destroy(dialog);
			}

			if (filename) {
				fflush(NULL);
				sprintf(buf, "fru-dump -i %s -o %s -s %s -d %d 2>&1",
						filename, eeprom, serial, (unsigned int)frutime);
#if DEBUG
				printf("%s\n", buf);
#else
				fp = popen(buf, "r");
#endif
				if (!fp) {
					printf("can't execute \"%s\"\n", buf);
				} else {
					i = 0;
					while(fgets(buf, sizeof(buf), fp) != NULL){
						/* fru-dump not installed */
						if (strstr(buf, "not found"))
							printf("no fru-tools installed\n");
						if (strstr(buf, "wrote") && strstr(buf, "bytes to") && strstr(buf, eeprom))
							i = 1;
					}
					pclose(fp);
				}
				fp = fopen(".serialnum", "w");
				if (fp) {
					fprintf(fp, "%c%s", gtk_combo_box_get_active(GTK_COMBO_BOX(fru_file_list)), serial);
					fclose(fp);
				}
			}
			break;
		case GTK_RESPONSE_DELETE_EVENT:
			break;
		default:
			printf("unknown response %d in %s\n", result, __func__);
			break;
	}
	gtk_widget_hide(GTK_WIDGET(dialogs.serial_num));

	g_free(filename);
	return i;
}
    return -1;
  }

  int db_files_select(const struct dirent *file) {
    int i;
    for (i = 0; db_name[i]; i++) if (db_name[i] != file->d_name[i]) return 0;

    while (1) switch (file->d_name[i]) {
      case '\0': return 1;
      case '0' ... '9': i++;
        continue;
      default: return 0;
    }
  }

  int ret = scandir (dir, files, db_files_select, db_files_sort);
  pthread_mutex_unlock(&mutex);
  return ret;
}


/// Projde databázi a opraví atributy typu Pointer z id uzlů na pointery.
static void fix_pointers(Database *D, IdToNode *nodes) {
  ndictFor(var, nodes) {
    Node *node = var->value;

    node_get_type(node)->init_pointers(nodes, node);
  } ndictForEnd;
}

Esempio n. 27
-1
static int scan_sys_cache_info (void) {
	long page_size = sysconf (_SC_PAGESIZE);
	if (page_size <= 0) {
		error (0, errno, "unable to get pagesize");
		return -1;
	}

	/* versionsort sort by index number */
	struct dirent ** list;
	int nb_dir = scandir (SYSPATH, &list, scandir_filter, alphasort);
	if (nb_dir < 0) {
		error (0, errno, "scandir(%s)", SYSPATH);
		return -1;
	}

	// alloc table (will set found to 0)
	caches = calloc (nb_dir, sizeof (struct cache_info));
	if (caches == NULL)
		error (EXIT_FAILURE, errno, "calloc");
	nb_cache_levels = nb_dir;

	for (int i = 0; i < nb_dir; i++) {
		const char * d = list[i]->d_name;
		int ok;
		char buf[BUF_SIZE];
		struct cache_info cinfo;

		// ensure type includes Data
		if (read_sys_cache_file (d, "type", buf) == -1)
			continue;
		if (strcmp (buf, "Data") == 0)
		  cinfo.type = "Data";
		else if (strcmp (buf, "Unified") == 0)
			cinfo.type = "Unified";
		else
			continue;

		// read size, assoc, level
		if (read_sys_cache_file (d, "size", buf) == -1)
			continue;
		cinfo.size = str2size (buf, &ok); 
		if (!(ok && cinfo.size > 0))
			continue;

		if (read_sys_cache_file (d, "ways_of_associativity", buf) == -1)
			continue;
		cinfo.assoc = checked_strtoul (buf, &ok, NULL);
		if (! (ok && cinfo.assoc > 0))
			continue;

		if (read_sys_cache_file (d, "level", buf) == -1)
			continue;
		int level = checked_strtoul (buf, &ok, NULL);
		if (! (ok && level < nb_cache_levels))
			continue;

		cinfo.nb_colors = cinfo.size / (page_size * cinfo.assoc);
		cinfo.found = 1;
		caches[level] = cinfo;
	}
	return 0;
}
Esempio n. 28
-1
int GetiLOGen() {
    int count = 0, k = 0;
    struct dirent ** devices;
    char *d_dir = "/sys/module/hpilo/drivers/pci:hpilo/";
    char buffer[256];
    int ilogen = 0;

    count = scandir(d_dir, &devices, pci_dev_filter, alphasort );
    for (k = 0; k < count; k++) {
        unsigned char config[256];
        int config_fd;

        strncpy(buffer, d_dir, sizeof(buffer) - 1);
        strncat(buffer, devices[k]->d_name, 255 - strlen(buffer));
        strncat(buffer, "/config", 255 - strlen(buffer));
        if ((config_fd = open(buffer, O_RDONLY)) != -1) {
            if (read(config_fd, config, 256) == 256 ) {
            /* Check for iLO3 and later */
                if ((config[45] == 0x10) && (config[44] == 0x3c)) { 
                    /* This is a HP iLO */
                    if (config[47] == 0x33) {
                        switch (config[46]) {
                            case 0x04:
                                /* It's an iLO */
                                ilogen = 0;
                                break;
                            case 0x05:
                                /* It's an iLO */
                                ilogen = 1;
                                break;
                            case 0x09:
                                /* It's either an iLO2 or iLO3 */
                                switch (config[8]) {
                                    case  3:
                                        ilogen = 2;
                                        break;
                                    case  4:
                                        ilogen = 3;
                                        break;
                                    default:
                                        ilogen = 1;
                                }
                                break;
                            case 0x0e:
                                ilogen = 3;
                                break;
                            case 0x81:
                                ilogen = 4;
                                break;
                            default:
                                ilogen = config[8] - 1;
                        }
                    } 
                }
            }
            close(config_fd);
         } 
        free(devices[k]);
    }
    free(devices);
    return ilogen;
}           
Esempio n. 29
-1
static LIST* create_list_from_dir(char *dir) {
    DIR *dir_p;
    G_GAME_LIST *t;
    struct dirent *dirent_p;
    char filename[strlen(dir)+256];
    LIST *l=NULL;
    struct stat filestat;
    struct DIRENT **namelist;
    int nbf, i;
/*
    if (dir[strlen(dir)-1]=='/')
	dir[strlen(dir)-1]=0;
*/
 
    if ((nbf = scandir(dir, &namelist, NULL/*game_selection*/, my_alphasort )) != -1) {
		for (i = 0; i < nbf; i++) {
#ifdef __QNXNTO__
			if (strcmp(namelist[i]->d_name, "..") == 0)
				continue;
			else if (strcmp(namelist[i]->d_name, ".") == 0)
				continue;
			else if (stricmp(namelist[i]->d_name, "romrc.d") == 0)
				continue;
			else if (stricmp(namelist[i]->d_name, "shots") == 0)
				continue;
#endif
			sprintf(filename, "%s/%s", dir, namelist[i]->d_name);
			lstat(filename, &filestat);
			if (S_ISDIR(filestat.st_mode))
			{
				t=malloc(sizeof(G_GAME_LIST));
				t->dir=malloc(strlen(namelist[i]->d_name)*sizeof(char)+2);
				sprintf(t->dir,"%s",namelist[i]->d_name);
				t->dr=NULL;
				t->file=NULL;
				l=list_prepend(l,t);
			}
			else if (game_only==SDL_TRUE)
			{
				DRIVER *dr;
				if ((dr=get_driver_for_zip(filename))!=NULL)
				{
					t=malloc(sizeof(G_GAME_LIST));
					t->dir=NULL;
					t->file=strdup(namelist[i]->d_name);
					t->dr=dr;
					l=list_prepend(l,t);
					//printf("GAME %s\n",t->dr->longname);
				}
			}
			else
			{
				t=malloc(sizeof(G_GAME_LIST));
				t->file=strdup(namelist[i]->d_name);
				t->dir=NULL;
				t->dr=NULL;
				l=list_prepend(l,t);
				//printf("FILE %s\n",t->file);
			}
		}
    }
    if (nbf==-1) {
	/* the dir is unreadable, we create pseudo dir . and .. */
	t=malloc(sizeof(G_GAME_LIST));
	t->dir=strdup("..");
	t->dr=NULL;
	t->file=NULL;
	l=list_prepend(l,t);

	t=malloc(sizeof(G_GAME_LIST));
	t->dir=strdup(".");
	t->dr=NULL;
	t->file=NULL;
	l=list_prepend(l,t);
    }

    return l;
}
Esempio n. 30
-1
int recursive_hardlink(const char *src, const char *dst, const char *client, struct cntr *p1cntr, struct cntr *cntr, struct config *conf)
{
	int n=-1;
	int ret=0;
	struct dirent **dir;
	char *tmp=NULL;
	//logp("in rec hl: %s %s\n", src, dst);
	if(!(tmp=prepend_s(dst, "dummy", strlen("dummy"))))
		return -1;
	if(mkpath(&tmp, dst))
	{
		logp("could not mkpath for %s\n", tmp);
		free(tmp);
		return -1;
	}
	free(tmp);

	if((n=scandir(src, &dir, 0, 0))<0)
	{
		logp("recursive_hardlink scandir %s: %s\n",
			src, strerror(errno));
		return -1;
	}
	while(n--)
	{
		struct stat statp;
		char *fullpatha=NULL;
		char *fullpathb=NULL;
		if(dir[n]->d_ino==0
		  || !strcmp(dir[n]->d_name, ".")
		  || !strcmp(dir[n]->d_name, ".."))
			{ free(dir[n]); continue; }
		if(!(fullpatha=prepend_s(src,
			dir[n]->d_name, strlen(dir[n]->d_name)))
		|| !(fullpathb=prepend_s(dst,
			dir[n]->d_name, strlen(dir[n]->d_name))))
		{
			if(fullpatha) free(fullpatha);
			if(fullpathb) free(fullpathb);
			break;
		}

		if(lstat(fullpatha, &statp))
		{
			logp("could not lstat %s\n", fullpatha);
		}
		else if(S_ISDIR(statp.st_mode))
		{
			if(recursive_hardlink(fullpatha, fullpathb, client,
				p1cntr, cntr, conf))
			{
				free(fullpatha);
				free(fullpathb);
				break;
			}
		}
		else
		{
			//logp("hardlinking %s to %s\n", fullpathb, fullpatha);
			write_status(client, STATUS_SHUFFLING, fullpathb,
				p1cntr, cntr);
			if(do_link(fullpatha, fullpathb, &statp, conf,
				FALSE /* do not overwrite target */))
			{
				free(fullpatha);
				free(fullpathb);
				break;
			}
		}
		free(fullpatha);
		free(fullpathb);
		free(dir[n]);
	}
	if(n>0)
	{
		ret=-1;
		for(; n>0; n--) free(dir[n]);
	}
	free(dir);

	return ret;
}