Exemplo n.º 1
0
/* Free resources for a given file descriptor struct.
   Walk the FP_TABLE to decrement numActive for the given file.
   If numActive == 0, close the file and remove the fp_info.
*/
static void free_fdm (struct fdm_info *fdm) 
{
  struct file* fp = fdm->fp;
  free(fdm);

  struct fpm_info *fpm = fpm_from_fp(fp);
  if(fpm == NULL) {
    return;
  }
  fpm->num_active--;
  if(fpm->num_active == 0) {
    // No remaining file descriptors for file; free and close.
    // Must rewalk the list to find previous element and patch.
    struct fpm_info *prev_fpm = fm->fp_map[hash_file(fp)];
    if(prev_fpm == fpm) {
      fm->fp_map[hash_file(fp)] = fpm->next;
    } else { 
      while(prev_fpm->next) {
        if(prev_fpm->next == fpm) {
          prev_fpm->next = fpm->next;
          break;
        }
        prev_fpm = prev_fpm->next;
      }
    }
    file_close (fpm->fp);
    free(fpm);
  }
}
Exemplo n.º 2
0
    virtual ssize_t hash_file
    (const entry_t& source, hash_t& target, char block[]) {
        const char_t* chars = 0;
        size_t length = 0;

        if ((chars = source.path(length)) && (0 < length)) {
            source_file_t source_file;

            EV_LOG_MESSAGE_INFO("open source file \"" << chars << "\"...");
            if ((source_file.open(chars, source_file.mode_read_binary()))) {
                EV_LOG_MESSAGE_INFO("...opened source file \"" << chars << "\"");

                if (0 < (length = hash_file(source_file, target, block))) {
                }

                EV_LOG_MESSAGE_INFO("close source file \"" << chars << "\"...");
                if ((source_file.close())) {
                    EV_LOG_MESSAGE_INFO("...closed source file \"" << chars << "\"");
                    return length;
                } else {
                    EV_LOG_MESSAGE_INFO("...failed to close source file \"" << chars << "\"");
                }
            } else {
                EV_LOG_MESSAGE_ERROR("...failed to open source file \"" << chars << "\"");
            }
        }
        return 0;
    }
Exemplo n.º 3
0
static void randomness_from_files(struct mcookie_control *ctl)
{
	size_t i;

	for (i = 0; i < ctl->nfiles; i++) {
		const char *fname = ctl->files[i];
		size_t count;
		int fd;

		if (*fname == '-' && !*(fname + 1))
			fd = STDIN_FILENO;
		else
			fd = open(fname, O_RDONLY);

		if (fd < 0) {
			warn(_("cannot open %s"), fname);
		} else {
			count = hash_file(ctl, fd);
			if (ctl->verbose)
				fprintf(stderr,
					P_("Got %zu byte from %s\n",
					   "Got %zu bytes from %s\n", count),
					count, fname);

			if (fd != STDIN_FILENO)
				if (close(fd))
					err(EXIT_FAILURE,
					    _("closing %s failed"), fname);
		}
	}
}
Exemplo n.º 4
0
static void hash_dir( int out, const char *path )
{
    DIR *dir;
    struct dirent *entry;

    dir = rb->opendir( path );
    if( dir )
    {
        while( !quit && ( entry = rb->readdir( dir ) ) )
        {
            char childpath[MAX_PATH];
            rb->snprintf( childpath, MAX_PATH, "%s/%s",
                          rb->strcmp( path, "/" ) ? path : "", entry->d_name );
            if( entry->attribute & ATTR_DIRECTORY )
            {
                if( rb->strcmp( entry->d_name, "." )
                    && rb->strcmp( entry->d_name, ".." ) )
                {
                    /* Got a sub directory */
                    hash_dir( out, childpath );
                }
            }
            else
            {
                /* Got a file */
                hash_file( out, childpath );
            }
        }
        rb->closedir( dir );
    }
}
Exemplo n.º 5
0
static void sign_file(const char *fname, rsa_key *key, prng_state *prng, const int prng_index, const int hash_index)
{
    const size_t sigfnamelen = strlen(fname) + 5;
    char *sigfname = (char *) malloc(sigfnamelen);
    unsigned char hash[256];
    unsigned long hashlen = sizeof (hash);
    unsigned char sig[1024];
    unsigned long siglen = sizeof (sig);
    int rc = 0;
    int status = 0;

    if (!sigfname) {
        fail("out of memory");
    }

    if ((rc = hash_file(hash_index, fname, hash, &hashlen)) != CRYPT_OK) {
        fail("hash_file for '%s' failed: %s", fname, error_to_string(rc));
    }

    if ((rc = rsa_sign_hash(hash, hashlen, sig, &siglen, prng, prng_index, hash_index, SALT_LEN, key)) != CRYPT_OK) {
        fail("rsa_sign_hash for '%s' failed: %s", fname, error_to_string(rc));
    }

    if ((rc = rsa_verify_hash(sig, siglen, hash, hashlen, hash_index, SALT_LEN, &status, key)) != CRYPT_OK) {
        fail("rsa_verify_hash for '%s' failed: %s", fname, error_to_string(rc));
    }

    if (!status) {
        fail("Generated signature isn't valid! Bug in the program!");
    }

    snprintf(sigfname, sigfnamelen, "%s.sig", fname);
    write_file(sigfname, sig, siglen);
    free(sigfname);
}
Exemplo n.º 6
0
/* Walk the FP_TABLE to find the fpm_info corresponding to fp.
   Return NULL if none are found. */
static struct fpm_info* fpm_from_fp (struct file *fp) 
{
  if (fp == NULL) return NULL;
  struct fpm_info * start = fm->fp_map[hash_file(fp)];
  while(start) {
    if(file_get_inode(start->fp) == file_get_inode(fp)) return start;
    start = start->next;
  }
  return NULL;
}
void main(int argc, char* argv[])
{	FILE *fp;
	fp=fopen(argv[1],"rb");
	struct hash hs;
	hs=hash_file(fp);
	//print_hash(&hs);
	char s[65];
	hash_to_hex_string(&hs,s);
	printf("Hash String:%s\n",s);
}
Exemplo n.º 8
0
void rehash(void)
{
    hash_file(oplist, "oplist.txt", HASHSIZE);
    hash_file(hoplist, "hoplist.txt", HASHSIZE);
    hash_file(voicelist, "voicelist.txt", HASHSIZE);
    hash_file(kicklist, "kicklist.txt", HASHSIZE);
    hash_file(masterlist, "masterlist.txt", MASTERSIZE);
    hash_file(calclist, "calclist.txt", CALCSIZE);
    hash_file(funclist, "functionlist.txt", FUNCSIZE);
}
Exemplo n.º 9
0
void hashtree_insert(HashTreeNode * tree, char *path, char *hash)
{
    unsigned int i = 2;         /* skip "./" */
    unsigned int j;
    unsigned int len;
    char found;
    HashTreeNode *current = tree;
    HashTreeNode *child;

    assert(tree != NULL);
    assert(path != NULL);

    len = strlen(path);

    while (i < len) {
        /* stop on the delimiter */
        if (path[i] != '/') {
            i++;
            continue;
        }

        path[i] = '\0';

        for (j = 0, found = 0; IS_VALID_CHILD(current, j); j++) {
            if (strcmp(current->children[j]->name, path) == 0) {
                /* found the path on the tree */
                current = current->children[j];
                found = 1;
                break;
            }
        }

        /* path not found, add it */
        if (!found) {
            child = hashtree_new_node(path);
            hashtree_append_child(current, child);
            current = child;
        }

        path[i] = '/';
        i++;
    }

    /* add the leaf node */
    child = hashtree_new_node(path);
    hashtree_append_child(current, child);

    if (hash == NULL)
        child->hash = hash_file(path);
    else
        child->hash = sstrdup(hash);
}
Exemplo n.º 10
0
/* Finds the corresponding entry for fp in the fp_map.
   Increments num_active, or creates a new entry if none exists.
   Adds a new fdm_info to the fd_map.
   Returns the new file descriptor.
*/
int get_new_fd (struct file *fp) 
{ 
  struct fdm_info * new_fdm = malloc(sizeof(struct fdm_info));
  if (new_fdm == NULL) return -1;

  lock_acquire (&(fm->file_map_lock));
  struct fpm_info * result = fpm_from_fp(fp);
  if(result == NULL) {  
    result = malloc(sizeof(struct fpm_info));
    if (result == NULL) {
      lock_release (&(fm->file_map_lock));
      free (new_fdm);
      return -1;
    }
    // No existing file descriptors, initialize new fpm_info
    result->fp = fp;
    result->inode = file_get_inode (fp);
    result->num_active = 0;
    result->next = fm->fp_map[hash_file(fp)];
    init_file_synch (&result->status); 
    
    fm->fp_map[hash_file(fp)] = result;
  }

  result->num_active++;
  int fd = fm->next_fd;
  
  // Create new fdm_info
  new_fdm->fp = fp;
  new_fdm->fd = fd;
  new_fdm->thread_id = thread_current ()->tid;
  new_fdm->next = fm->fd_map[fd % FD_TABLE_SIZE];
  fm->fd_map[fd % FD_TABLE_SIZE] = new_fdm;

  fm->next_fd++;
  lock_release (&(fm->file_map_lock));
  return fd;
}
Exemplo n.º 11
0
int main(int argc, char **argv)
{
   int idx, x, z;
   unsigned long w;
   unsigned char hash_buffer[MAXBLOCKSIZE];
   hash_state md;

   /* You need to register algorithms before using them */
   register_algs();
   if (argc < 2) {
      printf("usage: ./hash algorithm file [file ...]\n");
      printf("Algorithms:\n");
      for (x = 0; hash_descriptor[x].name != NULL; x++) {
         printf(" %s (%d)\n", hash_descriptor[x].name, hash_descriptor[x].ID);
      }
      exit(EXIT_SUCCESS);
   }

   idx = find_hash(argv[1]);
   if (idx == -1) {
      fprintf(stderr, "\nInvalid hash specified on command line.\n");
      return -1;
   }

   if (argc == 2) {
      hash_descriptor[idx].init(&md);
      do {
         x = fread(hash_buffer, 1, sizeof(hash_buffer), stdin);
         hash_descriptor[idx].process(&md, hash_buffer, x);
      } while (x == sizeof(hash_buffer));
      hash_descriptor[idx].done(&md, hash_buffer);
      for (x = 0; x < (int)hash_descriptor[idx].hashsize; x++) {
          printf("%02x",hash_buffer[x]);
      }
      printf("  (stdin)\n");
   } else {
      for (z = 2; z < argc; z++) {
         w = sizeof(hash_buffer);
         if ((errno = hash_file(idx,argv[z],hash_buffer,&w)) != CRYPT_OK) {
            printf("File hash error: %s\n", error_to_string(errno));
         } else {
             for (x = 0; x < (int)hash_descriptor[idx].hashsize; x++) {
                 printf("%02x",hash_buffer[x]);
             }
             printf("  %s\n", argv[z]);
         }
      }
   }
   return EXIT_SUCCESS;
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
  struct rsa_public_key key;
  struct sha1_ctx hash;
  mpz_t s;
  
  if (argc != 3)
    {
      werror("Usage: rsa-verify PUBLIC-KEY SIGNATURE-FILE < FILE\n");
      return EXIT_FAILURE;
    }

  rsa_public_key_init(&key);
  
  if (!read_rsa_key(argv[1], &key, NULL))
    {
      werror("Invalid key\n");
      return EXIT_FAILURE;
    }

  mpz_init(s);

  if (!read_signature(argv[2], s))
    {
      werror("Failed to read signature file `%s'\n",
	      argv[2]);
      return EXIT_FAILURE;
    }
  
  sha1_init(&hash);
  if (!hash_file(&nettle_sha1, &hash, stdin))
    {
      werror("Failed reading stdin: %s\n",
	      strerror(errno));
      return 0;
    }

  if (!rsa_sha1_verify(&key, &hash, s))
    {
      werror("Invalid signature!\n");
      return EXIT_FAILURE;
    }
    
  mpz_clear(s);
  rsa_public_key_clear(&key);

  return EXIT_SUCCESS;
}
Exemplo n.º 13
0
int main(int argc, char* argv[]) {
	unsigned char hash_buffer[EVP_MAX_MD_SIZE];
	unsigned int hash_length;
  if(!argv[1]) {
    printf("Usage: mdtest digestname filename\n");
	  exit(1);
	}
	if(hash_file(argv[1], hash_buffer, &hash_length) == 0)
	{
		print_hash(hash_buffer, &hash_length);
	}else{
		printf("There was an error hashing your file (%s)\n", strerror(errno));
	}
	return 0;
}
Exemplo n.º 14
0
std::string hash_rom(HashFunc * hf, boost::filesystem::path path)
{
	std::streampos size;
	boost::filesystem::path ext;
	std::ifstream file (path.string(), std::ios::binary | std::ios::ate);
	if (file.is_open())
	{
		size = file.tellg();
		ext = path.extension();
		switch (decoders[ext.string()])
		{
			case DEC_BINARY:
				return hash_file(hf, file, 0);
			case DEC_SNES:
				if (size % 1024 == 512)
					return hash_file(hf, file, 512);
				else
					return hash_file(hf, file, 0);
				break;
			case DEC_MGD:
				return hash_block(hf, file, (size_t)size, deinterleave);
			case DEC_SMD:
				return hash_block(hf, file, 16384, deinterleave);
			case DEC_LNX:
				return hash_file(hf, file, 64);
			case DEC_N64:
				return hash_n64(hf, file);
			case DEC_NES:
				return hash_nes(hf, file);
			case DEC_NOT_DEF:
				return "";
		}
		file.close();
	}
	return "";
}
Exemplo n.º 15
0
/* create hash from file */
ASHash *as_hash_file (const char *file)
{
	ASHash *hash;

	if (!(hash = as_hash_create (NULL, 0)))
		return NULL;

	if (!hash_file (hash, file))
	{
		as_hash_free (hash);
		return NULL;
	}

	return hash;
}
Exemplo n.º 16
0
static int hash_dir(const char *dirname)
{
	struct dirent *de;
	struct stat st;
	int dirfd;
	DIR *d;

	fprintf(stdout, "Doing %s\n", dirname);
	dirfd = open(dirname, O_RDONLY | O_DIRECTORY);
	if (dirfd < 0) {
		perror(dirname);
		return -1;
	}
	d = opendir(dirname);
	if (!d) {
		close(dirfd);
		return -1;
	}
	while ((de = readdir(d)) != NULL) {
		if (fstatat(dirfd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
			continue;
		if (!S_ISLNK(st.st_mode))
			continue;
		if (!is_hash_filename(de->d_name))
			continue;

		if (unlinkat(dirfd, de->d_name, 0) < 0)
			perror(de->d_name);
	}

	rewinddir(d);
	while ((de = readdir(d)) != NULL) {
		if (fnmatch("*.pem", de->d_name, FNM_NOESCAPE) == 0)
			hash_file(dirfd, de->d_name);
	}
	closedir(d);

	return 0;
}
Exemplo n.º 17
0
static void hash_list( int out, const char *path )
{
    int list = rb->open( path, O_RDONLY );
    char newpath[MAX_PATH];
    if( list < 0 ) return;

    while( !quit && rb->read_line( list, newpath, MAX_PATH ) > 0 )
    {
        DIR *dir = rb->opendir( newpath );
        if( dir )
        {
            rb->closedir( dir );
            hash_dir( out, newpath );
        }
        else
        {
            hash_file( out, newpath );
        }
    }

    rb->close( list );
}
Exemplo n.º 18
0
/*
 * Hash a file ignoring comments. Returns a bitmask of HASH_SOURCE_CODE_*
 * results.
 */
int
hash_source_code_file(struct conf *conf, struct mdfour *hash, const char *path)
{
	char *data;
	size_t size;
	int result;

	if (is_precompiled_header(path)) {
		if (hash_file(hash, path)) {
			return HASH_SOURCE_CODE_OK;
		} else {
			return HASH_SOURCE_CODE_ERROR;
		}
	} else {
		if (!read_file(path, 0, &data, &size)) {
			return HASH_SOURCE_CODE_ERROR;
		}
		result = hash_source_code_string(conf, hash, data, size, path);
		free(data);
		return result;
	}
}
Exemplo n.º 19
0
int md5_sha1_sum_main(int argc, char **argv)
{
	int return_value = EXIT_SUCCESS;
	uint8_t *hash_value;
	unsigned flags;
	hash_algo_t hash_algo = ENABLE_MD5SUM
		? (ENABLE_SHA1SUM ? (**argv=='m' ? HASH_MD5 : HASH_SHA1) : HASH_MD5)
		: HASH_SHA1;

	if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK)
		flags = getopt32(argc, argv, "scw");
	else optind = 1;

	if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && !(flags & FLAG_CHECK)) {
		if (flags & FLAG_SILENT) {
			bb_error_msg_and_die
				("-%c is meaningful only when verifying checksums", 's');
		} else if (flags & FLAG_WARN) {
			bb_error_msg_and_die
				("-%c is meaningful only when verifying checksums", 'w');
		}
	}

	if (argc == optind) {
		argv[argc++] = "-";
	}

	if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && (flags & FLAG_CHECK)) {
		FILE *pre_computed_stream;
		int count_total = 0;
		int count_failed = 0;
		char *file_ptr = argv[optind];
		char *line;

		if (optind + 1 != argc) {
			bb_error_msg_and_die
				("only one argument may be specified when using -c");
		}

		pre_computed_stream = stdin;
		if (NOT_LONE_DASH(file_ptr)) {
			pre_computed_stream = xfopen(file_ptr, "r");
		}

		while ((line = xmalloc_getline(pre_computed_stream)) != NULL) {
			char *filename_ptr;

			count_total++;
			filename_ptr = strstr(line, "  ");
			/* handle format for binary checksums */
			if (filename_ptr == NULL) {
				filename_ptr = strstr(line, " *");
			}
			if (filename_ptr == NULL) {
				if (flags & FLAG_WARN) {
					bb_error_msg("invalid format");
				}
				count_failed++;
				return_value = EXIT_FAILURE;
				free(line);
				continue;
			}
			*filename_ptr = '\0';
			filename_ptr += 2;

			hash_value = hash_file(filename_ptr, hash_algo);

			if (hash_value && (strcmp((char*)hash_value, line) == 0)) {
				if (!(flags & FLAG_SILENT))
					printf("%s: OK\n", filename_ptr);
			} else {
				if (!(flags & FLAG_SILENT))
					printf("%s: FAILED\n", filename_ptr);
				count_failed++;
				return_value = EXIT_FAILURE;
			}
			/* possible free(NULL) */
			free(hash_value);
			free(line);
		}
		if (count_failed && !(flags & FLAG_SILENT)) {
			bb_error_msg("WARNING: %d of %d computed checksums did NOT match",
						 count_failed, count_total);
		}
		/*
		if (fclose_if_not_stdin(pre_computed_stream) == EOF) {
			bb_perror_msg_and_die("cannot close file %s", file_ptr);
		}
		*/
	} else {
		while (optind < argc) {
			char *file_ptr = argv[optind++];

			hash_value = hash_file(file_ptr, hash_algo);
			if (hash_value == NULL) {
				return_value = EXIT_FAILURE;
			} else {
				printf("%s  %s\n", hash_value, file_ptr);
				free(hash_value);
			}
		}
	}
	return return_value;
}
Exemplo n.º 20
0
char *file_md5sum_alloc(const char *file_name)
{
	return hash_file(file_name, HASH_MD5);
}
Exemplo n.º 21
0
int
exec_clean(int argc, char **argv)
{
	struct pkgdb	*db = NULL;
	struct pkgdb_it	*it = NULL;
	struct pkg	*pkg = NULL;
	struct pkg	*p = NULL;
	FTS		*fts = NULL;
	FTSENT		*ent = NULL;
	struct dl_head	dl = STAILQ_HEAD_INITIALIZER(dl);
	const char	*cachedir;
	char		*paths[2];
	char		*repopath;
	bool		 dry_run = false;
	bool		 yes;
	int		 retcode = EX_SOFTWARE;
	int		 ret;
	int		 ch;

	pkg_config_bool(PKG_CONFIG_ASSUME_ALWAYS_YES, &yes);

	while ((ch = getopt(argc, argv, "nqy")) != -1) {
		switch (ch) {
		case 'n':
			dry_run = true;
			break;
		case 'q':
			quiet = true;
			break;
		case 'y':
			yes = true;
			break;
		default:
			usage_clean();
			return (EX_USAGE);
		}
	}
	argc -= optind;
	argv += optind;

	if (pkg_config_string(PKG_CONFIG_CACHEDIR, &cachedir) != EPKG_OK) {
		warnx("Cannot get cachedir config entry");
		return 1;
	}

	paths[0] = __DECONST(char*, cachedir);
	paths[1] = NULL;

	if (pkgdb_open(&db, PKGDB_REMOTE) != EPKG_OK) {
		goto cleanup;
	}

	if ((fts = fts_open(paths, FTS_PHYSICAL, NULL)) == NULL) {
		warn("fts_open(%s)", cachedir);
		goto cleanup;
	}

	/* Build the list of out-of-date or obsolete packages */

	while ((ent = fts_read(fts)) != NULL) {
		const char *origin, *pkgrepopath;

		if (ent->fts_info != FTS_F)
			continue;

		repopath = ent->fts_path + strlen(cachedir);
		if (repopath[0] == '/')
			repopath++;

		if (pkg_open(&pkg, ent->fts_path) != EPKG_OK) {
			if (!quiet)
				warnx("skipping %s", ent->fts_path);
			continue;
		}

		pkg_get(pkg, PKG_ORIGIN, &origin);
		it = pkgdb_search(db, origin, MATCH_EXACT, FIELD_ORIGIN,
		    FIELD_NONE, NULL);

		if (it == NULL) {
			if (!quiet)
				warnx("skipping %s", ent->fts_path);
			continue;
		}

		if ((ret = pkgdb_it_next(it, &p, PKG_LOAD_BASIC)) ==
		    EPKG_FATAL) {
			if (!quiet)
				warnx("skipping %s", ent->fts_path);
			continue;
		}

		pkg_get(p, PKG_REPOPATH, &pkgrepopath);
		if (ret == EPKG_END) {
			ret = add_to_dellist(&dl, REMOVED, ent->fts_path,
					     origin, NULL, NULL);
		} else if (strcmp(repopath, pkgrepopath)) {
			const char	*newname;
			const char	*newversion;

			pkg_get(p, 
				PKG_NAME,    &newname,
				PKG_VERSION, &newversion);

			ret = add_to_dellist(&dl, OUT_OF_DATE, ent->fts_path,
					     origin, newname, newversion);
		} else {
			char local_cksum[SHA256_DIGEST_LENGTH * 2 +1];
			const char *cksum;

			pkg_get(p, PKG_CKSUM, &cksum);

			if (hash_file(ent->fts_path, local_cksum) == EPKG_OK) {

				if (strcmp(cksum, local_cksum) != 0) {
					ret = add_to_dellist(&dl, CKSUM_MISMATCH, ent->fts_path,
						     origin, NULL, NULL);
				}
			}
		}

		if (ret != EPKG_OK && ret != EPKG_END) {
			retcode = EX_OSERR; /* out of memory */
			goto cleanup;
		}

		pkgdb_it_free(it);
	}

	if (STAILQ_EMPTY(&dl)) {
		if (!quiet)
			printf("Nothing to do.\n");
		retcode = EX_OK;
		goto cleanup;
	}

	if (dry_run || !yes || !quiet)
		display_dellist(&dl, cachedir);

	if (!dry_run) {
		if (!yes)
			yes = query_yesno(
				"\nProceed with cleaning cache [y/N]: ");
		if (yes)
			retcode = delete_dellist(&dl);
	} else 
		retcode = EX_OK;

cleanup:
	free_dellist(&dl);

	pkg_free(pkg);
	pkg_free(p);
	if (fts != NULL)
		fts_close(fts);
	if (db != NULL)
		pkgdb_close(db);

	return (retcode);
}
Exemplo n.º 22
0
/*\
|*| Find a file in the static directory structure that matches the md5 sums.
|*| Try matching filenames first
\*/
int
find_file(pfile_t *file, int displ)
{
	hfile_t *p;
	int cm, corr = 0;

	if (file->match) return 1;

	/*\ Check filename (caseless) and then check md5 hash \*/
	for (p = hfile; p; p = p->next) {
		cm = unicode_cmp(p->filename, file->filename);
		if (cm < 0) continue;
		if (!hash_file(p, HASH)) {
			if (displ) {
				fprintf(stderr, "      ERROR: %s",
						basename(p->filename));
				perror(" ");
			}
			corr = 1;
			continue;
		}
		if (CMP_MD5(p->hash, file->hash)) {
			if (!cm || !file->match)
				file->match = p;
			continue;
		}
		if (displ)
			fprintf(stderr, "      ERROR: %s: Failed md5 sum\n",
					basename(p->filename));
		corr = 1;
	}
	if (file->match) {
		if (displ)
			fprintf(stderr, "  %-40s - OK\n",
				basename(file->filename));
		if (!displ || !cmd.dupl)
			return 1;
	}

	/*\ Try to match md5 hash on all files \*/
	for (p = hfile; p; p = p->next) {
		if (file->match == p)
			continue;
		if (!hash_file(p, HASH16K))
			continue;
		if (!CMP_MD5(p->hash_16k, file->hash_16k))
			continue;
		if (!hash_file(p, HASH))
			continue;
		if (!CMP_MD5(p->hash, file->hash))
			continue;
		if (!file->match) {
			file->match = p;
			if (displ) {
				fprintf(stderr, "  %-40s - FOUND",
					basename(file->filename));
				fprintf(stderr, ": %s\n",
					basename(p->filename));
			}
			if (!displ || !cmd.dupl)
				return 1;
		}
		fprintf(stderr, "    Duplicate: %s",
			stuni(file->match->filename));
		fprintf(stderr, " == %s\n",
			basename(p->filename));
	}
	if (!file->match && displ)
		fprintf(stderr, "  %-40s - %s\n",
			basename(file->filename),
			corr ? "CORRUPT" : "NOT FOUND");
	return (file->match != 0);
}
Exemplo n.º 23
0
int main(int argc, const char * argv[])
{
    
    if (argc == 2) { 
        if (strcmp(argv[1], "-v") == 0) {
            printf("%s\n",version);
        }
        else if (strcmp(argv[1], "-s") == 0) {
            printf("MD5 (\"\") = %s\n", md5hash(""));
        }
        else if (strcmp(argv[1], "-f") == 0){
            printf("%s\n", illegal_option);
            printf("%s\n", usage);
        }
        else if (strcmp(argv[1], "-?") == 0){
            printf("%s\n", usage);
        }
        else if (strcmp(argv[1], "-cf") == 0){
            printf("%s\n", usage_check);
        }
        else if (strcmp(argv[1], "-cs") == 0){
            printf("%s\n", usage_check);
        }
        else{
            printf("%s %s\n", illegal_option, argv[1]);
            printf("%s\n",usage);
        }
    }
    else if (argc == 3){
        if (strcmp(argv[1], "-s") == 0) {
            printf("MD5 (\"%s\") = %s\n", argv[2], md5hash(argv[2]));
        }
        else if (strcmp(argv[1], "-f") == 0){
            clock_t start,end;
            start = clock();
            printf("MD5 (%s) = %s\n", argv[2], hash_file(argv[2]));
            end = clock();
            printf("Hash in %f sec\n",(float)(end-start)/CLOCKS_PER_SEC);
        }
        else if (strcmp(argv[1], "-cf") == 0){
            printf("%s\n", usage_check);
        }
        else if (strcmp(argv[1], "-cs") == 0){
            printf("%s\n", usage_check);
        }
        else{
            printf("%s (\"%s\")", illegal_string, argv[2]);
            printf("%s\n", usage);
        }
    }
    else if (argc == 4){
        if (strcmp(argv[1], "-cf") == 0 ) {
            if (strcmp(hash_file(argv[2]), argv[3]) == 0) {
                printf("It seems to be all right\n");
            }
            else
                printf("File Dismatch\n");
        }
        else if (strcmp(argv[1], "-cs") == 0 ) {
            if (strcmp(md5hash(argv[2]), argv[3]) == 0) {
                printf("It seems to be all right\n");
            }
            else
                printf("String Dismatch\n");
        }
    }
    else{
        printf("%s\n", illegal_option);
        printf("%s\n", usage);
    }
    
    
    
    return 0;
}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
	size_t i;
	struct MD5Context ctx;
	unsigned char digest[MD5LENGTH];
	unsigned char buf[BUFFERSIZE];
	int fd;
	int c;
	pid_t pid;
	char *file = NULL;
	int verbose = 0;
	int r;
	struct timeval tv;
	struct timezone tz;

	static const struct option longopts[] = {
		{"file", required_argument, NULL, 'f'},
		{"verbose", no_argument, NULL, 'v'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

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

	while ((c =
		getopt_long(argc, argv, "f:vVh", longopts, NULL)) != -1)
		switch (c) {
		case 'v':
			verbose = 1;
			break;
		case 'f':
			file = optarg;
			break;
		case 'V':
			printf(_("%s from %s\n"),
			       program_invocation_short_name,
			       PACKAGE_STRING);
			return EXIT_SUCCESS;
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}

	MD5Init(&ctx);
	gettimeofday(&tv, &tz);
	MD5Update(&ctx, (unsigned char *) &tv, sizeof(tv));

	pid = getppid();
	MD5Update(&ctx, (unsigned char *) &pid, sizeof(pid));
	pid = getpid();
	MD5Update(&ctx, (unsigned char *) &pid, sizeof(pid));

	if (file) {
		int count = 0;

		if (file[0] == '-' && !file[1])
			fd = STDIN_FILENO;
		else
			fd = open(file, O_RDONLY);

		if (fd < 0) {
			warn(_("Could not open %s"), file);
		} else {
			count = hash_file(&ctx, fd);
			if (verbose)
				fprintf(stderr,
					_("Got %d bytes from %s\n"), count,
					file);

			if (fd != STDIN_FILENO)
				if (close(fd))
					err(EXIT_FAILURE,
					    _("closing %s failed"), file);
		}
	}

	for (i = 0; i < RNGS; i++) {
		if ((fd = open(rngs[i].path, O_RDONLY | O_NONBLOCK)) >= 0) {
			int count = sizeof(buf);

			if (rngs[i].maxlength && count > rngs[i].maxlength)
				count = rngs[i].maxlength;
			r = read(fd, buf, count);
			if (r > 0)
				MD5Update(&ctx, buf, r);
			else
				r = 0;
			close(fd);
			if (verbose)
				fprintf(stderr,
					_("Got %d bytes from %s\n"), r,
					rngs[i].path);
			if (rngs[i].minlength && r >= rngs[i].minlength)
				break;
		} else if (verbose)
			warn(_("Could not open %s"), rngs[i].path);
	}

	MD5Final(digest, &ctx);
	for (i = 0; i < MD5LENGTH; i++)
		printf("%02x", digest[i]);
	putchar('\n');

	/*
	 * The following is important for cases like disk full,
	 * so shell scripts can bomb out properly rather than
	 * think they succeeded.
	 */
	if (fflush(stdout) < 0 || fclose(stdout) < 0)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}
Exemplo n.º 25
0
static int
qpkg_make(depend_atom *atom)
{
	FILE *fp, *out;
	char tmpdir[BUFSIZE];
	char filelist[BUFSIZE + 32];
	char tbz2[BUFSIZE + 32];
	size_t buflen;
	char *buf;
	int i;
	char *xpak_argv[2];
	struct stat st;

	if (pretend) {
		printf(" %s-%s %s/%s:\n",
				GREEN, NORM, atom->CATEGORY, atom_to_pvr(atom));
		return 0;
	}

	buflen = _Q_PATH_MAX;
	buf = xmalloc(buflen);

	snprintf(buf, buflen, "%s/%s/%s/CONTENTS",
			portvdb, atom->CATEGORY, atom_to_pvr(atom));
	if ((fp = fopen(buf, "r")) == NULL) {
		free(buf);
		return -1;
	}

	snprintf(tmpdir, sizeof(tmpdir), "%s/qpkg.XXXXXX", qpkg_get_bindir());
	if ((i = mkstemp(tmpdir)) == -1) {
		free(buf);
		return -2;
	}
	close(i);
	unlink(tmpdir);
	if (mkdir(tmpdir, 0750)) {
		free(buf);
		return -3;
	}

	snprintf(filelist, sizeof(filelist), "%s/filelist", tmpdir);
	if ((out = fopen(filelist, "w")) == NULL) {
		free(buf);
		return -4;
	}

	while (getline(&buf, &buflen, fp) != -1) {
		contents_entry *e;
		e = contents_parse_line(buf);
		if (!e || e->type == CONTENTS_DIR)
			continue;
		if (check_pkg_install_mask(e->name) != 0)
			continue;
		fprintf(out, "%s\n", e->name+1); /* dont output leading / */
		if (e->type == CONTENTS_OBJ && verbose) {
			char *hash = (char *)hash_file(e->name, HASH_MD5);
			if (hash != NULL) {
				if (strcmp(e->digest, hash) != 0)
					warn("MD5: mismatch expected %s got %s for %s",
							e->digest, hash, e->name);
				free(hash);
			}
		}
	}

	fclose(out);
	fclose(fp);

	printf(" %s-%s %s/%s: ", GREEN, NORM, atom->CATEGORY, atom_to_pvr(atom));
	fflush(stdout);

	snprintf(tbz2, sizeof(tbz2), "%s/bin.tbz2", tmpdir);
	if (snprintf(buf, buflen, "tar jcf '%s' --files-from='%s' "
			"--no-recursion >/dev/null 2>&1", tbz2, filelist) > (int)buflen ||
			(fp = popen(buf, "r")) == NULL)
	{
		free(buf);
		return 2;
	}
	pclose(fp);

	snprintf(buf, buflen, "%s/%s/%s",
			portvdb, atom->CATEGORY, atom_to_pvr(atom));
	xpak_argv[0] = buf;
	xpak_argv[1] = NULL;
	xpak_create(AT_FDCWD, tbz2, 1, xpak_argv, 1, verbose);

	unlink(filelist);

	snprintf(buf, buflen, "%s/%s.tbz2", qpkg_get_bindir(), atom_to_pvr(atom));
	if (rename(tbz2, buf)) {
		warnp("could not move '%s' to '%s'", tbz2, buf);
		free(buf);
		return 1;
	}

	rmdir(tmpdir);

	stat(buf, &st);
	printf("%s%s%s kB\n",
			RED, make_human_readable_str(st.st_size, 1, KILOBYTE), NORM);

	free(buf);
	return 0;
}
Exemplo n.º 26
0
/* This could become a common function for md5 as well, by using md5_stream */
static int hash_files(int argc, char **argv, const uint8_t hash_algo)
{
	int return_value = EXIT_SUCCESS;
	uint8_t *hash_value;

#ifdef CONFIG_FEATURE_MD5_SHA1_SUM_CHECK
	unsigned int flags;

	flags = bb_getopt_ulflags(argc, argv, "scw");
#endif

#ifdef CONFIG_FEATURE_MD5_SHA1_SUM_CHECK
	if (!(flags & FLAG_CHECK)) {
		if (flags & FLAG_SILENT) {
			bb_error_msg_and_die
				("the -s option is meaningful only when verifying checksums");
		} else if (flags & FLAG_WARN) {
			bb_error_msg_and_die
				("the -w option is meaningful only when verifying checksums");
		}
	}
#endif

	if (argc == optind) {
		argv[argc++] = "-";
	}
#ifdef CONFIG_FEATURE_MD5_SHA1_SUM_CHECK
	if (flags & FLAG_CHECK) {
		FILE *pre_computed_stream;
		int count_total = 0;
		int count_failed = 0;
		char *file_ptr = argv[optind];
		char *line;

		if (optind + 1 != argc) {
			bb_error_msg_and_die
				("only one argument may be specified when using -c");
		}

		if (strcmp(file_ptr, "-") == 0) {
			pre_computed_stream = stdin;
		} else {
			pre_computed_stream = bb_xfopen(file_ptr, "r");
		}

		while ((line = bb_get_chomped_line_from_file(pre_computed_stream)) != NULL) {
			char *filename_ptr;

			count_total++;
			filename_ptr = strstr(line, "  ");
			if (filename_ptr == NULL) {
				if (flags & FLAG_WARN) {
					bb_error_msg("Invalid format");
				}
				count_failed++;
				return_value = EXIT_FAILURE;
				free(line);
				continue;
			}
			*filename_ptr = '\0';
			filename_ptr += 2;

			hash_value = hash_file(filename_ptr, hash_algo);

			if (hash_value && (strcmp((char*)hash_value, line) == 0)) {
				if (!(flags & FLAG_SILENT))
					printf("%s: OK\n", filename_ptr);
			} else {
				if (!(flags & FLAG_SILENT))
					printf("%s: FAILED\n", filename_ptr);
				count_failed++;
				return_value = EXIT_FAILURE;
			}
			/* possible free(NULL) */
			free(hash_value);
			free(line);
		}
		if (count_failed && !(flags & FLAG_SILENT)) {
			bb_error_msg("WARNING: %d of %d computed checksums did NOT match",
						 count_failed, count_total);
		}
		if (bb_fclose_nonstdin(pre_computed_stream) == EOF) {
			bb_perror_msg_and_die("Couldnt close file %s", file_ptr);
		}
	} else
#endif
	{
		while (optind < argc) {
			char *file_ptr = argv[optind++];

			hash_value = hash_file(file_ptr, hash_algo);
			if (hash_value == NULL) {
				return_value = EXIT_FAILURE;
			} else {
				printf("%s  %s\n", hash_value, file_ptr);
				free(hash_value);
			}
		}
	}
	return (return_value);
}
Exemplo n.º 27
0
int main (int argc, char **argv)
{
    int c, i;

    int verbose = 0;

    int errors = 0;

    int open_mode = O_RDONLY;

    gost_subst_block *b = &GostR3411_94_CryptoProParamSet;

    FILE *check_file = NULL;

    gost_hash_ctx ctx;

    while ((c = getopt (argc, argv, "bc::tv")) != -1)
    {
        switch (c)
        {
            case 'v':
                verbose = 1;
                break;
            case 't':
                b = &GostR3411_94_TestParamSet;
                break;
            case 'b':
                open_mode |= O_BINARY;
                break;
            case 'c':
                if (optarg)
                {
                    check_file = fopen (optarg, "r");
                    if (!check_file)
                    {
                        perror (optarg);
                        exit (2);
                    }
                }
                else
                {
                    check_file = stdin;
                }
                break;
            default:
                fprintf (stderr, "invalid option %c", optopt);
                help ();
        }
    }
    init_gost_hash_ctx (&ctx, b);
    if (check_file)
    {
        char inhash[65], calcsum[65], filename[PATH_MAX];

        int failcount = 0, count = 0;;
        if (check_file == stdin && optind < argc)
        {
            check_file = fopen (argv[optind], "r");
            if (!check_file)
            {
                perror (argv[optind]);
                exit (2);
            }
        }
        while (get_line (check_file, inhash, filename))
        {
            if (!hash_file (&ctx, filename, calcsum, open_mode))
            {
                exit (2);
            }
            count++;
            if (!strncmp (calcsum, inhash, 65))
            {
                if (verbose)
                {
                    fprintf (stderr, "%s\tOK\n", filename);
                }
            }
            else
            {
                if (verbose)
                {
                    fprintf (stderr, "%s\tFAILED\n", filename);
                }
                else
                {
                    fprintf (stderr, "%s: GOST hash sum check failed for '%s'\n", argv[0], filename);
                }
                failcount++;
            }
        }
        if (verbose && failcount)
        {
            fprintf (stderr, "%s: %d of %d file(f) failed GOST hash sum check\n", argv[0], failcount, count);
        }
        exit (failcount ? 1 : 0);
    }
    if (optind == argc)
    {
        char sum[65];

        if (!hash_stream (&ctx, fileno (stdin), sum))
        {
            perror ("stdin");
            exit (1);
        }
        printf ("%s -\n", sum);
        exit (0);
    }
    for (i = optind; i < argc; i++)
    {
        char sum[65];

        if (!hash_file (&ctx, argv[i], sum, open_mode))
        {
            errors++;
        }
        else
        {
            printf ("%s %s\n", sum, argv[i]);
        }
    }
    exit (errors ? 1 : 0);
}
Exemplo n.º 28
0
int main(int argc, char **argv)
{
    int c, i;
    int verbose = 0;
    int errors = 0;
    int open_mode = O_RDONLY;
    FILE *check_file = NULL;
    int filenames_from_stdin = 0;
    gost_hash_ctx ctx;

    while ((c = getopt(argc, argv, "bxlvc::")) != -1) {
        switch (c) {
        case 'b':
            open_mode = open_mode | O_BINARY;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'l':
            hashsize = 512;
            break;
        case 'x':
            filenames_from_stdin = 1;
            break;
        case 'c':
            if (optarg) {
                check_file = fopen(optarg, "r");
                if (!check_file) {
                    perror(optarg);
                    exit(2);
                }
            } else {
                check_file = stdin;
            }
            break;
        default:
            fprintf(stderr, "invalid option %c", optopt);
            help();
        }
    }
    if (check_file) {
        char inhash[MAX_HASH_SIZE + 1], calcsum[MAX_HASH_SIZE + 1],
            filename[PATH_MAX];
        int failcount = 0, count = 0;;
        if (check_file == stdin && optind < argc) {
            check_file = fopen(argv[optind], "r");
            if (!check_file) {
                perror(argv[optind]);
                exit(2);
            }
        }
        while (get_line(check_file, inhash, filename, verbose)) {
            count++;
            if (!hash_file(&ctx, filename, calcsum, open_mode)) {
                errors++;
                continue;
            }
            if (!strncmp(calcsum, inhash, hashsize / 4 + 1)) {
                if (verbose) {
                    fprintf(stderr, "%s\tOK\n", filename);
                }
            } else {
                if (verbose) {
                    fprintf(stderr, "%s\tFAILED\n", filename);
                } else {
                    fprintf(stderr,
                            "%s: GOST hash sum check failed for '%s'\n",
                            argv[0], filename);
                }
                failcount++;
            }
        }
        if (errors) {
            fprintf(stderr,
                    "%s: WARNING %d of %d file(s) cannot be processed\n",
                    argv[0], errors, count);

        }
        if (failcount) {
            fprintf(stderr,
                    "%s: WARNING %d of %d file(s) failed GOST hash sum check\n",
                    argv[0], failcount, count - errors);
        }
        exit((failcount || errors) ? 1 : 0);
    } else if (filenames_from_stdin) {
        char sum[65];
        char filename[PATH_MAX + 1], *end;
        while (!feof(stdin)) {
            if (!fgets(filename, PATH_MAX, stdin))
                break;
            for (end = filename; *end; end++) ;
            end--;
            for (; *end == '\n' || *end == '\r'; end--)
                *end = 0;
            if (!hash_file(&ctx, filename, sum, open_mode)) {
                errors++;
            } else {
                printf("%s %s\n", sum, filename);
            }
        }
    } else if (optind == argc) {
        char sum[65];
#ifdef _WIN32
        if (open_mode & O_BINARY) {
            _setmode(fileno(stdin), O_BINARY);
        }
#endif
        if (!hash_stream(&ctx, fileno(stdin), sum)) {
            perror("stdin");
            exit(1);
        }
        printf("%s -\n", sum);
        exit(0);
    } else {
        for (i = optind; i < argc; i++) {
            char sum[65];
            if (!hash_file(&ctx, argv[i], sum, open_mode)) {
                errors++;
            } else {
                printf("%s %s\n", sum, argv[i]);
            }
        }
    }
    exit(errors ? 1 : 0);
}
Exemplo n.º 29
0
int main(int argc, char **argv)
{
   rsa_key rsakey;
   char          fname[256];
   char          *hashname;
   char          expiry[256];
   unsigned char buf[4096], rsabuf[2048], md[MAXBLOCKSIZE], sig[512];
   unsigned long buflen, rsalen, mdlen, siglen;
   FILE          *infile;
   int i;
   int           opt_v2      = 0;
   int           opt_fullkey = 0;
   int           argoffset   = 0;

   if (argc < 3) { 
     fprintf(stderr, "Usage: %s [--fullkey] [--v2 expiry] hashname key_file_name [signed_file_name]\n", argv[0]);
     return EXIT_FAILURE;
   }

   LTC_ARGCHK(register_hash(&sha256_desc) != -1);
   LTC_ARGCHK(register_hash(&sha512_desc) != -1);
   LTC_ARGCHK(register_hash(&rmd160_desc) != -1);
   LTC_ARGCHK(register_hash(&whirlpool_desc) != -1);
   LTC_ARGCHK(register_prng(&sprng_desc) != -1);
   ltc_mp = tfm_desc;

   for ( i=1; i < argc; i++) {
     if (strcmp(argv[i], OPT_V2)==0) {
       opt_v2 = 1;
       strncpy(expiry, argv[i+1], 256);
       i++;
       argoffset=argoffset+2;
       continue;
     }
     if (strcmp(argv[i], OPT_FULLKEY)==0) {
       opt_fullkey = 1;
       argoffset++;
       continue;
     }
     /* done! get out softly */
     i=argc;
   }

   hashname = argv[1+argoffset];

   /* get hashes of file */
   mdlen = sizeof(md);
   if ( argc - argoffset > 3) {
     DO(hash_file(find_hash(argv[1+argoffset]), argv[3+argoffset], md, &mdlen));
   } else {
     DO(hash_filehandle(find_hash(argv[1+argoffset]), stdin, md, &mdlen));
   }

   /* read keyblob and import key from it */
   strncpy(fname, argv[2+argoffset], 256);
   strncat(fname, ".private", 256);
   infile = fopen(fname, "rb");
   LTC_ARGCHK(infile != NULL);
   buflen = fread(buf, 1, sizeof(buf), infile);
   fclose(infile);

   /* now try to import the RSA key */
   DO(rsa_import(buf, buflen, &rsakey));

   /* now sign the hashes */
   siglen = sizeof(sig);
   DO(rsa_sign_hash(md, mdlen, sig, &siglen, NULL, find_prng("sprng"), find_hash(hashname), 8, &rsakey));

   /* open output file */
   if (opt_v2==1) {
     fprintf(stdout, "sig02: %s ", hashname);
   } else {
     fprintf(stdout, "sig01: %s ", hashname);
   }

   /* read keyblob and import key from it */
   strncpy(fname, argv[2+argoffset], 256);
   strncat(fname, ".public", 256);
   infile = fopen(fname, "rb");
   LTC_ARGCHK(infile != NULL);
   buflen = fread(buf, 1, sizeof(buf), infile);
   fclose(infile);

   if (opt_fullkey==1) {
     i = 0;
   } else {
     i = buflen-32;
   }
   for ( ; i < buflen; i++)
       fprintf(stdout, "%02x", buf[i]);

   fprintf(stdout, " ");

   if (opt_v2==1) {
     fprintf(stdout, expiry);
     fprintf(stdout, " ");
   }

   for (i = 0; i < siglen; i++)
       fprintf(stdout, "%02x", sig[i]);

   fprintf(stdout, "\n");

   rsa_free(&rsakey);

   return EXIT_SUCCESS;
}
Exemplo n.º 30
0
/* find the hash for a command. The hash includes all argument lists,
   plus the output from running the compiler with -E */
static void find_hash(ARGS *args)
{
	int i;
	char *path_stdout, *path_stderr;
	char *hash_dir;
	char *s;
	struct stat st;
	int status;
	int nlevels = 2;
	char *input_base;
	char *tmp;
	
	if ((s = getenv("CCACHE_NLEVELS"))) {
		nlevels = atoi(s);
		if (nlevels < 1) nlevels = 1;
		if (nlevels > 8) nlevels = 8;
	}

	hash_start();

	/* when we are doing the unifying tricks we need to include
           the input file name in the hash to get the warnings right */
	if (enable_unify) {
		hash_string(input_file);
	}

	/* we have to hash the extension, as a .i file isn't treated the same
	   by the compiler as a .ii file */
	hash_string(i_extension);

	/* first the arguments */
	for (i=1;i<args->argc;i++) {
		/* some arguments don't contribute to the hash. The
		   theory is that these arguments will change the
		   output of -E if they are going to have any effect
		   at all, or they only affect linking */
		if (i < args->argc-1) {
			if (strcmp(args->argv[i], "-I") == 0 ||
			    strcmp(args->argv[i], "-include") == 0 ||
			    strcmp(args->argv[i], "-L") == 0 ||
			    strcmp(args->argv[i], "-D") == 0 ||
			    strcmp(args->argv[i], "-idirafter") == 0 ||
			    strcmp(args->argv[i], "-isystem") == 0) {
				i++;
				continue;
			}
		}
		if (strncmp(args->argv[i], "-I", 2) == 0 ||
		    strncmp(args->argv[i], "-L", 2) == 0 ||
		    strncmp(args->argv[i], "-D", 2) == 0 ||
		    strncmp(args->argv[i], "-idirafter", 10) == 0 ||
		    strncmp(args->argv[i], "-isystem", 8) == 0) {
			continue;
		}

		if (strncmp(args->argv[i], "--specs=", 8) == 0 &&
		    stat(args->argv[i]+8, &st) == 0) {
			/* if given a explicit specs file, then hash that file, but
			   don't include the path to it in the hash */
			hash_file(args->argv[i]+8);
			continue;
		}

		/* all other arguments are included in the hash */
		hash_string(args->argv[i]);
	}

	/* the compiler driver size and date. This is a simple minded way
	   to try and detect compiler upgrades. It is not 100% reliable */
	if (stat(args->argv[0], &st) != 0) {
		cc_log("Couldn't stat the compiler!? (argv[0]='%s')\n", args->argv[0]);
		stats_update(STATS_COMPILER);
		failed();
	}

	/* also include the hash of the compiler name - as some compilers
	   use hard links and behave differently depending on the real name */
	if (st.st_nlink > 1) {
		hash_string(str_basename(args->argv[0]));
	}

	hash_int(st.st_size);
	hash_int(st.st_mtime);

	/* possibly hash the current working directory */
	if (getenv("CCACHE_HASHDIR")) {
		char *cwd = gnu_getcwd();
		if (cwd) {
			hash_string(cwd);
			free(cwd);
		}
	}

	/* ~/hello.c -> tmp.hello.123.i 
	   limit the basename to 10
	   characters in order to cope with filesystem with small
	   maximum filename length limits */
	input_base = str_basename(input_file);
	tmp = strchr(input_base, '.');
	if (tmp != NULL) {
		*tmp = 0;
	}
	if (strlen(input_base) > 10) {
		input_base[10] = 0;
	}

	/* now the run */
	x_asprintf(&path_stdout, "%s/%s.tmp.%s.%s", temp_dir,
		   input_base, tmp_string(), 
		   i_extension);
	x_asprintf(&path_stderr, "%s/tmp.cpp_stderr.%s", temp_dir, tmp_string());

	if (!direct_i_file) {
		/* run cpp on the input file to obtain the .i */
		args_add(args, "-E");
		args_add(args, input_file);
		status = execute(args->argv, path_stdout, path_stderr);
		args_pop(args, 2);
	} else {
		/* we are compiling a .i or .ii file - that means we
		   can skip the cpp stage and directly form the
		   correct i_tmpfile */
		path_stdout = input_file;
		if (create_empty_file(path_stderr) != 0) {
			stats_update(STATS_ERROR);
			cc_log("failed to create empty stderr file\n");
			failed();
		}
		status = 0;
	}

	if (status != 0) {
		if (!direct_i_file) {
			unlink(path_stdout);
		}
		unlink(path_stderr);
		cc_log("the preprocessor gave %d\n", status);
		stats_update(STATS_PREPROCESSOR);
		failed();
	}

	/* if the compilation is with -g then we have to include the whole of the
	   preprocessor output, which means we are sensitive to line number
	   information. Otherwise we can discard line number info, which makes
	   us less sensitive to reformatting changes 

	   Note! I have now disabled the unification code by default
	   as it gives the wrong line numbers for warnings. Pity.
	*/
	if (!enable_unify) {
		hash_file(path_stdout);
	} else {
		if (unify_hash(path_stdout) != 0) {
			stats_update(STATS_ERROR);
			failed();
		}
	}
	hash_file(path_stderr);

	i_tmpfile = path_stdout;

	if (!getenv("CCACHE_CPP2")) {
		/* if we are using the CPP trick then we need to remember this stderr
		   data and output it just before the main stderr from the compiler
		   pass */
		cpp_stderr = path_stderr;
	} else {	
		unlink(path_stderr);
		free(path_stderr);
	}

	/* we use a N level subdir for the cache path to reduce the impact
	   on filesystems which are slow for large directories
	*/
	s = hash_result();
	x_asprintf(&hash_dir, "%s/%c", cache_dir, s[0]);
	x_asprintf(&stats_file, "%s/stats", hash_dir);
	for (i=1; i<nlevels; i++) {
		char *p;
		if (create_dir(hash_dir) != 0) {
			cc_log("failed to create %s\n", hash_dir);
			failed();
		}
		x_asprintf(&p, "%s/%c", hash_dir, s[i]);
		free(hash_dir);
		hash_dir = p;
	}
	if (create_dir(hash_dir) != 0) {
		cc_log("failed to create %s\n", hash_dir);
		failed();
	}
	x_asprintf(&hashname, "%s/%s", hash_dir, s+nlevels);
	free(hash_dir);
}