Beispiel #1
0
void detect_power_meters(void)
{
	process_directory("/sys/class/power_supply", sysfs_power_meters_callback);
	if (power_meters.size() == 0) {
		process_directory("/proc/acpi/battery", acpi_power_meters_callback);
	}
}
Beispiel #2
0
void detect_power_meters(void)
{
	process_directory("/sys/class/power_supply", sysfs_power_meters_callback);
	process_glob("/sys/devices/platform/opal-sensor/hwmon/hwmon*/power*", sysfs_opal_sensors_callback);
	if (power_meters.size() == 0) {
		process_directory("/proc/acpi/battery", acpi_power_meters_callback);
	}
}
Beispiel #3
0
static void process_directory(char *path, const char *rel_path)
{
	struct dirent *ent;
	DIR *dir = opendir(path);
	char fpath[1000];
	char rpath[1000];

	memset(fpath, 0, 1000);
	memset(rpath, 0, 1000);
	while ((ent = readdir(dir)) != NULL) {
		if (strcmp(&ent->d_name, ".") && strcmp(&ent->d_name, "..")) {
			sprintf(fpath, "%s/%s", path, ent->d_name);
			sprintf(rpath, "%s/%s", rel_path, ent->d_name);

			if (ent->d_type == DT_DIR) {
				ifs_mkdir(remove_leading_slash(rpath));
				process_directory(fpath, rpath);
			} else if (ent->d_type == DT_REG) {
				FILE *f = fopen(fpath, "r");
				int size = 0;
				fseek(f, 0L, SEEK_END);
				size = ftell(f);
				fseek(f, 0L, SEEK_SET);
				char *tmp = (char *)malloc(size);
				fread(tmp, 1, size, f);
				fclose(f);
				ifs_add_file(remove_leading_slash(rpath), tmp, size);
				free(tmp);
			}
		}
	}
	closedir(dir);
}
void process_path(const char* path) {
  if (is_dir(path)) {
     process_directory(path);
  } else {
    process_file(path);
  }
}
Beispiel #5
0
static int process_path(const char *path)
{
	int pos, len;
	struct stat st;
	const struct cache_entry *ce;

	len = strlen(path);
	if (has_symlink_leading_path(path, len))
		return error("'%s' is beyond a symbolic link", path);

	pos = cache_name_pos(path, len);
	ce = pos < 0 ? NULL : active_cache[pos];
	if (ce && ce_skip_worktree(ce)) {
		/*
		 * working directory version is assumed "good"
		 * so updating it does not make sense.
		 * On the other hand, removing it from index should work
		 */
		if (allow_remove && remove_file_from_cache(path))
			return error("%s: cannot remove from the index", path);
		return 0;
	}

	/*
	 * First things first: get the stat information, to decide
	 * what to do about the pathname!
	 */
	if (lstat(path, &st) < 0)
		return process_lstat_error(path, errno);

	if (S_ISDIR(st.st_mode))
		return process_directory(path, len, &st);

	return add_one_path(ce, path, len, &st);
}
Beispiel #6
0
/*******************************************************************************
Process a (file system) pathname (a file, directory or "other").
*******************************************************************************/
void process_path(char *pathname, regex_t *extregexpptr, int recursiondepth) {
	struct stat	statinfo;

	if (recursiondepth == 0) {
		trim_trailing_slashes(pathname);
	}

	if (!regularfileflag && !directoryflag && !otherobjectflag) {
		fprintf(stderr, "No output target types requested for '%s'!\n",pathname);
		returncode = 1;
		return;
	}

	if (lstat(pathname, &statinfo) == -1) {
		fprintf(stderr, "process_path: Cannot access '%s'\n", pathname);
		returncode = 1;
		return;
	}

	if (S_ISREG(statinfo.st_mode)) {
		if (regularfileflag) {
			process_object(pathname, extregexpptr);
		}
	} else if (S_ISDIR(statinfo.st_mode)) {
		if (directoryflag) {
			process_object(pathname, extregexpptr);
		}
		if (recursiondepth == 0 || (recursiveflag && recursiondepth <= maxrecursiondepth)) {
			process_directory(pathname, extregexpptr, recursiondepth);
		}
	} else if (otherobjectflag) {
		process_object(pathname, extregexpptr);
	}
}
Beispiel #7
0
int main(int argc, char* argv[])
{
	void* img = (void*)malloc(5000000);
	create_image(img, 5000000);
	char* outp = "initrd.img";
	char* tdir = NULL;
	for(int i = 1; i < argc; i++)
	{
		if(strcmp(argv[i], "-d") == 0)
		{
			tdir = argv[++i];
		}
		else if (strcmp(argv[i], "-o") == 0)
		{
			outp = argv[++i];
		}
	}
	FILE* dmp = fopen(outp,"w");

	process_directory(tdir, "");
	fwrite(img,1, 5000000,dmp);

	fclose(dmp);
	return 0;
}
void do_dir_entry(const u8* base,
		  const char* dir,
		  const char* path,
		  const char* name, int namelen, 
		  const struct cramfs_inode* inode)
{
   int pathlen=strlen(path);
   char pname[pathlen+namelen+2];
   
   if (pathlen) {
      strncpy(pname, path, pathlen);
   }
   
   if (namelen) {
      if (pathlen) {
	 pname[pathlen]='/';
	 ++pathlen;
      }
      strncpy(pname+pathlen, name, namelen);
   }

   pname[pathlen+namelen]=0;

   // Only process directories here   
   if (S_ISDIR(inode->mode)) {
      printf("\n/%s:\n", pname);
      process_directory(base, dir, inode->offset<<2, inode->size, pname);
   }
}
Beispiel #9
0
/* Processes a path name according to its type, whether from the command line or
 * from directory recursion.
 *
 * This function calls process_file and process_directory as needed.
 */
static void process_path(const char* path, int depth)
{
    mode_t mode;
    struct stat sb;

    if (stat_path(path, &sb, depth) != 0)
        return;

    mode = sb.st_mode & S_IFMT;
    switch (mode)
    {
        case S_IFREG:
        {
            process_file(path, &sb);
            break;
        }

        case S_IFDIR:
        {
            if (recursive_flag)
            {
                process_directory(path, &sb, depth + 1);
                break;
            }

            /* FALLTHROUGH */
        }

        default:
        {
            if (quiet_flag)
                return;

            switch (mode)
            {
                case S_IFLNK:
                    warning(_("%s is a symbolic link; skipping"), path);
                    break;
                case S_IFIFO:
                    warning(_("%s is a named pipe; skipping"), path);
                    break;
                case S_IFBLK:
                    warning(_("%s is a block device; skipping"), path);
                    break;
                case S_IFCHR:
                    warning(_("%s is a character device; skipping"), path);
                    break;
                case S_IFDIR:
                    warning(_("%s is a directory; skipping"), path);
                    break;
                case S_IFSOCK:
                    warning(_("%s is a socket; skipping"), path);
                    break;
                default:
                    error(_("This cannot happen"));
            }
        }
    }
}
static void
process_file_cb (GObject      *object,
                 GAsyncResult *result,
                 gpointer      user_data)
{
	ProcessApplicationData *data;
	GFileInfo *file_info;
	GError *error = NULL;
	GFile *file;

	data = user_data;
	file = G_FILE (object);
	file_info = g_file_query_info_finish (file, result, &error);

	if (error) {
		tracker_miner_fs_file_notify (TRACKER_MINER_FS (data->miner), file, error);
		process_application_data_free (data);
		g_error_free (error);
		return;
	}

	if (g_file_info_get_file_type (file_info) == G_FILE_TYPE_DIRECTORY) {
		process_directory (data, file_info, &error);
	} else {
		data->key_file = get_desktop_key_file (file, &data->type, &error);
		if (!data->key_file) {
			gchar *uri;

			uri = g_file_get_uri (file);
			g_warning ("Couldn't properly parse desktop file '%s': '%s'",
			           uri,
			           error ? error->message : "unknown error");
			g_free (uri);
			g_clear_error (&error);

			error = g_error_new_literal (miner_applications_error_quark, 0, "File is not a key file");
		} else if (g_key_file_get_boolean (data->key_file, GROUP_DESKTOP_ENTRY, "Hidden", NULL)) {
			error = g_error_new_literal (miner_applications_error_quark, 0, "Desktop file is 'hidden', not gathering metadata for it");
		} else {
			process_desktop_file (data, file_info, &error);
		}
	}

	tracker_miner_fs_file_notify (TRACKER_MINER_FS (data->miner), data->file, error);
	process_application_data_free (data);

	if (error) {
		g_error_free (error);
	}

	if (file_info) {
		g_object_unref (file_info);
	}
}
/* Thread: scan */
static void
process_directories(char *root, int flags)
{
  char *path;

  process_directory(root, flags);

  if (scan_exit)
    return;

  while ((path = pop_dir(&dirstack)))
    {
      process_directory(path, flags);

      free(path);

      if (scan_exit)
	return;
    }
}
Beispiel #12
0
/* Win32 version */
static void
process_directory (char *path, char *cvspath)
{
  struct _finddata_t f;
  int findhandle;
  char searchbuf[MAX_PATH];
  char buf[MAX_PATH];
  char newcvspath[MAX_PATH];

  strcpy(searchbuf, path);
  strcat(searchbuf, "*.*");

  findhandle =_findfirst(searchbuf, &f);
  if (findhandle != -1)
    {
      do
      	{
          if (f.attrib & _A_SUBDIR)
      	    {
              if (f.name[0] != '.')
                {
                  strcpy(buf, path);
                  strcat(buf, f.name);
                  strcat(buf, DIR_SEPARATOR_STRING);

                  strcpy(newcvspath, cvspath);
                  strcat(newcvspath, f.name);
                  strcat(newcvspath, "/");

                  process_directory(buf, newcvspath);
                }
              continue;
      	    }

          strcpy(buf, path);
          strcat(buf, f.name);

          /* Must be a .c file */
          if (!is_valid_file(buf))
            {
              continue;
            }

          parse_file(buf, cvspath, f.name);
      	}
      while (_findnext(findhandle, &f) == 0);
      _findclose(findhandle);
    }
  else
    {
      printf("Cannot open directory '%s'", path);
      exit(1);
    }
}
Beispiel #13
0
static void
process_directories(char *root, int parent_id, int flags)
{
  struct stacked_dir *dir;

  process_directory(root, parent_id, flags);

  if (scan_exit)
    return;

  while ((dir = pop_dir(&dirstack)))
    {
      process_directory(dir->path, dir->parent_id, flags);

      free(dir->path);
      free(dir);

      if (scan_exit)
	return;
    }
}
Beispiel #14
0
int mkyaffs2image(char* target_directory, char* filename, int fixstats, mkyaffs2image_callback callback, int gzip)
{
	struct stat stats;
	memset(obj_list, 0, sizeof(objItem) * MAX_OBJECTS);
	n_obj = 0;
	obj_id = YAFFS_NOBJECT_BUCKETS + 1;

	if (stat(target_directory,&stats) < 0)
		return -1;
	
	outFile = -1;
	outgzFile = Z_NULL;

	outFile = open(filename, O_CREAT | O_TRUNC | O_WRONLY, S_IREAD | S_IWRITE);
	
	if(outFile < 0) {
		fprintf(stderr,"Could not open output file %s\n",filename);
		return -1;
	}

	if(gzip) outgzFile = gzdopen(outFile, "wb");

	if (fixstats) {
		int len = strlen(target_directory);

		if((len >= 4) && (!strcmp(target_directory + len - 4, "data"))) {
			source_path_len = len - 4;
		} else if((len >= 6) && (!strcmp(target_directory + len - 6, "system"))) {
			source_path_len = len - 6;
		} else {            
			fprintf(stderr,"Fixstats (-f) option requested but filesystem is not data or android!\n");
			return -1;
		}
		fix_stat(target_directory, &stats);
	}

	//printf("Processing directory %s into image file %s\n",argv[1],argv[2]);
	error =  write_object_header(1, YAFFS_OBJECT_TYPE_DIRECTORY, &stats, 1,"", -1, NULL);
	if(error)
		error = process_directory(YAFFS_OBJECTID_ROOT,target_directory,fixstats,callback);
	
	if(outgzFile == Z_NULL) close(outFile);
	else gzclose(outgzFile);
	
	return error < 0 ? error : 0;
}
Beispiel #15
0
void
process_file(const char* path)
{
	struct stat stat;
	if (::lstat(path, &stat) != 0) {
		fprintf(stderr, "Could not stat file \"%s\": %s\n", path,
			strerror(errno));
		return;
	}

	if (S_ISDIR(stat.st_mode)) {
		process_directory(path);
		return;
	}
	if (S_ISLNK(stat.st_mode))
		return;

	int file = open(path, O_RDONLY);
	if (file < 0) {
		fprintf(stderr, "Could not open file \"%s\": %s\n", path,
			strerror(errno));
		return;
	}

	status_t status = gSHA.Process(file);
	if (status != B_OK) {
		fprintf(stderr, "Computing SHA failed \"%s\": %s\n", path,
			strerror(status));
		return;
	}

	file_entry entry;
	memcpy(entry.hash, gSHA.Digest(), SHA_DIGEST_LENGTH);
	entry.node = stat.st_ino;
	entry.path = path;

	//printf("%s  %s\n", entry.HashString().c_str(), path);

	gFiles.push_back(entry);

	static bigtime_t sLastUpdate = -1;
	if (system_time() - sLastUpdate > 500000) {
		printf("%ld files scanned\33[1A\n", gFiles.size());
		sLastUpdate = system_time();
	}
}
Beispiel #16
0
int main(int argc, char ** argv)
{
    //use the current path as default
    char * path = argv[0];

    //use the path in the second arg if it was provided
    if(argc > 1)
        path = argv[1];

    //fix path string
    char * slash = strrchr(path, '/');
    if(!slash)
        slash = strrchr(path, '\\');

    slash[1] = 0x0;

    return process_directory(path);
};
Beispiel #17
0
File_Bag get_files_to_process(String_Bag dirs)
{
    std::cerr << "Proccessing " << dirs.size() << " directories\n";

    // get all the files desired by the user
    std::vector<File_Bag> dir_results;
    std::for_each(dirs.cbegin(), dirs.cend(), [&dir_results](const std::string& arg)
    {
        dir_results.push_back(process_directory(arg));
    });

    File_Bag files, temp;
    for (auto it = dir_results.cbegin(); it != dir_results.cend(); ++it) {
        std::merge(files.begin(), files.end(), it->begin(), it->end(), std::inserter(temp, temp.end()));
        std::swap(files, temp);
        temp.erase(temp.begin(), temp.end());
    }

    return files;
}
Beispiel #18
0
static int process_path(const char *path)
{
	int len;
	struct stat st;

	len = strlen(path);
	if (has_symlink_leading_path(len, path))
		return error("'%s' is beyond a symbolic link", path);

	/*
	 * First things first: get the stat information, to decide
	 * what to do about the pathname!
	 */
	if (lstat(path, &st) < 0)
		return process_lstat_error(path, errno);

	if (S_ISDIR(st.st_mode))
		return process_directory(path, len, &st);

	return process_file(path, len, &st);
}
Beispiel #19
0
int process_directory( t_string8 x_sIn, t_string8 x_sOut, t_string8 x_sRel, t_cmdline8 &cl, t_strlist8 &lstCmp, t_string8 &sRoot, long &lI )
{
	if ( !x_sIn.length() || !x_sOut.length() )
		return 0;

	// Process directory contents
	disk::SFindData fd;
	disk::HFIND hFind = disk::FindFirst( x_sIn.c_str(), "*", &fd );
	if ( disk::c_invalid_hfind == hFind )
		return 0;

	do 
	{ 
		// Ignore relative
		if ( '.' != *fd.szName )
		{
			// Recurse if directory
			if ( disk::eFileAttribDirectory & fd.uFileAttributes )
				process_directory( disk::FilePath< char, t_string8 >( x_sIn, fd.szName ), 
								   disk::FilePath< char, t_string8 >( x_sOut, fd.szName ),
								   disk::FilePath< char, t_string8 >( x_sRel, fd.szName ), 
								   cl, lstCmp, sRoot, lI );

			// Go process the file
			else
				process_file( x_sIn, x_sOut, x_sRel, fd.szName, cl, lstCmp, sRoot, lI );

		} // end if

	// While we can find more files
	} while ( disk::FindNext( hFind, &fd ) );

	// Close the find handle
	disk::FindClose( hFind );

	return 1;
}
Beispiel #20
0
int process_directory(const char * path)
{
    printf("Processing %s\n", path);

    //try to open directory
    DIR * directory = opendir(path);
    if(!directory)
        return 0;

    dirent * entry;
    while((entry = readdir(directory)) > 0)
    {
        //skip current, parent, this file and parts
        if(!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..") || strstr(entry->d_name, ".part"))
            continue;

        //create full path for the entry
        char * fullpath = new char[strlen(path) + entry->d_namlen + 2];
        strcpy(fullpath, path);
        strcat(fullpath, entry->d_name);

        //process files
        if(!process_file(fullpath))
        {
            //process subdirs
            strcat(fullpath, "/");
            process_directory(fullpath);
        };

        delete [] fullpath;
    };

    //close directory
    closedir(directory);
    return 1;
};
Beispiel #21
0
static int process_directory(int parent, const char *path, int fixstats, mkyaffs2image_callback callback)
{

	DIR *dir;
	struct dirent *entry;

	//nDirectories++;
	
	dir = opendir(path);
	
	if(dir)
	{
		while((entry = readdir(dir)) != NULL)
		{
		
			/* Ignore . and .. */
			if(strcmp(entry->d_name,".") &&
			   strcmp(entry->d_name,".."))
 			{
 				char full_name[PATH_MAX];
				struct stat stats;
				int equivalentObj;
				int newObj;
				
				sprintf(full_name,"%s/%s",path,entry->d_name);
				
				lstat(full_name,&stats);
				
				if(S_ISLNK(stats.st_mode) ||
				    S_ISREG(stats.st_mode) ||
				    S_ISDIR(stats.st_mode) ||
				    S_ISFIFO(stats.st_mode) ||
				    S_ISBLK(stats.st_mode) ||
				    S_ISCHR(stats.st_mode) ||
				    S_ISSOCK(stats.st_mode))
				{
				
					newObj = obj_id++;
					if (callback != NULL)
                        callback(full_name);
					//nObjects++;

                    if (fixstats) {
                        fix_stat(full_name, &stats);
                    }

					//printf("Object %d, %s is a ",newObj,full_name);
					
					/* We're going to create an object for it */
					if((equivalentObj = find_obj_in_list(stats.st_dev, stats.st_ino)) > 0)
					{
					 	/* we need to make a hard link */
					 	//printf("hard link to object %d\n",equivalentObj);
						error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_HARDLINK, &stats, parent, entry->d_name, equivalentObj, NULL);
					}
					else 
					{
						
						add_obj_to_list(stats.st_dev,stats.st_ino,newObj);
						
						if(S_ISLNK(stats.st_mode))
						{
					
							char symname[PATH_MAX];
						
							memset(symname,0, sizeof(symname));
					
							readlink(full_name,symname,sizeof(symname) -1);
						
							//printf("symlink to \"%s\"\n",symname);
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SYMLINK, &stats, parent, entry->d_name, -1, symname);

						}
						else if(S_ISREG(stats.st_mode))
						{
							//printf("file, ");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_FILE, &stats, parent, entry->d_name, -1, NULL);

							if(error >= 0)
							{
								int h;
								__u8 bytes[chunkSize];
								int nBytes;
								int chunk = 0;
								
								h = open(full_name,O_RDONLY);
								if(h >= 0)
								{
									memset(bytes,0xff,sizeof(bytes));
									while((nBytes = read(h,bytes,sizeof(bytes))) > 0)
									{
										chunk++;
										write_chunk(bytes,newObj,chunk,nBytes);
										memset(bytes,0xff,sizeof(bytes));
									}
									if(nBytes < 0) 
									   error = nBytes;
									   
									//printf("%d data chunks written\n",chunk);
								}
								else
								{
									perror("Error opening file");
								}
								close(h);
								
							}							
														
						}
						else if(S_ISSOCK(stats.st_mode))
						{
							//printf("socket\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL);
						}
						else if(S_ISFIFO(stats.st_mode))
						{
							//printf("fifo\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL);
						}
						else if(S_ISCHR(stats.st_mode))
						{
							//printf("character device\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL);
						}
						else if(S_ISBLK(stats.st_mode))
						{
							//printf("block device\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL);
						}
						else if(S_ISDIR(stats.st_mode))
						{
							//printf("directory\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_DIRECTORY, &stats, parent, entry->d_name, -1, NULL);
// NCB modified 10/9/2001				process_directory(1,full_name);
							process_directory(newObj,full_name,fixstats,callback);
						}
					}
				}
				else
				{
					//printf(" we don't handle this type\n");
				}
			}
		}

		closedir(dir);
	}
	
	return 0;

}
void process_file(char *filename, int forcelang)
{
    FILE *fd = NULL;
    int             i;
    accumulator_t * acc;
#ifdef _MSC_VER
    struct _stat fstat;
#else
	struct stat fstat;
#endif

    /* 
     * We need to determine the filetype first.
     * If it's a real file, process normally.  
     * If it's a directory and the recursion flag is set, iterate through the
     * files in the directory and run process_file on them.
     */

    if (!strcmp(filename, "<stdin>"))
    {
      fd=stdin;
    } else {
    
      if(lstat(filename,&fstat)==-1) 
      {
        fprintf(stderr,"An error occurred. The file '%s' does not appear to exist\n", filename);
      return;
      }
#ifndef _MSC_VER
      /* Symbolic link check */
      if(S_ISLNK(fstat.st_mode)) {
        if(flags & FOLLOW_SYMLINK) {
	  char *symname;
	  symname=calloc(PATH_MAX,1);
	  if(readlink(filename,symname,PATH_MAX)==-1) {
	    return;
	  }
	  process_file(symname,forcelang);
        }
        return;
      }
#endif
      if(S_ISDIR(fstat.st_mode)) {
        /* Need to error catch here.*/
        if( flags & RECURSIVE_FILE_SCAN ) {
	  process_directory(filename,forcelang);
	  return;
        }
     }
    
     if (!S_ISREG(fstat.st_mode))
     {
       printf("NOT REGULAR FILE\n");
       return;
     } 

   }
 

   if(!fd && (fd=fopen(filename,"r")) == (FILE *)NULL) {
      return;
   }

    /* (Re-)Initialize state */
    if(!determine_language(filename, fd, forcelang)) {
      fclose(fd);
      return;
    }

    *ratslexer.lex_lineno = 1;
    last_text_line = 0;
    current_file = strdup(filename);
    for (i = 0;  i < DEPTH_COUNT;  depths[i++] = 0);

    /* Process the file */

   if (!(flags & NO_STATUS))
   {
     if ((flags & HTML_OUTPUT))
     {
       printf("Analyzing <b>%s</b><br>\n", filename);
     } else if (flags & XML_OUTPUT) {
       printf("<analyzed>%s</analyzed>\n", filename);
     } else {
       printf("Analyzing %s\n", filename);
     }
   }

    scan_tokens((processorfn_t)NULL, NULL);
    process_toctou();
    

    total_lines += *ratslexer.lex_lineno;
    /* Cleanup */
    current_ignore = (ignore_t *)NULL;
    while ((acc = accumulators) != (accumulator_t *)NULL)
    {
        if (*(acc->text) != (char *)NULL)
            free(*(acc->text));
        pop_accumulator();
    }
    fclose(fd);
}
Beispiel #23
0
int
process_directory(FILE *afile, FILE *cfile, Tcl_HashTable *ht,
		  int *recno, int *tot_length, int *cfilenum, 
		  char *dirname, char *tag, int tag_length, int quiet,
		  int skipheaders)
{
  assoc_rec assocrec; /* associator output record */
  int offset;        /* address in marc file */
  int startnum, endnum; /* the starting and ending recnos for a given file */
  int result;
  Tcl_HashEntry *entry;

  DIR *dirptr;
  struct dirent *direntry;
  int dirsize, dirname_size;
  char *filenamebuff;

  /* We need to scan the directory and grab each file -- getting its  */
  /* page number from the name and generating the appropriate mapping */
  /* info in the associated special index files                       */
  if ((dirptr = opendir(dirname)) == NULL)  {
    /* printf("Normal file? (errno = %d) - returning -- \n", errno); */
    return(0); /* this indicates that this is probably a normal file  */
  }
 

  while ((direntry = readdir(dirptr)) != NULL) {
    
    /* get each file in the directory... */
#if defined SOLARIS || defined LINUX || defined WIN32
    dirsize = direntry->d_reclen + strlen(dirname) + 3;
    dirname_size = direntry->d_reclen - sizeof(struct dirent) + 2;
#else
    dirsize = strlen(dirname) + direntry->d_namlen + 3;
    dirname_size = direntry->d_namlen + 1;
#endif
    filenamebuff = CALLOC(char, dirsize); 
    if (filenamebuff == NULL) {
      fprintf(LOGFILE, "Unable to allocate file name buffer in idxpages\n");
      exit(1);
    }
    
    /* skip dot and dotdot */
    if (strcmp(direntry->d_name,".") == 0 
	|| (strcmp(direntry->d_name, "..") == 0)) {
      FREE(filenamebuff);
      continue;
    }
    
    strcpy(filenamebuff, dirname);
#ifdef WIN32
    strcat(filenamebuff, "\\");
#else
    strcat(filenamebuff, "/");
#endif
    strcat(filenamebuff, direntry->d_name);

    entry = Tcl_FindHashEntry(ht,filenamebuff);

    if (entry == NULL) {

      /* This filename may be a directory so we will recursively call */
      /* this routine                                                 */
      /* printf("(recursive) Calling process directory for %s\n", filenamebuff);*/

      if (process_directory(afile, cfile, ht, recno, tot_length, 
			    cfilenum, filenamebuff, tag, tag_length, 
			    quiet, skipheaders) == 1)
	continue; /* when the result is a 1 */
      
      offset = 0;
      
      startnum = *recno + 1;

      while ((result = get_next_sgmlrec_data(&offset, 
					     filenamebuff, tag, tag_length, 
					     skipheaders)) != 0) {
	if (result < 0) {
	  /* this is a special case where there is trailing information */
	  /* after the last record end tag in a file                    */
	  /* redo the last record...                                    */
	  fseek(afile,*recno*sizeof(assoc_rec), 0);
	  fread(&assocrec, sizeof(assoc_rec), 1, afile);
	  assocrec.recsize = assocrec.recsize + (result * -1);
	  *tot_length += assocrec.recsize ;
	  
	  if (!quiet)
	    printf ("Additional Data at EOF: ReWriting Record #%08d: Length %08d\n",*recno,
		    (int)assocrec.recsize);
	  
	  fseek(afile,*recno*sizeof(assoc_rec), 0);
	  fwrite(&assocrec, sizeof(assoc_rec), 1, afile);
	  fflush(afile);
	  
	}
	else {
	  *recno = *recno + 1;
	  
	  if (!quiet)
	    printf ("Record #%08d: Length %08d\n",*recno, result);
	  
	  /* record offset and length of sgml record in assoc file */
	  assocrec.offset = offset ;
	  assocrec.recsize = result;
	  *tot_length += result;
	  fseek(afile,*recno*sizeof(assoc_rec), 0);
	  fwrite(&assocrec, sizeof(assoc_rec), 1, afile);
	  fflush(afile);
	}
      }

      get_next_sgmlrec_data(NULL,NULL,NULL, 0, 0); /* closes file */

      if (*recno >= startnum) { /* we actually processed some records */
	endnum = *recno;
	/* write out the continuation record */
	*cfilenum = *cfilenum + 1;
	fprintf(cfile, "<FILECONT ID=%d MIN=%d MAX=%d> %s </FILECONT>\n",
		*cfilenum, startnum, endnum, filenamebuff);
      }
    }
    else {
      /* match in the hash table */
      if (!quiet)
	printf ("Duplicate file name: %s\n", filenamebuff);
    }
    FREE(filenamebuff);
  }
  closedir(dirptr);
  return (1);
}
Beispiel #24
0
int
main (int argc, char **argv)
{
  int result;
  char afilename[500];
  char cfilename[500];
  FILE *afile, *cfile, *fopen();
  char *tag;
  int tag_length;
  int quiet;
  int recursive;
  int skipheaders;
  int exists;
  int cfilenum = 0;
  continuation *cont;
  char *fmread, *fmwrite;
  Tcl_HashTable *ContNamesHash;

  assoc_rec assocrec; /* associator output record */
  int offset;        /* address in marc file */
  int high_recno;    /* current highest logical record number */
  int recno;         /* logical record number of the new record    */
                      /* added by this function and passed to index */
		      /* function. Also the value of the 0th record */
		      /* in assocfile to keep track of highest      */
		      /* logical recno in use.                      */
  int total_doc_length; /* sum of document lengths */
  LOGFILE = stderr;

  

  if ((argc > 2 && (argv[1][0] == '-' && argv[1][1] == 'q')) 
      || (argc > 3 && (argv[2][0] == '-' && argv[2][1] == 'q'))
      || (argc > 4 && (argv[3][0] == '-' && argv[3][1] == 'q')))
    quiet = 1;
  else
    quiet = 0;

  if ((argc > 2 && (argv[1][0] == '-' && argv[1][1] == 'r'))
      || (argc > 3 && (argv[2][0] == '-' && argv[2][1] == 'r'))
      || (argc > 4 && (argv[3][0] == '-' && argv[3][1] == 'r')))
    recursive = 1;
  else
    recursive = 0;

  if ((argc > 2 && (argv[1][0] == '-' && argv[1][1] == 's'))
      || (argc > 3 && (argv[2][0] == '-' && argv[2][1] == 's'))
      || (argc > 4 && (argv[3][0] == '-' && argv[3][1] == 's')))
    skipheaders = 1;
  else
    skipheaders = 0;

  if (argc-quiet-recursive-skipheaders < 3 
      || argc-quiet-recursive-skipheaders > 7) {
    fprintf(LOGFILE, "usage: %s {-q}{-s} sgmlfile <assocfile> sgmltag{/sgml_subtag/.../sgml_subtag}\n   or: %s {-q}{-s} -r directory assocfile sgmltag{/sgml_subtag/.../sgml_subtag}\n",argv[0], argv[0]);
    exit(1);
  }

  /* open up the associator (only one file even if recursive */
  if (argc-quiet-recursive-skipheaders == 3)
    sprintf(afilename,"%s.assoc",argv[1+quiet+recursive+skipheaders]);
  else
    strcpy(afilename, argv[2+quiet+recursive+skipheaders]);

  /* printf (" afilename = %s", afilename); */
#ifdef WIN32
  /* have to define the file as binary */
  fmread = "rb+";
  fmwrite = "wb+";
#else
  fmread = "r+";
  fmwrite = "w+";
#endif

  
  if ((afile = fopen(afilename,fmread)) == NULL) { /* try to open for update */
    if ((afile = fopen(afilename,fmwrite)) == NULL) {
      fprintf(LOGFILE, "unable to open %s\n",afilename);
      exit(1);
    }
  }

  if (recursive) {
    /* open a file for generating continuation entries */
    sprintf(cfilename,"%s.cont",argv[1+quiet+recursive+skipheaders]);
    if ((cfile = fopen(cfilename,fmread)) == NULL) { /* try to open for update */
      if ((cfile = fopen(cfilename,fmwrite)) == NULL) {
	fprintf(LOGFILE, "unable to open %s\n",cfilename);
	exit(1);
      } else {
	/* new file -- create empty hash table */
	ContNamesHash = CALLOC(Tcl_HashTable,1);
	Tcl_InitHashTable(ContNamesHash,TCL_STRING_KEYS);
      }
    } else {
      /* parse the EXISTING continuation input file */
      fseek(cfile, 0, SEEK_SET);
      cont_restart_scanner(cfile);
      CONTparse();
      ContNamesHash = CALLOC(Tcl_HashTable,1);
      Tcl_InitHashTable(ContNamesHash,TCL_STRING_KEYS);

      for (cont = first_cont; cont; cont = cont->next_cont) {
	/* printf("CONT FILE NAME IS: %s \n", cont->name); */
	/* build hash entries for name */	  
	Tcl_SetHashValue(
			 Tcl_CreateHashEntry(
					     ContNamesHash,
					     cont->name,
					     &exists),
			 (ClientData)cont);
       if (cfilenum < cont->id_number)
	 cfilenum = cont->id_number;
      }

      /* there is an existing file -- go to the end */
      fseek(cfile, 0, SEEK_END);
    }
  }

  high_recno = 0;
  total_doc_length = 0;
  /* get new highest logical record number */
  fseek(afile, 0, 0);
  fread(&high_recno,sizeof(int),1, afile); 
  fread(&total_doc_length,sizeof(int),1, afile); /* Should be doclent */ 
  recno = high_recno;

  if (high_recno > 0) {
   printf ("Appending to existing associator file %s... start record #%d\n", 
	   afilename, high_recno+1); 
   fseek(afile,recno*sizeof(assoc_rec), 0);
   fread(&assocrec, sizeof(assoc_rec), 1, afile);
   offset = assocrec.offset + assocrec.recsize;
  } 
  else
    offset = 0;        /* address in marc file */



  tag = argv[argc-1];
  tag_length = strlen(tag);

  if (!recursive) {
    int seekresult, writeresult, flushresult;

    while ((result = get_next_sgmlrec_data(&offset, 
					   argv[1+quiet+recursive+skipheaders],
					   tag, tag_length, skipheaders)) != 0) {
      recno++;
      if (!quiet)
	printf ("Record #%08d: Length %08d\n",recno, result);
      
      /* record offset and length of sgml record in assoc file */
      assocrec.offset = offset ;
      assocrec.recsize = result;
      total_doc_length += result;
      seekresult = fseek(afile,recno*sizeof(assoc_rec), SEEK_SET);
      writeresult = fwrite(&assocrec, sizeof(assoc_rec), 1, afile);
      flushresult = fflush(afile);
    }

    printf("End of File encountered after record %d\n", recno);

    get_next_sgmlrec_data(NULL,NULL,NULL, 0, 0); /* closes file */
    
    /* increment the zeroth record to record the */
    /* highest record number now in use          */
    fseek(afile, 0, 0);
    fwrite(&recno, sizeof(int), 1, afile);
    fwrite(&total_doc_length, sizeof(int), 1, afile);
    fclose(afile);
  }
  else {
    /* Process a directory tree recursively looking for sgml tags */
    /* that match the one provided...                             */
    /* the filename provided should be a directory                */
    process_directory(afile, cfile, ContNamesHash, &recno, &total_doc_length, 
		      &cfilenum, argv[1+quiet+recursive+skipheaders], 
		      tag, tag_length, quiet, skipheaders);
    

    get_next_sgmlrec_data(NULL,NULL,NULL, 0, 0); /* closes file */
    
    /* increment the zeroth record to record the */
    /* highest record number now in use          */
    fseek(afile, 0, 0);
    fwrite(&recno, sizeof(int), 1, afile);
    fwrite(&total_doc_length, sizeof(int), 1, afile);
    fclose(afile);
  }
  return 0;

}
Beispiel #25
0
/** process_directory
 * A recursive fuction that processes all directories
 * 
 * Parameters:
 *     struct Filename *file - the names associated with the file
 */
void*
process_directory(void *val){
	DIR *dptr;
	struct dirent *entry;
	struct dirent *ent_buf;
	struct Thread_args *ta;
	
	unsigned int my_flags;
	int max_depth;
	int path_max;
	
	ta = malloc(sizeof(struct Thread_args));
	if(ta == NULL){
		exit(EXIT_FAILURE);
	}
	ta = (struct Thread_args*)val;
	
	my_flags = ta->gl->my_flags;
	max_depth = ta->gl->max_depth;
	path_max = ta->gl->path_max;
	
	errno = 0;
	if((dptr = opendir(ta->fe->file->realptr)) == NULL){
		/* If the file was not opened successfully then print an error and 
		   move on to the next file */
		if(errno != 0){
			/* If an error occurred opening the file then print a message */
			if(ta->fe->file->is_cmd_line || (my_flags&QUIET) != QUIET){
				/* If the file was specified on the commandline or if the -q
	           	   flag was not selected then print the error */
				pthread_mutex_lock(&mu);
				if(ta->gl->is_network){
					char *output;

					output = calloc(sizeof(char), ta->gl->path_max);
					sprintf(output, "%s: %s\n", strerror(errno), ta->fe->file->name);
					write_error_line(output, ta->gl);
					free(output);
				}
				fprintf(stderr, "%s: %s\n", strerror(errno), ta->fe->file->name);
				pthread_mutex_unlock(&mu);
			}
			else{
				/* If the file error was not printed then increment the 
			   	   corresponding counter */
				ta->fe->file->counters->err_not_printed++;
			}
			if(ta->fe->file->counters->num_recurse == 0){
				pthread_mutex_lock(&mu);
				(*(ta->gl->num_threads))--;
				pthread_mutex_unlock(&mu);
			}
			ta->fe->file->counters->num_recurse--;
			check_print_counters(ta->fe, ta->gl);
			return NULL;
		}
	}
	
	if(deal_with_cstack(ta->fe, dptr, ta->gl) == FAILURE){
		/* If an error occurred adding the directory to the stack then return */
		if(ta->fe->file->counters->num_recurse == 0){
			pthread_mutex_lock(&mu);
			(*(ta->gl->num_threads))--;
			pthread_mutex_unlock(&mu);
		}
		ta->fe->file->counters->num_recurse--;
		check_print_counters(ta->fe, ta->gl);
		return NULL;
	}
	
	ent_buf = malloc(/*sizeof(struct dirent)*/path_max);
	if(ent_buf == NULL){
		/* If memory allocation failed, print an error */
		exit(EXIT_FAILURE);
	}
	
	while(1){
		int status;
		struct Filename *newfile;
		
		readdir_r(dptr, ent_buf, &entry);
		if(entry == NULL){
			break;
		}

		if(entry->d_name[0] == '.'){
			/* Handle hidden files separately */
			if((my_flags&DO_DOTS) == DO_DOTS){
				/* Handles the -a flag if it was selected */
				if(strcmp("..", entry->d_name) == 0 
						|| strcmp(".", entry->d_name) == 0){
					/* If the hidden directory is . or .. then ignore it */
					continue;
				}
				ta->fe->file->counters->dot_processed++;
			}
			else{
				/* If the -a flag wasn't selected then ignore the hidden file */
				continue;
			}
		}
		
		newfile = malloc(sizeof(struct Filename));
		if(newfile == NULL){
			/* If memory allocation failed, print an error */
			exit(EXIT_FAILURE);
		}
		newfile->name = malloc(path_max);
		newfile->realptr = malloc(path_max);
		newfile->fullptr = malloc(path_max);
		if(newfile->name == NULL || newfile->realptr == NULL || newfile->fullptr == NULL){
			/* If memory allocation failed, print an error */
			exit(EXIT_FAILURE);
		}
		strcpy(newfile->realptr, ta->fe->file->realptr);
		strcpy(newfile->name, entry->d_name);
		newfile->is_cmd_line = false;
		
		get_fullpath(newfile, &newfile->fullptr, ta->gl);
		if(newfile->fullptr == NULL){
			/* Continue onto the next file if there was a failure getting the 
			   realpath of this one */
			combine_counters(newfile->counters, ta->gl);
			continue;
		}
		
		newfile->counters = NULL;
		initialize_counters(&(newfile->counters));
		
		if(handle_link(newfile, ta->gl) == true){
			/* Try to handle a link. */
			combine_counters(newfile->counters, ta->gl);
			continue;
		}
		
		status = is_directory(newfile->fullptr, newfile, ta->gl);
		if(status == 1){
			/* Processes another directory */
			struct Thread_args *newta;
			pthread_t threadid;
			DIR *newdptr;

			newta = malloc(sizeof(struct Thread_args));
			if(newta == NULL){
				exit(EXIT_FAILURE);
			}
	
			newta->gl = malloc(sizeof(struct Globals));
			if(newta->gl == NULL){
				exit(EXIT_FAILURE);
			}
			
			/*****HERE UPDATE*****/
			newta->gl->my_flags = ta->gl->my_flags;
			newta->gl->num_chars = ta->gl->num_chars;
			newta->gl->max_lines = ta->gl->max_lines;
			newta->gl->max_depth = ta->gl->max_depth;
			newta->gl->path_max = ta->gl->path_max;
			newta->gl->allowed_threads = ta->gl->allowed_threads;
			newta->gl->num_threads = &(*(ta->gl->num_threads));
			newta->gl->machine = &(*(ta->gl->machine));
			newta->gl->is_printed = &(*(ta->gl->is_printed));
			newta->gl->final_counters = &(*(ta->gl->final_counters));
			newta->gl->donecmdln = &(*(ta->gl->donecmdln));
			newta->gl->is_network = ta->gl->is_network;
			newta->gl->num_networking = &(*(ta->gl->num_networking));
			newta->gl->fd = ta->gl->fd;
			
			newta->fe = malloc(sizeof(struct elem));
			if(newta->fe == NULL){
				exit(EXIT_FAILURE);
			}
			
			strcpy(newfile->realptr, ta->fe->file->name);
			if(newfile->realptr[strlen(newfile->realptr)-1] != '/')
				strcat(newfile->realptr, "/");
			strcat(newfile->realptr, entry->d_name);
			strcpy(newfile->name, newfile->realptr);
			
			free(newfile->realptr);
			get_realpath(newfile, &newfile->realptr, ta->gl);
			if(newfile->realptr == NULL){
				/* Continue onto the next file if there was a failure getting the 
				   realpath of this one */
				combine_counters(newfile->counters, newta->gl);
				continue;
			}
			
			pthread_mutex_lock(&mu);
			cstack_add(newfile, ta->fe, &newta->fe);
			pthread_mutex_unlock(&mu);
			
			errno = 0;
			if((newdptr = opendir(newta->fe->file->realptr)) == NULL){
				/* If the file was not opened successfully then print an error and 
				   move on to the next file */
				if(errno != 0){
					/* If an error occurred opening the file then print a message */
					if(newta->fe->file->is_cmd_line || (my_flags&QUIET) != QUIET){
						/* If the file was specified on the commandline or if the -q
			           	   flag was not selected then print the error */
						pthread_mutex_lock(&mu);
						if(newta->gl->is_network){
							char *output;

							output = calloc(sizeof(char), newta->gl->path_max);
							sprintf(output, "%s: %s\n", strerror(errno), newta->fe->file->name);
							write_error_line(output, newta->gl);
							free(output);
						}
						fprintf(stderr, "%s: %s\n", strerror(errno), newta->fe->file->name);
						pthread_mutex_unlock(&mu);
					}
					else{
						/* If the file error was not printed then increment the 
					   	   corresponding counter */
						newta->fe->file->counters->err_not_printed++;
					}
					if(newta->fe->file->counters->num_recurse == 0){
						pthread_mutex_lock(&mu);
						(*(ta->gl->num_threads))--;
						pthread_mutex_unlock(&mu);
					}
					combine_counters(newfile->counters, newta->gl);
					check_print_counters(newta->fe, ta->gl);
					continue;
				}
			}
	
			if(deal_with_cstack(newta->fe, newdptr, ta->gl) == FAILURE){
				/* If an error occurred adding the directory to the stack then return */
				if(ta->fe->file->counters->num_recurse == 0){
					pthread_mutex_lock(&mu);
					(*(ta->gl->num_threads))--;
					pthread_mutex_unlock(&mu);
				}
				check_print_counters(newta->fe, ta->gl);
				continue;
			}
			newta->fe->file->counters->dr_opened--;
			
			if(max_depth == DEFAULT_DEPTH || ta->fe->file->counters->max_depth < max_depth){
				if(*(newta->gl->num_threads) < newta->gl->allowed_threads || newta->gl->allowed_threads == DEFAULT_ALLOWED_THREADS){
					if((status = pthread_create(&threadid, NULL, process_directory, (void*)newta))){
						if(newta->gl->is_network){
							char *output;

							output = calloc(sizeof(char), newta->gl->path_max);
							sprintf(output, "Could not create thread: %s\n", strerror(status));
							write_error_line(output, newta->gl);
							free(output);
						}
						fprintf(stderr, "Could not create thread: %s\n", strerror(status));
						newta->fe->file->counters->num_recurse = ta->fe->file->counters->num_recurse + 1;
						process_directory((void*)newta);
					}
					else{
						pthread_mutex_lock(&mu);
						(*(ta->gl->num_threads))++;
						if(*(ta->gl->num_threads) > ta->fe->file->counters->max_dt_created)
							ta->fe->file->counters->max_dt_created = *(ta->gl->num_threads);
						pthread_mutex_unlock(&mu);
						pthread_detach(threadid);
						ta->fe->file->counters->num_dt_created++;
					}
				}
				else{
					if((my_flags&QUIET) != QUIET){
						/* If the file was specified on the commandline or if the -q
			           	   flag was not selected then print the error */
						if(ta->gl->is_network){
							char *output;

							output = calloc(sizeof(char), ta->gl->path_max);
							sprintf(output, "Descent thread pruned due to a -t%d flag\n", newta->gl->allowed_threads);
							write_error_line(output, ta->gl);
							free(output);
						}
						fprintf(stderr, "Descent thread pruned due to a -t%d flag\n", newta->gl->allowed_threads);
					}
					else{
						/* If the file error was not printed then increment the 
					   	   corresponding counter */
						ta->fe->file->counters->err_not_printed++;
					}
						
					ta->fe->file->counters->num_dt_notcreated++;
					newta->fe->file->counters->num_recurse = ta->fe->file->counters->num_recurse + 1;
					process_directory((void*)newta);
				}
			}
			else{
				process_directory((void*)newta);
			}
		}
		else if(status == 0){
			/* Else process the entry as a file */
			strcpy(newfile->name, newfile->fullptr);
			process_file(newfile, ta->gl);
			combine_counters(newfile->counters, ta->gl);
		}
	}
	
	if(ta->fe->file->counters->num_recurse == 0){
		pthread_mutex_lock(&mu);
		(*(ta->gl->num_threads))--;
		pthread_mutex_unlock(&mu);
	}
	ta->fe->file->counters->num_recurse--;
	closedir(dptr);
	check_print_counters(ta->fe, ta->gl);
	return NULL;
	/*process_directory*/
}
static int process_directory(int parent, const char *path, int fixstats)
{

	DIR *dir;
	struct dirent *entry;
	char *secontext = NULL;

	nDirectories++;
	
	dir = opendir(path);
	
	if(dir)
	{
		while((entry = readdir(dir)) != NULL)
		{
		
			/* Ignore . and .. */
			if(strcmp(entry->d_name,".") &&
			   strcmp(entry->d_name,".."))
 			{
 				char full_name[500];
				char *suffix, dest_name[500];
				int ret;
				struct stat stats;
				int equivalentObj;
				int newObj;
				
				sprintf(full_name,"%s/%s",path,entry->d_name);
				
				lstat(full_name,&stats);

				if (sehnd) {
					suffix = full_name + seprefixlen;
					ret = snprintf(dest_name,
						       sizeof dest_name,
						       "%s%s", mntpoint,
						       suffix);
					if (ret < 0 ||
					    (size_t) ret >= sizeof dest_name) {
						fprintf(stderr,
							"snprintf failed on %s%s\n",
							mntpoint, suffix);
						exit(1);
					}

					char *sepath = NULL;
					if (dest_name[0] == '/')
					        sepath = strdup(dest_name);
					else if (asprintf(&sepath, "/%s", dest_name) < 0)
                                                sepath = NULL;

					if (!sepath) {
					        perror("malloc");
					        exit(1);
					}

					if (selabel_lookup(sehnd, &secontext,
							   sepath,
							   stats.st_mode) < 0) {
					        perror("selabel_lookup");
					        free(sepath);
					        exit(1);
					}
					free(sepath);
				}

				if(S_ISLNK(stats.st_mode) ||
				    S_ISREG(stats.st_mode) ||
				    S_ISDIR(stats.st_mode) ||
				    S_ISFIFO(stats.st_mode) ||
				    S_ISBLK(stats.st_mode) ||
				    S_ISCHR(stats.st_mode) ||
				    S_ISSOCK(stats.st_mode))
				{
				
					newObj = obj_id++;
					nObjects++;

                    if (fixstats) {
                        fix_stat(full_name, &stats);
                    }

					//printf("Object %d, %s is a ",newObj,full_name);
					
					/* We're going to create an object for it */
					if((equivalentObj = find_obj_in_list(stats.st_dev, stats.st_ino)) > 0)
					{
					 	/* we need to make a hard link */
					 	//printf("hard link to object %d\n",equivalentObj);
						error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_HARDLINK, &stats, parent, entry->d_name, equivalentObj, NULL, secontext);
					}
					else 
					{
						
						add_obj_to_list(stats.st_dev,stats.st_ino,newObj);
						
						if(S_ISLNK(stats.st_mode))
						{
					
							char symname[500];
						
							memset(symname,0, sizeof(symname));
					
							readlink(full_name,symname,sizeof(symname) -1);
						
							//printf("symlink to \"%s\"\n",symname);
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SYMLINK, &stats, parent, entry->d_name, -1, symname, secontext);

						}
						else if(S_ISREG(stats.st_mode))
						{
							//printf("file, ");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_FILE, &stats, parent, entry->d_name, -1, NULL, secontext);

							if(error >= 0)
							{
								int h;
								__u8 bytes[chunkSize];
								int nBytes;
								int chunk = 0;
								
								h = open(full_name,O_RDONLY);
								if(h >= 0)
								{
									memset(bytes,0xff,sizeof(bytes));
									while((nBytes = read(h,bytes,sizeof(bytes))) > 0)
									{
										chunk++;
										write_chunk(bytes,newObj,chunk,nBytes);
										memset(bytes,0xff,sizeof(bytes));
									}
									if(nBytes < 0) 
									   error = nBytes;
									   
									//printf("%d data chunks written\n",chunk);
								}
								else
								{
									perror("Error opening file");
								}
								close(h);
								
							}							
														
						}
						else if(S_ISSOCK(stats.st_mode))
						{
							//printf("socket\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL, secontext);
						}
						else if(S_ISFIFO(stats.st_mode))
						{
							//printf("fifo\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL, secontext);
						}
						else if(S_ISCHR(stats.st_mode))
						{
							//printf("character device\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL, secontext);
						}
						else if(S_ISBLK(stats.st_mode))
						{
							//printf("block device\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_SPECIAL, &stats, parent, entry->d_name, -1, NULL, secontext);
						}
						else if(S_ISDIR(stats.st_mode))
						{
							//printf("directory\n");
							error =  write_object_header(newObj, YAFFS_OBJECT_TYPE_DIRECTORY, &stats, parent, entry->d_name, -1, NULL, secontext);
// NCB modified 10/9/2001				process_directory(1,full_name);
							process_directory(newObj,full_name,fixstats);
						}
					}
				}
				else
				{
					//printf(" we don't handle this type\n");
				}
			}
		}
		closedir(dir);
	}
	
	return 0;

}
int main(int argc, char *argv[])
{
	int fixstats = 0;
	struct stat stats;
	int opt;
	char *image;
	char *dir;
	char *secontext = NULL;

	while ((opt = getopt(argc, argv, "fc:s:")) != -1) {
		switch (opt) {
		case 'f':
			fixstats = 1;
			break;
		case 'c':
			chunkSize = (unsigned)strtoul(optarg, NULL, 0);
			break;
		case 's':
			spareSize = (unsigned)strtoul(optarg, NULL, 0);
			break;
		default:
			usage();
			exit(1);
		}
	}

	if (!chunkSize || !spareSize) {
		usage();
		exit(1);
	}

	if ((argc - optind < 2) || (argc - optind > 4)) {
		usage();
		exit(1);
	}

	dir = argv[optind];
	seprefixlen = strlen(dir);
	image = argv[optind + 1];

	if (optind + 2 < argc) {
		if (!strncmp(argv[optind + 2], "convert", strlen("convert")))
			convert_endian = 1;
		else {
			struct selinux_opt seopts[] = {
				{ SELABEL_OPT_PATH, argv[optind + 2] }
			};
			sehnd = selabel_open(SELABEL_CTX_FILE, seopts, 1);
			if (!sehnd) {
				perror(argv[optind + 2]);
				usage();
				exit(1);
			}
			if (optind + 3 >= argc) {
				usage();
				exit(1);
			}
			mntpoint = argv[optind + 3];
			if (optind + 4 < argc) {
				if (!strncmp(argv[optind + 4], "convert", strlen("convert")))
					convert_endian = 1;
			}
		}
	}

	if(stat(dir,&stats) < 0)
	{
		fprintf(stderr,"Could not stat %s\n",dir);
		exit(1);
	}
	
	if(!S_ISDIR(stats.st_mode))
	{
		fprintf(stderr," %s is not a directory\n",dir);
		exit(1);
	}
	
	outFile = open(image,O_CREAT | O_TRUNC | O_WRONLY, S_IREAD | S_IWRITE);
	
	
	if(outFile < 0)
	{
		fprintf(stderr,"Could not open output file %s\n",image);
		exit(1);
	}

    if (fixstats) {
        int len = strlen(dir);
        
        if((len >= 4) && (!strcmp(dir + len - 4, "data"))) {
            source_path_len = len - 4;
        } else if((len >= 6) && (!strcmp(dir + len - 6, "system"))) {
            source_path_len = len - 6;
        } else {            
            fprintf(stderr,"Fixstats (-f) option requested but filesystem is not data or android!\n");
            exit(1);
        }
        fix_stat(dir, &stats);
    }
    
	//printf("Processing directory %s into image file %s\n",dir,image);
    if (sehnd) {

        char *sepath = NULL;
        if (mntpoint[0] == '/')
	    sepath = strdup(mntpoint);
        else if (asprintf(&sepath, "/%s", mntpoint) < 0)
            sepath = NULL;

        if (!sepath) {
	    perror("malloc");
	    exit(1);
	}

	if (selabel_lookup(sehnd, &secontext, sepath, stats.st_mode) < 0) {
	    perror("selabel_lookup");
	    free(sepath);
	    exit(1);
	}

	free(sepath);
    }

    error =  write_object_header(1, YAFFS_OBJECT_TYPE_DIRECTORY, &stats, 1,"", -1, NULL, secontext);
	if(error)
	error = process_directory(YAFFS_OBJECTID_ROOT,dir,fixstats);
	
	close(outFile);
	
	if(error < 0)
	{
		perror("operation incomplete");
		exit(1);
	}
	else
	{
        /*
		printf("Operation complete.\n"
		       "%d objects in %d directories\n"
		       "%d NAND pages\n",nObjects, nDirectories, nPages);
        */
	}
	
	close(outFile);
	
	exit(0);
}	
Beispiel #28
0
/* Linux version */
static void
process_directory (char *path, char *cvspath)
{
  DIR *dirp;
  struct dirent *entry;
  struct stat stbuf;
  char buf[MAX_PATH];
  char newcvspath[MAX_PATH];

#ifdef HAVE_D_TYPE
  dirp = opendir(path);
  if (dirp != NULL)
    {
      while ((entry = readdir(dirp)) != NULL)
        {
          if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue; // skip self and parent

      	  if (entry->d_type == DT_REG) // normal file
      	    {
              // Check for an absolute path
              if (path[0] == DIR_SEPARATOR_CHAR)
                {
                  strcpy(buf, path);
                  strcat(buf, DIR_SEPARATOR_STRING);
                  strcat(buf, entry->d_name);
                }
              else
                {
                  if (!getcwd(buf, sizeof(buf)))
                    {
                      printf("Can't get CWD: %s\n", strerror(errno));
                      return;
                    }
                  strcat(buf, DIR_SEPARATOR_STRING);
                  strcat(buf, path);
                  strcat(buf, entry->d_name);
                }

      	      if (stat(buf, &stbuf) == -1)
                {
                  printf("Can't access '%s' (%s)\n", buf, strerror(errno));
                  return;
                }

              if (S_ISDIR(stbuf.st_mode))
          	    {
                  strcpy(newcvspath, cvspath);
                  strcat(newcvspath, f.name);
                  strcat(newcvspath, "/");

                  process_directory(buf, newcvspath);
                  continue;
          	    }

              /* Must be a .c file */
              if (!is_valid_file(buf))
                {
                  continue;
                }

              parse_file(buf, cvspath, entry->d_name);
           }
      }
      closedir(dirp);
    }
  else
    {
      printf("Can't open %s\n", path);
      exit(1);
    }

#else

  dirp = opendir(path);
  if (dirp != NULL)
    {
      while ((entry = readdir(dirp)) != NULL)
      	{
          if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue; // skip self and parent

          // Check for an absolute path
          if (path[0] == DIR_SEPARATOR_CHAR)
            {
              strcpy(buf, path);
              strcat(buf, DIR_SEPARATOR_STRING);
              strcat(buf, entry->d_name);
            }
          else
            {
              if (!getcwd(buf, sizeof(buf)))
                {
                  printf("Can't get CWD: %s\n", strerror(errno));
                  return;
                }
              strcat(buf, DIR_SEPARATOR_STRING);
              strcat(buf, path);
              strcat(buf, entry->d_name);
            }

          if (stat(buf, &stbuf) == -1)
            {
              printf("Can't access '%s' (%s)\n", buf, strerror(errno));
              return;
            }

          if (S_ISDIR(stbuf.st_mode))
      	    {
              strcpy(newcvspath, cvspath);
              strcat(newcvspath, entry->d_name);
              strcat(newcvspath, "/");

              process_directory(buf, newcvspath);
              continue;
      	    }

          /* Must be a .c file */
          if (!is_valid_file(buf))
            {
              continue;
            }

          parse_file(buf, cvspath, entry->d_name);
        }
      closedir(dirp);
    }
  else
    {
      printf("Can't open %s\n", path);
      exit(1);
    }

#endif
}
void add_i2c_tunables(void)
{
	process_directory("/sys/bus/i2c/devices/", add_i2c_callback);
}
Beispiel #30
0
static void
read_input_file(char *input_file)
{
  char component_name[MAX_PATH];
  char component_path[MAX_PATH];
  char *canonical_path;
  unsigned int index;
  unsigned int start;
  PAPI_INFO api_info;
  PAPI_INFO next_api_info;
  char *buffer;
  unsigned int size;
  int len;

  in = fopen(input_file, "rb");
  if (in == NULL)
    {
    	printf("Cannot open input file");
    	exit(1);
    }

  // Get the size of the file
  fseek(in, 0, SEEK_END);
  size = ftell(in);

  // Load it all into memory
  buffer = malloc(size);
  if (buffer == NULL)
    {
      fclose(in);
      printf("Out of memory\n");
      exit(1);
    }
  fseek(in, 0, SEEK_SET);
  if (fread (buffer, 1, size, in) < 1)
    {
      fclose(in);
      printf("Read error in file %s\n", input_file);
      exit(1);
    }

  index = 0;

  write_line("<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>");
  write_line("<?xml-stylesheet type=\"text/xsl\" href=\"rapistatus.xsl\"?>");
  write_line("");
  write_line("<components>");

  while (1)
    {
      /* Free previous list */
      for (api_info = api_info_list; api_info != NULL; api_info = next_api_info)
        {
          next_api_info = api_info->next;
          free(api_info);
        }
      api_info_list = NULL;

      /* Skip whitespace and eol characters */
      while ((index < size) && (is_whitespace(buffer[index]) || (is_eol_char(buffer[index]))))
          index++;
      if ((file_pointer < size) && (buffer[index] == '\n'))
          index++;

      if (buffer[index] == ';')
        {
          /* Skip comments */
          while ((index < size) && (!is_eol_char(buffer[index])))
              index++;
          if ((index < size) && (buffer[index] == '\n'))
              index++;
          continue;
        }

      /* Get component name */
      start = index;
      while ((index < size) && (!is_whitespace(buffer[index])))
          index++;
      if (index >= size)
          break;

      len = index - start;
      strncpy(component_name, &buffer[start], len);
      component_name[len] = 0;

      /* Skip whitespace */
      while ((index < size) && (is_whitespace(buffer[index])))
          index++;
      if (index >= size)
          break;

      /* Get component path */
      start = index;
      while ((index < size) && (!is_whitespace(buffer[index]) && !is_eol_char(buffer[index])))
          index++;

      len = index - start;
      strncpy(component_path, &buffer[start], len);
      component_path[len] = 0;

      /* Append directory separator if needed */
      if (component_path[strlen(component_path)] != DIR_SEPARATOR_CHAR)
        {
          int i = strlen(component_path);
          component_path[strlen(component_path)] = DIR_SEPARATOR_CHAR;
          component_path[i + 1] = 0;
        }

      /* Skip to end of line */
      while ((index < size) && (!is_eol_char(buffer[index])))
          index++;
      if ((index < size) && (buffer[index] == '\n'))
          index++;

      canonical_path = convert_path(component_path);
      if (canonical_path != NULL)
        {
          process_directory(canonical_path, canonical_path);
          free(canonical_path);
          generate_xml_for_component(component_name,
	                             component_path);
        }
    }

  write_line("</components>");
}