Exemple #1
0
static bool scan_directory(std::vector<Path>& nodes, const Path& path, ScanMode mode)
{
    auto dir = opendir(path.c_str());
    if( dir )
    {
        struct dirent* de;
        struct stat st;
        while( (de = readdir(dir)) )
        {
            if( strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0 )
                continue;

            if( !value(mode & ScanMode::HIDDEN) && de->d_name[0] == '.' )
                continue;

            auto npath = (path / de->d_name);
            if( stat(npath.c_str(), &st) == 0 )
            {
                if( st.st_mode & S_IFDIR )
                {
                    if( value(mode & ScanMode::RECURSIVE) )
                        scan_directory(nodes, npath, mode);

                    if( value(mode & ScanMode::DIRECTORIES) )
                        nodes.push_back(std::move(npath));
                }
                else if( value(mode & ScanMode::FILES) )
                    nodes.push_back(std::move(npath));
            }
        }
        closedir(dir);
        return true;
    }
    return false;
}
Exemple #2
0
static bool scan_directory(std::vector<Path>& nodes, const Path& path, ScanMode mode)
{
    WIN32_FIND_DATAW info;
    HANDLE handle = FindFirstFileW(to_win32(path.c_str()).c_str(), &info);
    if( handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            auto npath = (path / info.cFileName);
            if( !info.cFileName.empty() )
            {
                if( info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN && !(mode & ScanMode::HIDDEN) )
                    continue;
                if( info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
                {
                    if( value(mode & ScanMode::RECURSIVE) )
                        scan_directory(nodes, npath, mode);

                    if( value(mode & ScanMode::DIRECTORIES) )
                        nodes.push_back(std::move(npath));
                }
                else if( value(mode & ScanMode::FILES) )
                    nodes.push_back(std::move(npath));
            }
        }
        while(FindNextFileW(handle, &info));
        FindClose(handle);
        return true;
    }
    return false;
}
Exemple #3
0
//---------------------------------------------------------
// PURPOSE: Default action 
// NOTE: Please comment this function if no default action and this library module
//---------------------------------------------------------
int _module_run(int moduleidx, int argn, int* arguments)
{
	module_idx=moduleidx;

    if ( argn!=2 ) {
		module_async_unload(moduleidx);		// fail to init - "unload me"
		return 1;
	}

	CMenu* menu;
	CMenuItem* item = (void*) arguments[1];
	switch ( item->type ) 
	{
		case MENUITEM_SUBMENU:
			free_modules_submenu( (CMenu*) item->value );
		case MENUITEM_PROC:
		case MENUITEM_TEXT:
			item->type = MENUITEM_TEXT;
			break;
		default:
			// should never be other types
			module_async_unload(moduleidx);
			return 1;
	}

	strlen_basepath = strlen( (char*) arguments[0] );
	menu = scan_directory( (char*) arguments[0] );
	if ( menu!=0 ) {
		item->type = MENUITEM_SUBMENU;
		item->value = (int*)menu;
	}

	module_async_unload(moduleidx);		// processing finished - "unload me"
	return 0;
}
Exemple #4
0
static void handle_propfind(struct mg_connection *conn, const char *path,
                            struct file *filep) {
  const char *depth = mg_get_header(conn, "Depth");

  conn->must_close = 1;
  conn->status_code = 207;
  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
            "Connection: close\r\n"
            "Content-Type: text/xml; charset=utf-8\r\n\r\n");

  conn->num_bytes_sent += mg_printf(conn,
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
      "<d:multistatus xmlns:d='DAV:'>\n");

  // Print properties for the requested resource itself
  print_props(conn, conn->request_info.uri, filep);

  // If it is a directory, print directory entries too if Depth is not 0
  if (filep->is_directory &&
      !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
      (depth == NULL || strcmp(depth, "0") != 0)) {
    scan_directory(conn, path, conn, &print_dav_dir_entry);
  }

  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
}
Exemple #5
0
bool ImageDirectorySequence::load_list()
{

  scan_directory(sequence_source);

  ImageFileListSequence::load_list();

}
Exemple #6
0
void
scan_directory(const char *dir)
{
    DIR *pd;
    struct dirent *pe;
    char canonical_path[PATH_MAX+1] = { 0 };
    char *end;
    struct stat sb;

    if (!(pd = opendir(dir))) {
        perror_str("[!] Unable to open dir \"%s\"", dir);
        return;
    }

    while ((pe = readdir(pd))) {
        if (pe->d_name[0] == '.') {
            if (pe->d_name[1] == '\0')
                continue;
            if (pe->d_name[1] == '.' && pe->d_name[2] == '\0')
                continue;
        }

        end = my_stpcpy(canonical_path, dir);
        if (end - canonical_path >= PATH_MAX - 1 - strlen(pe->d_name)) {
            fprintf(stderr, "[!] name too long \"%s/%s\"\n", dir, pe->d_name);
            continue;
        }
        if (end > canonical_path && *(end - 1) != '/')
            *end++ = '/';
        strcpy(end, pe->d_name);

#ifdef DEBUG
        printf("[*] checking: 0x%x 0x%x 0x%x 0x%x %s ...\n", 
               (unsigned int)pe->d_ino, (unsigned int)pe->d_off,
               pe->d_reclen,
               pe->d_type, canonical_path);
#endif

        /* decide where to put this one */
        if (lstat(canonical_path, &sb) == -1) {
            perror_str("[!] Unable to lstat \"%s\"", canonical_path);
            continue;
        }

        /* skip symlinks.. */
        if (S_ISLNK(sb.st_mode))
            continue;

        record_access_level(canonical_path, &sb);

        /* can the child directory too */
        if (S_ISDIR(sb.st_mode)
            && is_executable(&sb))
            scan_directory(canonical_path);
    }

    closedir(pd);
}
Exemple #7
0
bool file_cache::add_directory(const std::string& name) {
    if (scan_directory(name)) {
        log_debug("added directory " << name);
        std::lock_guard<std::mutex> lock(m_dir_mtx);
        m_directories.insert(name);
        return true;
    }
    log_err(name << " not added");
    return false;
}
Exemple #8
0
/*! \brief Build a list of available serial ports.
	Query the serial driver about the available devices,
	and build a list of them. 
*/
void
BSerialPort::_ScanDevices()
{
	// First, we empty the list
	if (fDevices != NULL) {
		for (int32 count = fDevices->CountItems() - 1; count >= 0; count--)
			free(fDevices->RemoveItem(count));
		
		// Add devices to the list
		scan_directory(SERIAL_DIR, fDevices);	
	}
}
Exemple #9
0
int
main(int argc, char *argv[])
{
    char canonical_path[PATH_MAX+1] = { 0 };
    int i, opt;
    char *user = NULL, *groups = NULL;

    /* process arguments */
    while ((opt = getopt(argc, argv, "u:g:")) != -1) {
        switch (opt) {
            case 'u':
                user = optarg;
                break;

            case 'g':
                groups = optarg;
                break;

            default:
                usage(argv);
                return 1;
        }
    }

    argc -= optind;
    argv += optind;

    /* get user info */
    obtain_user_info(user, groups);

    /* process remaining args as directories */
    for (i = 0; i < argc; i++) {
        if (!realpath(argv[i], canonical_path)) {
            perror_str("[!] Unable to resolve path \"%s\"", argv[i]);
            return 1;
        }

        scan_directory(canonical_path);
    }

    /* report the findings */
    report_findings("set-uid executable", &g_suid);
    report_findings("set-gid executable", &g_sgid);
    report_findings("writable", &g_writable);
#ifdef RECORD_LESS_INTERESTING
    report_findings("readable", &g_readable);
    report_findings("only executable", &g_executable);
#endif

    return 0;
}
Exemple #10
0
void scan_all(database* db)
{
    db_inject_library_directories(db);

    wchar* curr_dir;

    while((curr_dir = db_get_local_dir_copy(db)))
    {
        scan_directory(db, curr_dir);
        wprintf(L"Scanning directory: %s\n", curr_dir);
        db_remove_local_dir(db, curr_dir);
        delete [] curr_dir;
    }
}
Exemple #11
0
ImageDirectorySequence::ImageDirectorySequence(const char* directory, int start, int end) : sequence_source(directory), ImageFileListSequence()
{

  scan_directory(string(directory));

  file_end = files.size();

  if (start > -1) file_start = MIN(file_end-2, MAX(1, start));
  if (end > -1) file_end = MIN(file_end, MAX(file_start+1, end));

  load_list();


}
Exemple #12
0
bool file_cache::scan_directory(const std::string& name) {
    path p(name);
    if (exists(p) && is_directory(p)) {
        for (directory_entry& entry : directory_iterator(p)) {
            if (is_directory(entry.status())) {
                scan_directory(entry.path().string());
            } else {
                std::shared_ptr<file> f = get_file_main(entry.path().string());
                if (nullptr == f) {
                    // new file
                    add_file(entry.path().string());
                }
            }
        }
        return true;
    }
    log_debug(name << " is no direcotory or does not exists");
    return false;
}
Exemple #13
0
static void scan()
{
  const char *raw_path = config_to_path("music-directory");
  char *path;
  time_t now;
  
  if (raw_path == NULL) {
    musicd_log(LOG_INFO, "scan", "music-directory not set, not scanning");
    return;
  }
  
  path = strcopy(raw_path);
  
  /* Strip possible trailing / */
  if (path[strlen(path) - 1] == '/') {
    path[strlen(path) - 1] = '\0';
  }
  
  
  last_scan = db_meta_get_int("last-scan");
  now = time(NULL);
  
  musicd_log(LOG_INFO, "scan", "starting");
  
  signal(SIGINT, scan_signal_handler);
  
  scan_directory(path, 0);
  
  free(path);
  
  signal(SIGINT, NULL);
  
  if (interrupted) {  
    musicd_log(LOG_INFO, "scan", "interrupted");
    return;
  }
  
  musicd_log(LOG_INFO, "scan", "finished");
  
  db_meta_set_int("last-scan", now);
}
Exemple #14
0
file_cache::file_cache(int refresh_time) {
    m_thread = std::thread([this, refresh_time] {
        while (!m_stop) {
            // relax
            std::this_thread::sleep_for(std::chrono::seconds(refresh_time));
            // look for new objects
            std::unordered_set<std::string> dirs;
            {
                std::lock_guard<std::mutex> lock(m_dir_mtx);
                dirs = m_directories;
            }
            for (auto& dir : dirs) {
                scan_directory(dir);
            }
            // update/remove existing objects
            std::vector<std::string> to_remove;
            std::vector<std::string> to_add;
            {
                std::lock_guard<std::mutex> lock(m_file_mtx);
                for (auto& pair : m_file_map) {
                    path p(pair.first);
                    if (exists(p)) {
                        if (*pair.second != file(pair.first)) {
                            // changed file
                            to_add.push_back(pair.first);
                        }
                    } else {
                        // file does not exists, remove it
                        to_remove.push_back(pair.first);
                    }
                }
            }
            for (auto& f : to_add) {
                add_file(f);
            }
            for (auto& f : to_remove) {
                remove_file(f);
            }
        }
    });
}
Exemple #15
0
void
name_fill_directory (struct name *name, dev_t device, bool cmdline)
{
  name->directory = scan_directory (name->name, device, cmdline);
}
Exemple #16
0
/**
 * Iterates through directory. Subdirectories will be scanned using
 * scan_directory.
 */
static void iterate_directory(const char *dirpath, int dir_id)
{
  struct stat status;
  DIR *dir;
  struct dirent *entry;
  
  int64_t file;
  time_t file_mtime;
  
  char *path;
  
  if (!(dir = opendir(dirpath))) {
    /* Probably no read access - ok, we just omit. */
    musicd_perror(LOG_WARNING, "scan", "could not open directory %s", dirpath);
    return;
  }
  
  /* + 256 4-bit UTF-8 characters + / and \0 
   * More than enough on every platform really in use. */
  path = malloc(strlen(dirpath) + 1024 + 2);
  
  errno = 0;
  while ((entry = readdir(dir))) {
    if (interrupted) {
      break;
    }
    
    /* Omit hidden files and most importantly . and .. */
    if (entry->d_name[0] == '.') {
      goto next;
    }
    
    sprintf(path, "%s/%s", dirpath, entry->d_name);

    if (stat(path, &status)) {
      goto next;
    }
      
    if (S_ISDIR(status.st_mode)) {
      scan_directory(path, dir_id);
      goto next;
    }
    if (!S_ISREG(status.st_mode)) {
      goto next;
    }
    
    file = library_file(path, 0);
    if (file > 0) {
      file_mtime = library_file_mtime(file);
      if (file_mtime == status.st_mtime) {
        goto next;
      }
    }
    
    file = scan_file(path, dir_id);
    if (file) {
      library_file_mtime_set(file, status.st_mtime);
    }

  next:
    errno = 0;
  }
  
  closedir(dir);
  
  if (errno) {
    /* It was possible to open the directory but we can't iterate it anymore?
     * Something's fishy. */
    musicd_perror(LOG_ERROR, "scan", "could not iterate directory %s", path);
  }
  free(path);
}
Exemple #17
0
//---------------------------------------------------------
CMenu* scan_directory(const char* dir) {

    STD_DIR           *d;
    struct STD_dirent *de;
    static struct STD_stat   st;

	char curdir[100];
	strcpy( curdir, dir);

    int iter, count, len;
	CMenu* mmenu = 0;
	CMenuItem* mitems = 0;
	CMenuItem* curitem;

	// Two iterations:
	//		first for draft count possible elements. then allocate
	//		second exact check and filling each elements
	for ( iter=1; iter<=2; iter++ )
	{
	    d = safe_opendir(curdir);
    	if (!d) return 0;

		count = 0;
	    for( de = safe_readdir(d); de; de = safe_readdir(d) ) {

            if (de->d_name[0] == 0xE5 /* deleted entry */ )
				continue;

            if (de->d_name[0] == '.' && de->d_name[1]==0) 
				continue;

            if (de->d_name[0] == '.' && de->d_name[1]=='.' && de->d_name[2] == 0 )
				continue;

           	sprintf(buf, "%s/%s", curdir, de->d_name);
	        if (safe_stat(buf, &st)!=0) 
				continue;
			
			if ( st.st_attrib != DOS_ATTR_DIRECTORY &&
				 st.st_size <= (sizeof(struct flat_hdr)+sizeof(struct ModuleInfo)) ) 
				continue;

			if ( iter==2 ) {

				curitem=mitems+count;

				if ( st.st_attrib == DOS_ATTR_DIRECTORY ) {
					void* submenu = 0;
					submenu = scan_directory( buf );

					if ( submenu==0 )
						continue;

					curitem->text = (int)malloc( strlen(de->d_name)+1 );
					if ( curitem->text==0 ) continue;
					curitem->type = MENUITEM_SUBMENU;
					curitem->value = submenu;
					strcpy( (char*)curitem->text, de->d_name);
				} else {

					char *ext = strchr(de->d_name,'.');
        		    if ( !ext || (ext[1]|0x20)!='f' || (ext[2]|0x20)!='l' || (ext[3]|0x20)!='t' )
						continue;

					if ( !load_module_info(buf) )
						continue;

					if (minfo.flags & MODULEINFO_FLAG_SYSTEM )
						continue;

					len = ( minfo.moduleName < 0 ) ? 0 : strlen(modulename);

					curitem->arg = (int)malloc( len+1 + strlen(buf)-strlen_basepath );
					if ( curitem->arg==0 ) continue;

					curitem->type = MENUITEM_PROC;
					curitem->value = (void*)gui_menu_run_fltmodule;
					strcpy( (void*)curitem->arg, buf+strlen_basepath+1 );

					if ( minfo.moduleName < 0 )
						curitem->text= -minfo.moduleName;
					else {
						curitem->text = curitem->arg + strlen((char*)curitem->arg)+1;
						strcpy( (char*)curitem->text, modulename );
					}
				}

				curitem->symbol=0x5c;
			}

			count++;
		}

		safe_closedir(d);

		// Iteration#1 final: allocate menuitems
		if (iter==1) {

			if ( count==0 )	{ safe_closedir(d); return 0;}

			len = sizeof(CMenu) + sizeof(CMenuItem)*(count+2);
			mmenu=malloc( len );
			if ( mmenu==0 ) return 0;
			mitems = (CMenuItem*) ((char*)mmenu + sizeof(CMenu) );
			memset( mmenu, 0, len );
		}
	}

	// Iteration#2 final

	if ( count == 0 ) {
		free( mmenu );
		return 0;
	}

	// .. fill Cmenu
	mmenu->symbol = 0x29;
	mmenu->on_change = 0;
	mmenu->menu = mitems;
	if ( strlen(curdir)==strlen_basepath )
		strcpy( buf, "Modules");
	else
		sprintf( buf, "Modules %s", curdir+strlen_basepath+1);

	mmenu->title = (int)malloc( strlen(buf)+1 );
	if ( mmenu->title==0 )
	{
		free( mmenu );
		return 0;
	}

	strcpy( (void*)mmenu->title, buf );


	// sort item
    qsort(mitems, count, sizeof(CMenuItem), fselect_sort_nothumb);


	// Add "Back" item
	curitem=mitems+count;
	curitem->text = LANG_MENU_BACK;
	curitem->symbol=0x51;
    curitem->type = MENUITEM_UP;

	return mmenu;
}
Exemple #18
0
bool Directory::scan(const Path& path, ScanMode mode)
{
    return scan_directory(_nodes, path, mode);
}
Exemple #19
0
const char *
get_directory_contents (char *dir, dev_t device)
{
  return scan_directory (dir, device);
}
int main (int argc, char** argv) {
  GFile              *db_dir, *db_file;
  notmuch_status_t    status;
  notmuch_database_t *db   = NULL;
  notmuch_query_t *query = NULL;
  notmuch_messages_t *messages = NULL;
  notmuch_message_t *message = NULL;
  GMainLoop          *loop = NULL;

  const char *query_string = "date:2014-02-01..";

  if (argc != 2)
  {
    g_warning ("Usage: %s EVOLUTION_MAILDIR", argv[0]);
    return 1;
  }

  db_dir = g_file_new_for_path (argv[1]);
  db_file = g_file_get_child (db_dir, ".notmuch");

  if (!g_file_query_exists (db_dir, NULL))
  {
    g_object_unref (db_dir);
    g_object_unref (db_file);
    g_error ("directory %s does not exists");
    return 2;
  }

  if (!g_file_query_exists (db_file, NULL))
    status = notmuch_database_create (argv[1], &db);
  else
    status = notmuch_database_open (argv[1], NOTMUCH_DATABASE_MODE_READ_WRITE, &db);

  if (status)
  {
    g_error ("Could not open database: %d", status);
    g_object_unref (db_dir);
    g_object_unref (db_file);
    notmuch_database_destroy (db);
    return 3;
  }


  scan_directory (db, db_dir);
  //loop = g_main_loop_new (NULL, FALSE);
  //g_main_loop_run (loop);

  query = notmuch_query_create (db, query_string);

  if (!query) {
    g_error ("Could not create query from string = \"%s\"", query_string);
    notmuch_database_destroy (db);
    g_object_unref (db_file);
    g_object_unref (db_dir);
    return 4;
  }

  g_message ("Query results -\n\n");

  for (messages = notmuch_query_search_messages (query);
         notmuch_messages_valid (messages);
         notmuch_messages_move_to_next (messages)) {

    message = notmuch_messages_get (messages);

    g_message ("Message file: %s", notmuch_message_get_filename (message));
    g_message ("Message ID: %s", notmuch_message_get_message_id (message));
    g_message ("Message Sender: %s", notmuch_message_get_header (message, "from"));
    g_message ("Message Recipients: %s", notmuch_message_get_header (message, "to"));
    g_message ("Message Subject: %s", notmuch_message_get_header (message, "subject"));
    g_message ("Message date: %s\n", notmuch_message_get_header (message, "date"));

    notmuch_message_destroy (message);
  }

  notmuch_query_destroy (query);

  notmuch_database_destroy (db);
  g_object_unref (db_file);
  g_object_unref (db_dir);
  return 0;
}
Exemple #21
0
static void
walk_dirs(lua_State* L, int path_index, int callback_index)
{
	size_t dir_count;
	int dir_table, file_table;

	/* create a new table to store the work queue of directories in */
	lua_newtable(L);
	dir_table = lua_gettop(L);

	/* put the initial path in the dir table */
	lua_pushvalue(L, path_index);
	lua_rawseti(L, dir_table, 1);

	/* create a new table to store the resulting files in */
	lua_newtable(L);
	file_table = lua_gettop(L);

	/* loop until the directory stack has been exhausted */
	while (0 != (dir_count = lua_objlen(L, dir_table)))
	{
		int new_dir_table, new_file_table, path_index;
		size_t i, e;
		const char *path;

		/* pick off last dir and remove from stack */
		lua_rawgeti(L, dir_table, (int) dir_count);
		lua_pushnil(L);
		lua_rawseti(L, dir_table, (int) dir_count);

		path = lua_tostring(L, -1);
		path_index = lua_gettop(L);

		/* pushes two tables on the stack, files and directories */
		scan_directory(L, path);
		new_file_table = lua_gettop(L);
		new_dir_table = new_file_table - 1;

		/* sort the file table (in-place) so we get consistent results */
		lua_getglobal(L, "table");
		lua_getfield(L, -1, "sort");
		lua_pushvalue(L, new_file_table);
		lua_call(L, 1, 0);

		/* Call out with the results of this directory query to be saved with
		 * the DAG cache. When the DAG cache is read back in, the queries will
		 * re-run to make sure the cache is still valid. */
		td_call_cache_hook(L, &td_dirwalk_hook_key, path_index, new_file_table);

		/* see what directories to keep */
		for (i = 1, e = lua_objlen(L, new_dir_table); i <= e; ++i)
		{
			/* push three pieces <parent> </> <dir> in anticipation of success
			 * so we don't have to reshuffle the stack */
			lua_pushvalue(L, path_index);
			lua_pushstring(L, "/");
			lua_rawgeti(L, new_dir_table, (int) i);

			/* If there's a callback function to filter directories, call it
			 * now. Otherwise, just include everything. */
			if (callback_index)
			{
				lua_pushvalue(L, callback_index);
				lua_pushvalue(L, -2); /* push a copy of the new dir name */
	
				lua_call(L, 1, 1); /* stack -2, +1 */
				if (!lua_toboolean(L, -1))
				{
					lua_pop(L, 4);
					continue;
				}

				/* just pop the boolean */
				lua_pop(L, 1);
			}

			lua_concat(L, 3);
			lua_rawseti(L, dir_table, (int) (lua_objlen(L, dir_table) + 1));
		}

		/* add all files */
		for (i = 1, e = lua_objlen(L, new_file_table); i <= e; ++i)
		{
			/* push three pieces <parent> </> <dir> in anticipation of success
			 * so we don't have to reshuffle the stack */
			lua_pushvalue(L, path_index);
			lua_pushstring(L, "/");
			lua_rawgeti(L, new_file_table, (int) i);
			lua_concat(L, 3);
			lua_rawseti(L, file_table, (int) (lua_objlen(L, file_table) + 1));
		}

		/* pop the two new tables */
		lua_pop(L, 2);
	}

	lua_pushvalue(L, file_table);
}
Exemple #22
0
int
main(int argc, char *argv[])
{
	static struct option long_options[] = {
		{"pgdata", required_argument, NULL, 'D'},
		{"verbose", no_argument, NULL, 'v'},
		{NULL, 0, NULL, 0}
	};

	char	   *DataDir = NULL;
	int			c;
	int			option_index;
	bool		crc_ok;

	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_checksums"));

	progname = get_progname(argv[0]);

	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			usage();
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("pg_checksums (PostgreSQL) " PG_VERSION);
			exit(0);
		}
	}

	while ((c = getopt_long(argc, argv, "D:r:v", long_options, &option_index)) != -1)
	{
		switch (c)
		{
			case 'v':
				verbose = true;
				break;
			case 'D':
				DataDir = optarg;
				break;
			case 'r':
				if (atoi(optarg) == 0)
				{
					fprintf(stderr, _("%s: invalid relfilenode specification, must be numeric: %s\n"), progname, optarg);
					exit(1);
				}
				only_relfilenode = pstrdup(optarg);
				break;
			default:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit(1);
		}
	}

	if (DataDir == NULL)
	{
		if (optind < argc)
			DataDir = argv[optind++];
		else
			DataDir = getenv("PGDATA");

		/* If no DataDir was specified, and none could be found, error out */
		if (DataDir == NULL)
		{
			fprintf(stderr, _("%s: no data directory specified\n"), progname);
			fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
			exit(1);
		}
	}

	/* Complain if any arguments remain */
	if (optind < argc)
	{
		fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
				progname, argv[optind]);
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
				progname);
		exit(1);
	}

	/* Check if cluster is running */
	ControlFile = get_controlfile(DataDir, progname, &crc_ok);
	if (!crc_ok)
	{
		fprintf(stderr, _("%s: pg_control CRC value is incorrect\n"), progname);
		exit(1);
	}

	if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
	{
		fprintf(stderr, _("%s: cluster is not compatible with this version of pg_checksums\n"),
				progname);
		exit(1);
	}

	if (ControlFile->state != DB_SHUTDOWNED &&
		ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
	{
		fprintf(stderr, _("%s: cluster must be shut down to verify checksums\n"), progname);
		exit(1);
	}

	if (ControlFile->data_checksum_version == 0)
	{
		fprintf(stderr, _("%s: data checksums are not enabled in cluster\n"), progname);
		exit(1);
	}

	/* Scan all files */
	scan_directory(DataDir, "global");
	scan_directory(DataDir, "base");
	scan_directory(DataDir, "pg_tblspc");

	printf(_("Checksum scan completed\n"));
	printf(_("Data checksum version: %d\n"), ControlFile->data_checksum_version);
	printf(_("Files scanned:  %s\n"), psprintf(INT64_FORMAT, files));
	printf(_("Blocks scanned: %s\n"), psprintf(INT64_FORMAT, blocks));
	printf(_("Bad checksums:  %s\n"), psprintf(INT64_FORMAT, badblocks));

	if (badblocks > 0)
		return 1;

	return 0;
}
Exemple #23
0
static int outfile_remove (hashcat_ctx_t *hashcat_ctx)
{
  // some hash-dependent constants

  hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  hashes_t       *hashes       = hashcat_ctx->hashes;
  outcheck_ctx_t *outcheck_ctx = hashcat_ctx->outcheck_ctx;
  status_ctx_t   *status_ctx   = hashcat_ctx->status_ctx;
  user_options_t *user_options = hashcat_ctx->user_options;

  u32  dgst_size  = hashconfig->dgst_size;
  u32  is_salted  = hashconfig->is_salted;
  u32  esalt_size = hashconfig->esalt_size;
  u32  hash_mode  = hashconfig->hash_mode;
  char separator  = hashconfig->separator;

  char *root_directory      = outcheck_ctx->root_directory;
  u32   outfile_check_timer = user_options->outfile_check_timer;

  // buffers
  hash_t hash_buf = { 0, 0, 0, 0, 0, NULL, 0 };

  hash_buf.digest = hcmalloc (dgst_size);

  if (is_salted)  hash_buf.salt =  (salt_t *) hcmalloc (sizeof (salt_t));
  if (esalt_size) hash_buf.esalt = (void   *) hcmalloc (esalt_size);

  u32 digest_buf[64] = { 0 };

  outfile_data_t *out_info = NULL;

  char **out_files = NULL;

  time_t folder_mtime = 0;

  int out_cnt = 0;

  u32 check_left = outfile_check_timer; // or 1 if we want to check it at startup

  while (status_ctx->shutdown_inner == false)
  {
    hc_sleep (1);

    if (status_ctx->devices_status != STATUS_RUNNING) continue;

    check_left--;

    if (check_left == 0)
    {
      hc_stat_t outfile_check_stat;

      if (hc_stat (root_directory, &outfile_check_stat) == 0)
      {
        u32 is_dir = S_ISDIR (outfile_check_stat.st_mode);

        if (is_dir == 1)
        {
          if (outfile_check_stat.st_mtime > folder_mtime)
          {
            char **out_files_new = scan_directory (root_directory);

            int out_cnt_new = count_dictionaries (out_files_new);

            outfile_data_t *out_info_new = NULL;

            if (out_cnt_new > 0)
            {
              out_info_new = (outfile_data_t *) hccalloc (out_cnt_new, sizeof (outfile_data_t));

              for (int i = 0; i < out_cnt_new; i++)
              {
                out_info_new[i].file_name = out_files_new[i];

                // check if there are files that we have seen/checked before (and not changed)

                for (int j = 0; j < out_cnt; j++)
                {
                  if (strcmp (out_info[j].file_name, out_info_new[i].file_name) == 0)
                  {
                    hc_stat_t outfile_stat;

                    if (hc_stat (out_info_new[i].file_name, &outfile_stat) == 0)
                    {
                      if (outfile_stat.st_ctime == out_info[j].ctime)
                      {
                        out_info_new[i].ctime = out_info[j].ctime;
                        out_info_new[i].seek  = out_info[j].seek;
                      }
                    }
                  }
                }
              }
            }

            hcfree (out_info);
            hcfree (out_files);

            out_files = out_files_new;
            out_cnt   = out_cnt_new;
            out_info  = out_info_new;

            folder_mtime = outfile_check_stat.st_mtime;
          }

          for (int j = 0; j < out_cnt; j++)
          {
            FILE *fp = fopen (out_info[j].file_name, "rb");

            if (fp != NULL)
            {
              //hc_thread_mutex_lock (status_ctx->mux_display);

              hc_stat_t outfile_stat;

              hc_fstat (fileno (fp), &outfile_stat);

              if (outfile_stat.st_ctime > out_info[j].ctime)
              {
                out_info[j].ctime = outfile_stat.st_ctime;
                out_info[j].seek  = 0;
              }

              fseeko (fp, out_info[j].seek, SEEK_SET);

              char *line_buf = (char *) hcmalloc (HCBUFSIZ_LARGE);

              while (!feof (fp))
              {
                char *ptr = fgets (line_buf, HCBUFSIZ_LARGE - 1, fp);

                if (ptr == NULL) break;

                size_t line_len = strlen (line_buf);

                if (line_len == 0) continue;

                size_t iter = MAX_CUT_TRIES;

                for (size_t i = line_len - 1; i && iter; i--, line_len--)
                {
                  if (line_buf[i] != separator) continue;

                  iter--;

                  int parser_status = PARSER_OK;

                  if ((hash_mode != 2500) && (hash_mode != 6800))
                  {
                    parser_status = hashconfig->parse_func ((u8 *) line_buf, line_len - 1, &hash_buf, hashconfig);
                  }

                  u32 found = 0;

                  if (parser_status == PARSER_OK)
                  {
                    for (u32 salt_pos = 0; (found == 0) && (salt_pos < hashes->salts_cnt); salt_pos++)
                    {
                      if (hashes->salts_shown[salt_pos] == 1) continue;

                      salt_t *salt_buf = &hashes->salts_buf[salt_pos];

                      for (u32 digest_pos = 0; (found == 0) && (digest_pos < salt_buf->digests_cnt); digest_pos++)
                      {
                        u32 idx = salt_buf->digests_offset + digest_pos;

                        if (hashes->digests_shown[idx] == 1) continue;

                        u32 cracked = 0;

                        if (hash_mode == 6800)
                        {
                          if (i == salt_buf->salt_len)
                          {
                            cracked = (memcmp (line_buf, salt_buf->salt_buf, salt_buf->salt_len) == 0);
                          }
                        }
                        else if (hash_mode == 2500)
                        {
                          // BSSID : MAC1 : MAC2 (:plain)
                          if (i == (salt_buf->salt_len + 1 + 12 + 1 + 12))
                          {
                            cracked = (memcmp (line_buf, salt_buf->salt_buf, salt_buf->salt_len) == 0);

                            if (!cracked) continue;

                            // now compare MAC1 and MAC2 too, since we have this additional info
                            char *mac1_pos = line_buf + salt_buf->salt_len + 1;
                            char *mac2_pos = mac1_pos + 12 + 1;

                            wpa_t *wpas = (wpa_t *) hashes->esalts_buf;
                            wpa_t *wpa  = &wpas[salt_pos];

                            // compare hex string(s) vs binary MAC address(es)

                            for (u32 mac_idx = 0, orig_mac_idx = 0; mac_idx < 6; mac_idx++, orig_mac_idx += 2)
                            {
                              if (wpa->orig_mac1[mac_idx] != hex_to_u8 ((const u8 *) &mac1_pos[orig_mac_idx]))
                              {
                                cracked = 0;

                                break;
                              }
                            }

                            // early skip ;)
                            if (!cracked) continue;

                            for (u32 mac_idx = 0, orig_mac_idx = 0; mac_idx < 6; mac_idx++, orig_mac_idx += 2)
                            {
                              if (wpa->orig_mac2[mac_idx] != hex_to_u8 ((const u8 *) &mac2_pos[orig_mac_idx]))
                              {
                                cracked = 0;

                                break;
                              }
                            }
                          }
                        }
                        else
                        {
                          char *digests_buf_ptr = (char *) hashes->digests_buf;

                          memcpy (digest_buf, digests_buf_ptr + (hashes->salts_buf[salt_pos].digests_offset * dgst_size) + (digest_pos * dgst_size), dgst_size);

                          cracked = (sort_by_digest_p0p1 (digest_buf, hash_buf.digest, hashconfig) == 0);
                        }

                        if (cracked == 1)
                        {
                          found = 1;

                          hashes->digests_shown[idx] = 1;

                          hashes->digests_done++;

                          salt_buf->digests_done++;

                          if (salt_buf->digests_done == salt_buf->digests_cnt)
                          {
                            hashes->salts_shown[salt_pos] = 1;

                            hashes->salts_done++;

                            if (hashes->salts_done == hashes->salts_cnt) mycracked (hashcat_ctx);
                          }
                        }
                      }

                      if (status_ctx->devices_status == STATUS_CRACKED) break;
                    }
                  }

                  if (found) break;

                  if (status_ctx->devices_status == STATUS_CRACKED) break;
                }

                if (status_ctx->devices_status == STATUS_CRACKED) break;
              }

              hcfree (line_buf);

              out_info[j].seek = ftello (fp);

              //hc_thread_mutex_unlock (status_ctx->mux_display);

              fclose (fp);
            }
          }
        }
      }

      check_left = outfile_check_timer;
    }
  }

  hcfree (hash_buf.esalt);

  hcfree (hash_buf.salt);

  hcfree (hash_buf.digest);

  hcfree (out_info);

  hcfree (out_files);

  return 0;
}
Exemple #24
0
NTSTATUS unix_convert(connection_struct *conn,
			pstring name,
			BOOL allow_wcard_last_component,
			char *saved_last_component, 
			SMB_STRUCT_STAT *pst)
{
	SMB_STRUCT_STAT st;
	char *start, *end;
	pstring dirpath;
	pstring orig_path;
	BOOL component_was_mangled = False;
	BOOL name_has_wildcard = False;

	SET_STAT_INVALID(*pst);

	*dirpath = 0;

	if(saved_last_component) {
		*saved_last_component = 0;
	}

	if (conn->printer) {
		/* we don't ever use the filenames on a printer share as a
			filename - so don't convert them */
		return NT_STATUS_OK;
	}

	DEBUG(5, ("unix_convert called on file \"%s\"\n", name));

	/* 
	 * Conversion to basic unix format is already done in check_path_syntax().
	 */

	/* 
	 * Names must be relative to the root of the service - any leading /.
	 * and trailing /'s should have been trimmed by check_path_syntax().
	 */

#ifdef DEVELOPER
	SMB_ASSERT(*name != '/');
#endif

	/*
	 * If we trimmed down to a single '\0' character
	 * then we should use the "." directory to avoid
	 * searching the cache, but not if we are in a
	 * printing share.
	 * As we know this is valid we can return true here.
	 */

	if (!*name) {
		name[0] = '.';
		name[1] = '\0';
		if (SMB_VFS_STAT(conn,name,&st) == 0) {
			*pst = st;
		}
		DEBUG(5,("conversion finished \"\" -> %s\n",name));
		return NT_STATUS_OK;
	}

	if (name[0] == '.' && (name[1] == '/' || name[1] == '\0')) {
		/* Start of pathname can't be "." only. */
		if (name[1] == '\0' || name[2] == '\0') {
			return NT_STATUS_OBJECT_NAME_INVALID;
		} else {
			return determine_path_error(&name[2], allow_wcard_last_component);
		}
	}

	/*
	 * Ensure saved_last_component is valid even if file exists.
	 */

	if(saved_last_component) {
		end = strrchr_m(name, '/');
		if (end) {
			pstrcpy(saved_last_component, end + 1);
		} else {
			pstrcpy(saved_last_component, name);
		}
	}

	/*
	 * Large directory fix normalization. If we're case sensitive, and
	 * the case preserving parameters are set to "no", normalize the case of
	 * the incoming filename from the client WHETHER IT EXISTS OR NOT !
	 * This is in conflict with the current (3.0.20) man page, but is
	 * what people expect from the "large directory howto". I'll update
	 * the man page. Thanks to [email protected] for finding this. JRA.
	 */

	if (conn->case_sensitive && !conn->case_preserve && !conn->short_case_preserve) {
		strnorm(name, lp_defaultcase(SNUM(conn)));
	}
	
	start = name;
	pstrcpy(orig_path, name);

	if(!conn->case_sensitive && stat_cache_lookup(conn, name, dirpath, &start, &st)) {
		*pst = st;
		return NT_STATUS_OK;
	}

	/* 
	 * stat the name - if it exists then we are all done!
	 */

	if (SMB_VFS_STAT(conn,name,&st) == 0) {
		/* Ensure we catch all names with in "/."
		   this is disallowed under Windows. */
		const char *p = strstr(name, "/."); /* mb safe. */
		if (p) {
			if (p[2] == '/') {
				/* Error code within a pathname. */
				return NT_STATUS_OBJECT_PATH_NOT_FOUND;
			} else if (p[2] == '\0') {
				/* Error code at the end of a pathname. */
				return NT_STATUS_OBJECT_NAME_INVALID;
			}
		}
		/*
		 * This is a case insensitive file system, we really need to
		 * get the correct case of the name.
		 */
		if (!(conn->fs_capabilities & FILE_CASE_SENSITIVE_SEARCH)) {
		    pstring case_preserved_name;

		    if (SMB_VFS_GET_PRESERVED_NAME(conn, name, case_preserved_name)) {
			char * last_component = strrchr(name, '/');
			int space_left = PSTRING_LEN;

			if (last_component) {
				last_component++;
				*last_component = 0;
				space_left = PSTRING_LEN - strlen(name);
			} else
				last_component = name;
			strlcpy(last_component, case_preserved_name, space_left);
		    }
		}
		stat_cache_add(orig_path, name, conn->case_sensitive);
		DEBUG(5,("conversion finished %s -> %s\n",orig_path, name));
		*pst = st;
		return NT_STATUS_OK;
	}

	DEBUG(5,("unix_convert begin: name = %s, dirpath = %s, start = %s\n", name, dirpath, start));

	/* 
	 * A special case - if we don't have any mangling chars and are case
	 * sensitive then searching won't help.
	 */

	if (conn->case_sensitive && 
			!mangle_is_mangled(name, conn->params) &&
			!*lp_mangled_map(conn->params)) {
		return NT_STATUS_OK;
	}

	/* 
	 * is_mangled() was changed to look at an entire pathname, not 
	 * just a component. JRA.
	 */

	if (mangle_is_mangled(start, conn->params)) {
		component_was_mangled = True;
	}

	/* 
	 * Now we need to recursively match the name against the real 
	 * directory structure.
	 */

	/* 
	 * Match each part of the path name separately, trying the names
	 * as is first, then trying to scan the directory for matching names.
	 */

	for (; start ; start = (end?end+1:(char *)NULL)) {
		/* 
		 * Pinpoint the end of this section of the filename.
		 */
		end = strchr(start, '/'); /* mb safe. '/' can't be in any encoded char. */

		/* 
		 * Chop the name at this point.
		 */
		if (end) {
			*end = 0;
		}

		if (saved_last_component != 0) {
			pstrcpy(saved_last_component, end ? end + 1 : start);
		}

		/* The name cannot have a component of "." */

		if (ISDOT(start)) {
			if (!end)  {
				/* Error code at the end of a pathname. */
				return NT_STATUS_OBJECT_NAME_INVALID;
			}
			return determine_path_error(end+1, allow_wcard_last_component);
		}

		/* The name cannot have a wildcard if it's not
		   the last component. */

		name_has_wildcard = ms_has_wild(start);

		/* Wildcard not valid anywhere. */
		if (name_has_wildcard && !allow_wcard_last_component) {
			return NT_STATUS_OBJECT_NAME_INVALID;
		}

		/* Wildcards never valid within a pathname. */
		if (name_has_wildcard && end) {
			return NT_STATUS_OBJECT_NAME_INVALID;
		}

		/* 
		 * Check if the name exists up to this point.
		 */

		if (SMB_VFS_STAT(conn,name, &st) == 0) {
			/*
			 * It exists. it must either be a directory or this must be
			 * the last part of the path for it to be OK.
			 */
			if (end && !(st.st_mode & S_IFDIR)) {
				/*
				 * An intermediate part of the name isn't a directory.
				 */
				DEBUG(5,("Not a dir %s\n",start));
				*end = '/';
				/* 
				 * We need to return the fact that the intermediate
				 * name resolution failed. This is used to return an
				 * error of ERRbadpath rather than ERRbadfile. Some
				 * Windows applications depend on the difference between
				 * these two errors.
				 */
				return NT_STATUS_OBJECT_PATH_NOT_FOUND;
			}

			if (!end) {
				/*
				 * We just scanned for, and found the end of the path.
				 * We must return the valid stat struct.
				 * JRA.
				 */

				*pst = st;
			}

		} else {
			pstring rest;

			/* Stat failed - ensure we don't use it. */
			SET_STAT_INVALID(st);
			*rest = 0;

			/*
			 * Remember the rest of the pathname so it can be restored
			 * later.
			 */

			if (end) {
				pstrcpy(rest,end+1);
			}

			/* Reset errno so we can detect directory open errors. */
			errno = 0;

			/*
			 * Try to find this part of the path in the directory.
			 */

			if (name_has_wildcard || 
			    !scan_directory(conn, dirpath, start, sizeof(pstring) - 1 - (start - name))) {
				if (end) {
					/*
					 * An intermediate part of the name can't be found.
					 */
					DEBUG(5,("Intermediate not found %s\n",start));
					*end = '/';

					/* 
					 * We need to return the fact that the intermediate
					 * name resolution failed. This is used to return an
					 * error of ERRbadpath rather than ERRbadfile. Some
					 * Windows applications depend on the difference between
					 * these two errors.
					 */

					/* ENOENT, ENOTDIR and ELOOP all map to
					 * NT_STATUS_OBJECT_PATH_NOT_FOUND
					 * in the filename walk. */

					if (errno == ENOENT ||
							errno == ENOTDIR ||
							errno == ELOOP) {
						return NT_STATUS_OBJECT_PATH_NOT_FOUND;
					}
					return map_nt_error_from_unix(errno);
				}

				/* ENOENT is the only valid error here. */
				if (errno != ENOENT) {
					/* ENOTDIR and ELOOP both map to
					 * NT_STATUS_OBJECT_PATH_NOT_FOUND
					 * in the filename walk. */
					if (errno == ENOTDIR ||
							errno == ELOOP) {
						return NT_STATUS_OBJECT_PATH_NOT_FOUND;
					}
					return map_nt_error_from_unix(errno);
				}

				/*
				 * Just the last part of the name doesn't exist.
				 * We need to strupper() or strlower() it as
				 * this conversion may be used for file creation 
				 * purposes. Fix inspired by Thomas Neumann <*****@*****.**>.
				 */
				if (!conn->case_preserve ||
				    (mangle_is_8_3(start, False, conn->params) &&
						 !conn->short_case_preserve)) {
					strnorm(start, lp_defaultcase(SNUM(conn)));
				}

				/*
				 * check on the mangled stack to see if we can recover the 
				 * base of the filename.
				 */

				if (mangle_is_mangled(start, conn->params)) {
					mangle_check_cache( start, sizeof(pstring) - 1 - (start - name), conn->params);
				}

				DEBUG(5,("New file %s\n",start));
				return NT_STATUS_OK;
			}

			/* 
			 * Restore the rest of the string. If the string was mangled the size
			 * may have changed.
			 */
			if (end) {
				end = start + strlen(start);
				if (!safe_strcat(start, "/", sizeof(pstring) - 1 - (start - name)) ||
				    !safe_strcat(start, rest, sizeof(pstring) - 1 - (start - name))) {
					return map_nt_error_from_unix(ENAMETOOLONG);
				}
				*end = '\0';
			} else {
				/*
				 * We just scanned for, and found the end of the path.
				 * We must return a valid stat struct if it exists.
				 * JRA.
				 */

				if (SMB_VFS_STAT(conn,name, &st) == 0) {
					*pst = st;
				} else {
					SET_STAT_INVALID(st);
				}
			}
		} /* end else */

#ifdef DEVELOPER
		if (VALID_STAT(st) && get_delete_on_close_flag(st.st_dev, st.st_ino)) {
			return NT_STATUS_DELETE_PENDING;
		}
#endif

		/* 
		 * Add to the dirpath that we have resolved so far.
		 */
		if (*dirpath) {
			pstrcat(dirpath,"/");
		}

		pstrcat(dirpath,start);

		/*
		 * Don't cache a name with mangled or wildcard components
		 * as this can change the size.
		 */
		
		if(!component_was_mangled && !name_has_wildcard) {
			stat_cache_add(orig_path, dirpath, conn->case_sensitive);
		}
	
		/* 
		 * Restore the / that we wiped out earlier.
		 */
		if (end) {
			*end = '/';
		}
	}
  
	/*
	 * Don't cache a name with mangled or wildcard components
	 * as this can change the size.
	 */

	if(!component_was_mangled && !name_has_wildcard) {
		stat_cache_add(orig_path, name, conn->case_sensitive);
	}

	/* 
	 * The name has been resolved.
	 */

	DEBUG(5,("conversion finished %s -> %s\n",orig_path, name));
	return NT_STATUS_OK;
}
Exemple #25
0
static int outfile_remove (hashcat_ctx_t *hashcat_ctx)
{
  // some hash-dependent constants

  hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  hashes_t       *hashes       = hashcat_ctx->hashes;
  outcheck_ctx_t *outcheck_ctx = hashcat_ctx->outcheck_ctx;
  status_ctx_t   *status_ctx   = hashcat_ctx->status_ctx;
  user_options_t *user_options = hashcat_ctx->user_options;

  u32  dgst_size      = hashconfig->dgst_size;
  bool is_salted      = hashconfig->is_salted;
  u32  esalt_size     = hashconfig->esalt_size;
  u32  hook_salt_size = hashconfig->hook_salt_size;
  u32  hash_mode      = hashconfig->hash_mode;
  char separator      = hashconfig->separator;

  char *root_directory      = outcheck_ctx->root_directory;
  u32   outfile_check_timer = user_options->outfile_check_timer;

  // buffers
  hash_t hash_buf = { 0, 0, 0, 0, 0, 0, NULL, 0 };

  hash_buf.digest = hcmalloc (dgst_size);

  if (is_salted == true)  hash_buf.salt      = (salt_t *) hcmalloc (sizeof (salt_t));
  if (esalt_size > 0)     hash_buf.esalt     = hcmalloc (esalt_size);
  if (hook_salt_size > 0) hash_buf.hook_salt = hcmalloc (hook_salt_size);

  u32 digest_buf[64] = { 0 };

  outfile_data_t *out_info = NULL;

  char **out_files = NULL;

  time_t folder_mtime = 0;

  int out_cnt = 0;

  u32 check_left = outfile_check_timer; // or 1 if we want to check it at startup

  while (status_ctx->shutdown_inner == false)
  {
    sleep (1);

    if (status_ctx->devices_status != STATUS_RUNNING) continue;

    check_left--;

    if (check_left == 0)
    {
      if (hc_path_exist (root_directory) == true)
      {
        const bool is_dir = hc_path_is_directory (root_directory);

        if (is_dir == true)
        {
          struct stat outfile_check_stat;

          if (stat (root_directory, &outfile_check_stat) == -1)
          {
            event_log_error (hashcat_ctx, "%s: %s", root_directory, strerror (errno));

            hcfree (out_files);
            hcfree (out_info);

            return -1;
          }

          if (outfile_check_stat.st_mtime > folder_mtime)
          {
            char **out_files_new = scan_directory (root_directory);

            int out_cnt_new = count_dictionaries (out_files_new);

            outfile_data_t *out_info_new = NULL;

            if (out_cnt_new > 0)
            {
              out_info_new = (outfile_data_t *) hccalloc (out_cnt_new, sizeof (outfile_data_t));

              for (int i = 0; i < out_cnt_new; i++)
              {
                out_info_new[i].file_name = out_files_new[i];

                // check if there are files that we have seen/checked before (and not changed)

                for (int j = 0; j < out_cnt; j++)
                {
                  if (strcmp (out_info[j].file_name, out_info_new[i].file_name) == 0)
                  {
                    struct stat outfile_stat;

                    if (stat (out_info_new[i].file_name, &outfile_stat) == 0)
                    {
                      if (outfile_stat.st_ctime == out_info[j].ctime)
                      {
                        out_info_new[i].ctime = out_info[j].ctime;
                        out_info_new[i].seek  = out_info[j].seek;
                      }
                    }
                  }
                }
              }
            }

            hcfree (out_info);
            hcfree (out_files);

            out_files = out_files_new;
            out_cnt   = out_cnt_new;
            out_info  = out_info_new;

            folder_mtime = outfile_check_stat.st_mtime;
          }

          for (int j = 0; j < out_cnt; j++)
          {
            FILE *fp = fopen (out_info[j].file_name, "rb");

            if (fp != NULL)
            {
              //hc_thread_mutex_lock (status_ctx->mux_display);

              struct stat outfile_stat;

              if (fstat (fileno (fp), &outfile_stat))
              {
                fclose (fp);

                continue;
              }

              if (outfile_stat.st_ctime > out_info[j].ctime)
              {
                out_info[j].ctime = outfile_stat.st_ctime;
                out_info[j].seek  = 0;
              }

              fseeko (fp, out_info[j].seek, SEEK_SET);

              char *line_buf = (char *) hcmalloc (HCBUFSIZ_LARGE);

              while (!feof (fp))
              {
                char *ptr = fgets (line_buf, HCBUFSIZ_LARGE - 1, fp);

                if (ptr == NULL) break;

                size_t line_len = strlen (line_buf);

                if (line_len == 0) continue;

                size_t iter = 1;

                for (size_t i = line_len - 1; i && iter; i--, line_len--)
                {
                  if (line_buf[i] != separator) continue;

                  iter--;

                  int parser_status = PARSER_OK;

                  if ((hash_mode != 2500) && (hash_mode != 2501) && (hash_mode != 6800))
                  {
                    parser_status = hashconfig->parse_func ((u8 *) line_buf, line_len - 1, &hash_buf, hashconfig);
                  }

                  u32 found = 0;

                  if (parser_status == PARSER_OK)
                  {
                    for (u32 salt_pos = 0; (found == 0) && (salt_pos < hashes->salts_cnt); salt_pos++)
                    {
                      if (hashes->salts_shown[salt_pos] == 1) continue;

                      salt_t *salt_buf = &hashes->salts_buf[salt_pos];

                      for (u32 digest_pos = 0; (found == 0) && (digest_pos < salt_buf->digests_cnt); digest_pos++)
                      {
                        u32 idx = salt_buf->digests_offset + digest_pos;

                        if (hashes->digests_shown[idx] == 1) continue;

                        u32 cracked = 0;

                        if (hash_mode == 6800)
                        {
                          if (i == salt_buf->salt_len)
                          {
                            cracked = (memcmp (line_buf, salt_buf->salt_buf, salt_buf->salt_len) == 0);
                          }
                        }
                        else if ((hash_mode == 2500) || (hash_mode == 2501))
                        {
                          // this comparison is a bit inaccurate as we compare only ESSID
                          // call it a bug, but it's good enough for a special case used in a special case
                          // in this case all essid will be marked as cracked that match the essid

                          if (i == salt_buf->salt_len)
                          {
                            cracked = (memcmp (line_buf, salt_buf->salt_buf, salt_buf->salt_len) == 0);
                          }
                        }
                        else
                        {
                          char *digests_buf_ptr = (char *) hashes->digests_buf;

                          memcpy (digest_buf, digests_buf_ptr + (hashes->salts_buf[salt_pos].digests_offset * dgst_size) + (digest_pos * dgst_size), dgst_size);

                          cracked = (sort_by_digest_p0p1 (digest_buf, hash_buf.digest, hashconfig) == 0);
                        }

                        if (cracked == 1)
                        {
                          found = 1;

                          hashes->digests_shown[idx] = 1;

                          hashes->digests_done++;

                          salt_buf->digests_done++;

                          if (salt_buf->digests_done == salt_buf->digests_cnt)
                          {
                            hashes->salts_shown[salt_pos] = 1;

                            hashes->salts_done++;

                            if (hashes->salts_done == hashes->salts_cnt) mycracked (hashcat_ctx);
                          }
                        }
                      }

                      if (status_ctx->devices_status == STATUS_CRACKED) break;
                    }
                  }

                  if (found) break;

                  if (status_ctx->devices_status == STATUS_CRACKED) break;
                }

                if (status_ctx->devices_status == STATUS_CRACKED) break;
              }

              hcfree (line_buf);

              out_info[j].seek = ftello (fp);

              //hc_thread_mutex_unlock (status_ctx->mux_display);

              fclose (fp);
            }
          }
        }
      }

      check_left = outfile_check_timer;
    }
  }

  hcfree (hash_buf.esalt);
  hcfree (hash_buf.hook_salt);

  hcfree (hash_buf.salt);

  hcfree (hash_buf.digest);

  hcfree (out_info);

  hcfree (out_files);

  return 0;
}
Exemple #26
0
static void
scan_directory(const char *basedir, const char *subdir)
{
	char		path[MAXPGPATH];
	DIR		   *dir;
	struct dirent *de;

	snprintf(path, sizeof(path), "%s/%s", basedir, subdir);
	dir = opendir(path);
	if (!dir)
	{
		fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
				progname, path, strerror(errno));
		exit(1);
	}
	while ((de = readdir(dir)) != NULL)
	{
		char		fn[MAXPGPATH];
		struct stat st;

		if (strcmp(de->d_name, ".") == 0 ||
			strcmp(de->d_name, "..") == 0)
			continue;

		/* Skip temporary files */
		if (strncmp(de->d_name,
					PG_TEMP_FILE_PREFIX,
					strlen(PG_TEMP_FILE_PREFIX)) == 0)
			continue;

		/* Skip temporary folders */
		if (strncmp(de->d_name,
					PG_TEMP_FILES_DIR,
					strlen(PG_TEMP_FILES_DIR)) == 0)
			return;

		snprintf(fn, sizeof(fn), "%s/%s", path, de->d_name);
		if (lstat(fn, &st) < 0)
		{
			fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
					progname, fn, strerror(errno));
			exit(1);
		}
		if (S_ISREG(st.st_mode))
		{
			char		fnonly[MAXPGPATH];
			char	   *forkpath,
					   *segmentpath;
			BlockNumber segmentno = 0;

			if (skipfile(de->d_name))
				continue;

			/*
			 * Cut off at the segment boundary (".") to get the segment number
			 * in order to mix it into the checksum. Then also cut off at the
			 * fork boundary, to get the relfilenode the file belongs to for
			 * filtering.
			 */
			strlcpy(fnonly, de->d_name, sizeof(fnonly));
			segmentpath = strchr(fnonly, '.');
			if (segmentpath != NULL)
			{
				*segmentpath++ = '\0';
				segmentno = atoi(segmentpath);
				if (segmentno == 0)
				{
					fprintf(stderr, _("%s: invalid segment number %d in file name \"%s\"\n"),
							progname, segmentno, fn);
					exit(1);
				}
			}

			forkpath = strchr(fnonly, '_');
			if (forkpath != NULL)
				*forkpath++ = '\0';

			if (only_relfilenode && strcmp(only_relfilenode, fnonly) != 0)
				/* Relfilenode not to be included */
				continue;

			scan_file(fn, segmentno);
		}
#ifndef WIN32
		else if (S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))
#else
		else if (S_ISDIR(st.st_mode) || pgwin32_is_junction(fn))
#endif
			scan_directory(path, de->d_name);
	}
	closedir(dir);
}
Exemple #27
0
int straight_ctx_init (hashcat_ctx_t *hashcat_ctx)
{
  straight_ctx_t       *straight_ctx        = hashcat_ctx->straight_ctx;
  user_options_extra_t *user_options_extra  = hashcat_ctx->user_options_extra;
  user_options_t       *user_options        = hashcat_ctx->user_options;

  straight_ctx->enabled = false;

  if (user_options->example_hashes == true) return 0;
  if (user_options->left           == true) return 0;
  if (user_options->opencl_info    == true) return 0;
  if (user_options->show           == true) return 0;
  if (user_options->usage          == true) return 0;
  if (user_options->version        == true) return 0;

  if (user_options->attack_mode == ATTACK_MODE_BF) return 0;

  straight_ctx->enabled = true;

  /**
   * generate NOP rules
   */

  if ((user_options->rp_files_cnt == 0) && (user_options->rp_gen == 0))
  {
    straight_ctx->kernel_rules_buf = (kernel_rule_t *) hcmalloc (sizeof (kernel_rule_t));

    straight_ctx->kernel_rules_buf[0].cmds[0] = RULE_OP_MANGLE_NOOP;

    straight_ctx->kernel_rules_cnt = 1;
  }
  else
  {
    if (user_options->rp_files_cnt)
    {
      const int rc_kernel_load = kernel_rules_load (hashcat_ctx, &straight_ctx->kernel_rules_buf, &straight_ctx->kernel_rules_cnt);

      if (rc_kernel_load == -1) return -1;
    }
    else if (user_options->rp_gen)
    {
      const int rc_kernel_generate = kernel_rules_generate (hashcat_ctx, &straight_ctx->kernel_rules_buf, &straight_ctx->kernel_rules_cnt);

      if (rc_kernel_generate == -1) return -1;
    }
  }

  /**
   * wordlist based work
   */

  if (user_options->attack_mode == ATTACK_MODE_STRAIGHT)
  {
    if (user_options_extra->wordlist_mode == WL_MODE_FILE)
    {
      for (int i = 0; i < user_options_extra->hc_workc; i++)
      {
        char *l0_filename = user_options_extra->hc_workv[i];

        // at this point we already verified the path actually exist and is readable

        if (hc_path_is_directory (l0_filename) == true)
        {
          char **dictionary_files;

          dictionary_files = scan_directory (l0_filename);

          if (dictionary_files != NULL)
          {
            qsort (dictionary_files, (size_t) count_dictionaries (dictionary_files), sizeof (char *), sort_by_stringptr);

            for (int d = 0; dictionary_files[d] != NULL; d++)
            {
              char *l1_filename = dictionary_files[d];

              if (hc_path_read (l1_filename) == false)
              {
                event_log_error (hashcat_ctx, "%s: %s", l1_filename, strerror (errno));

                hcfree (dictionary_files);

                return -1;
              }

              if (hc_path_is_file (l1_filename) == true)
              {
                const int rc = straight_ctx_add_wl (hashcat_ctx, l1_filename);

                if (rc == -1)
                {
                  hcfree (dictionary_files);

                  return -1;
                }
              }
            }
          }

          hcfree (dictionary_files);
        }
        else
        {
          const int rc = straight_ctx_add_wl (hashcat_ctx, l0_filename);

          if (rc == -1) return -1;
        }
      }

      if (straight_ctx->dicts_cnt == 0)
      {
        event_log_error (hashcat_ctx, "No usable dictionary file found.");

        return -1;
      }
    }
  }
  else if (user_options->attack_mode == ATTACK_MODE_COMBI)
  {

  }
  else if (user_options->attack_mode == ATTACK_MODE_BF)
  {

  }
  else if (user_options->attack_mode == ATTACK_MODE_HYBRID1)
  {
    for (int i = 0; i < user_options_extra->hc_workc - 1; i++)
    {
      char *l0_filename = user_options_extra->hc_workv[i];

      // at this point we already verified the path actually exist and is readable

      if (hc_path_is_directory (l0_filename) == true)
      {
        char **dictionary_files;

        dictionary_files = scan_directory (l0_filename);

        if (dictionary_files != NULL)
        {
          qsort (dictionary_files, (size_t) count_dictionaries (dictionary_files), sizeof (char *), sort_by_stringptr);

          for (int d = 0; dictionary_files[d] != NULL; d++)
          {
            char *l1_filename = dictionary_files[d];

            if (hc_path_read (l1_filename) == false)
            {
              event_log_error (hashcat_ctx, "%s: %s", l1_filename, strerror (errno));

              hcfree (dictionary_files);

              return -1;
            }

            if (hc_path_is_file (l1_filename) == true)
            {
              const int rc = straight_ctx_add_wl (hashcat_ctx, l1_filename);

              if (rc == -1)
              {
                hcfree (dictionary_files);

                return -1;
              }
            }
          }
        }

        hcfree (dictionary_files);
      }
      else
      {
        const int rc = straight_ctx_add_wl (hashcat_ctx, l0_filename);

        if (rc == -1) return -1;
      }
    }

    if (straight_ctx->dicts_cnt == 0)
    {
      event_log_error (hashcat_ctx, "No usable dictionary file found.");

      return -1;
    }
  }
  else if (user_options->attack_mode == ATTACK_MODE_HYBRID2)
  {
    for (int i = 1; i < user_options_extra->hc_workc; i++)
    {
      char *l0_filename = user_options_extra->hc_workv[i];

      // at this point we already verified the path actually exist and is readable

      if (hc_path_is_directory (l0_filename) == true)
      {
        char **dictionary_files;

        dictionary_files = scan_directory (l0_filename);

        if (dictionary_files != NULL)
        {
          qsort (dictionary_files, (size_t) count_dictionaries (dictionary_files), sizeof (char *), sort_by_stringptr);

          for (int d = 0; dictionary_files[d] != NULL; d++)
          {
            char *l1_filename = dictionary_files[d];

            if (hc_path_read (l1_filename) == false)
            {
              event_log_error (hashcat_ctx, "%s: %s", l1_filename, strerror (errno));

              hcfree (dictionary_files);

              return -1;
            }

            if (hc_path_is_file (l1_filename) == true)
            {
              const int rc = straight_ctx_add_wl (hashcat_ctx, l1_filename);

              if (rc == -1)
              {
                hcfree (dictionary_files);

                return -1;
              }
            }
          }
        }

        hcfree (dictionary_files);
      }
      else
      {
        const int rc = straight_ctx_add_wl (hashcat_ctx, l0_filename);

        if (rc == -1) return -1;
      }
    }

    if (straight_ctx->dicts_cnt == 0)
    {
      event_log_error (hashcat_ctx, "No usable dictionary file found.");

      return -1;
    }
  }

  return 0;
}