Question

In: Computer Science

Can anyone who is knowledgable with multi-threading take a look at the following c++ program posted...

Can anyone who is knowledgable with multi-threading take a look at the following c++ program posted below and take a swing at making it multi-threaded (and if possible please use C++ 2011 standard threading). Its only one part of the overall program, so there wont be anything to compile/test but if you could take a crack at it that would be great. Even if it doesnt work when I test your program, ill still give credit/like since then ill at least have somewhere to start and a better understanding of what needs to be done from your code. If you have any specific questions please and ill do my best to answer them, thank you!


scan1.cpp
/*
* This program takes the name of a password file and some guessing parameters
* and tries to guess the passwords by simple enumeration. Command line
* is the
* filename charset short long
* Where charset is either a string of characters from which the password
* is drawn, or one of these special names:
* ASCII Printable ascii, 32-126
* DIGITS 0-9
* ALNUM Alphanumeric characters, 0-9A-Za-z
* Short and long are range of lengths of the passwords to try.
*/

#include <crypt.h>
#include <errno.h>

#include <cstring>
#include <cstdlib>

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <memory>

#include "enum.h"

using std::string;

/*
* Try the indicated password against each recorded password in the file.
* Return true if any matched, false otw.
*/
bool scan(const std::list<std::pair<string,string>> &passwords, string pass)
{
struct crypt_data pass_data; // Password data area.
string line; // Input line.
bool found = false; // We found something.

// Clear the data area.
memset(&pass_data, 0, sizeof pass_data);

// Try each of the passwords.
for(auto p: passwords) {
// Encrypt the guess using the method recorded for the existing.
// (crypt_r only reads the encryption type and salt from the
// exiting password, not the hash itself.)
char *ret = crypt_r(pass.c_str(), p.second.c_str(), &pass_data);

// See if we got a match.
if(ret && ret == p.second) {
std::cout << p.first << ": " << pass << std::endl;
found = true;
}
}
return found;
}

int main(int argc, char **argv)
{
// Check args.
if(argc != 5) {
std::cerr << "Usage: " << argv[0]
<< " filename charset min max" << std::endl;
std::cerr << " charset is DIGITS, ALNUM, ASCII or a set of "
<< "characters." << std::endl;
exit(1);
}

// Size range.
int min = atoi(argv[3]);
int max = atoi(argv[4]);

// Create an appropriate enumerator object.
std::unique_ptr<pwd_enum> enumerator;
string charset = argv[2];
if(charset == "DIGITS") {
enumerator.reset(new pwd_enum('0', '9', min, max));
} else if(charset == "ALNUM") {
enumerator.reset
(new pwd_enum("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz", min, max));
} else if(charset == "ASCII") {
enumerator.reset(new pwd_enum(' ', '~', min, max));
} else {
enumerator.reset(new pwd_enum(charset, min, max));
}

// Try to open the file.
std::ifstream passfile(argv[1], std::fstream::binary);
if(!passfile) {
std::cerr << "Unable to open " << argv[1] << std::endl;
exit(1);
}

// Read the passwords from the file.
std::list<std::pair<string,string>> passwords;
string line;
while(std::getline(passfile, line)) {
// Extract account
int loc = line.find(":");
if(loc == string::npos) continue;
string acct = line.substr(0,loc);

// Extract crypted password, leaving it in line.
line.erase(0,loc+1);
loc = line.find(":");
if(loc != string::npos) {
acct.erase(loc);
}

// Add the account and password to the list.
passwords.push_back(std::make_pair(acct, line));
}

// This will happen at the end anyway, but we're going to spend a
// long time in the next loop, so let's release the resource now.
passfile.close();

// Run through the passwords.
string pw;
bool found = false;
while((pw = enumerator->next()) != "") {
found = scan(passwords, pw) || found;
//std::cout << pw << std::endl;
}
if(!found)
std::cout << "No passwords matched." << std::endl;
}

.

Solutions

Expert Solution

scan1.cpp
/*
* This program takes the name of a password file and some guessing parameters
* and tries to guess the passwords by simple enumeration. Command line
* is the
* filename charset short long
* Where charset is either a string of characters from which the password
* is drawn, or one of these special names:
* ASCII   Printable ascii, 32-126
* DIGITS 0-9
* ALNUM Alphanumeric characters, 0-9A-Za-z
* Short and long are range of lengths of the passwords to try.
*/

#include <crypt.h>
#include <errno.h>

#include <pthread.h>

#include <cstring>
#include <cstdlib>

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <memory>

#include "enum.h"

using std::string;

// Create an appropriate enumerator object.
std::unique_ptr<pwd_enum> enumerator;

pthread_mutex_t lock;

/* The Program's critical section data structure is 'passwords', which will be protected using mutex_lock */

std::list<std::pair<string,string>> passwords;

/*
* Try the indicated password against each recorded password in the file.
* Return true if any matched, false otw.
*/
bool scan(const std::list<std::pair<string,string>> &passwords, string pass)
{
   struct crypt_data pass_data;   // Password data area.
   string line;           // Input line.
   bool found = false;       // We found something.

   // Clear the data area.
   memset(&pass_data, 0, sizeof pass_data);

   // Try each of the passwords.

   /* Take the mutex lock */
   pthread_mutex_lock(&lock);  

   for(auto p: passwords) {
       // Encrypt the guess using the method recorded for the existing.
       // (crypt_r only reads the encryption type and salt from the
       // exiting password, not the hash itself.)
       char *ret = crypt_r(pass.c_str(), p.second.c_str(), &pass_data);

       // See if we got a match.
       if(ret && ret == p.second) {
           std::cout << p.first << ": " << pass << std::endl;
           found = true;
       }
   }

   /* release the mutex lock */
   pthread_mutex_unlock(&lock);
  
   return found;
}

void *read_thread(void * arg)
{
   // Try to open the file.
   std::ifstream passfile(argv[1], std::fstream::binary);
   if(!passfile) {
       std::cerr << "Unable to open " << argv[1] << std::endl;
       exit(1);
   }

   // Read the passwords from the file.
   string line;
   while(std::getline(passfile, line)) {
       // Extract account
       int loc = line.find(":");
       if(loc == string::npos) continue;
       string acct = line.substr(0,loc);

       // Extract crypted password, leaving it in line.
       line.erase(0,loc+1);
       loc = line.find(":");
       if(loc != string::npos) {
           acct.erase(loc);
       }

       // Add the account and password to the list.

       /* Take the mutex lock */
       pthread_mutex_lock(&lock);  

       passwords.push_back(std::make_pair(acct, line));
      
       /* release the mutex lock */
       pthread_mutex_unlock(&lock);

   }

   // This will happen at the end anyway, but we're going to spend a
   // long time in the next loop, so let's release the resource now.
   passfile.close();

}

void *scan_thread(void * arg)
{
   // Run through the passwords.
   string pw;
   bool found = false;
   while((pw = enumerator->next()) != "") {
       found = scan(passwords, pw) || found;
       //std::cout << pw << std::endl;
   }
   if(!found)
       std::cout << "No passwords matched." << std::endl;
}


int main(int argc, char **argv)
{
   pthread_t t1, t2;

   // Check args.
   if(argc != 5) {
       std::cerr << "Usage: " << argv[0]
           << " filename charset min max" << std::endl;
       std::cerr << " charset is DIGITS, ALNUM, ASCII or a set of "
           << "characters." << std::endl;
       exit(1);
   }

   // Size range.
   int min = atoi(argv[3]);
   int max = atoi(argv[4]);

   string charset = argv[2];
   if(charset == "DIGITS") {
       enumerator.reset(new pwd_enum('0', '9', min, max));
   } else if(charset == "ALNUM") {
       enumerator.reset
           (new pwd_enum("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
               "abcdefghijklmnopqrstuvwxyz", min, max));
   } else if(charset == "ASCII") {
       enumerator.reset(new pwd_enum(' ', '~', min, max));
   } else {
       enumerator.reset(new pwd_enum(charset, min, max));
   }

   /* Initialize the mute lock for use with multi-threading */
   pthread_mutex_init(&lock);

   /* Create the two threads prime_thread and print_thread */

pthread_create( &t1, NULL, read_thread, (void *) passfile);

pthread_create( &t2, NULL, scan_thread, NULL);

/* Wait for the threads to finish */

pthread_join(t1, NULL);
pthread_join(t2, NULL);

pthread_exit(0);

}


Related Solutions

C program for copying data from one directory to another using multi threading for linux using...
C program for copying data from one directory to another using multi threading for linux using command line arrangement. Program will take two arguments: 1: Source 2: Destination it will copy all the files from source to destination recursively Deadline: 4 hours from now.
I have this matlab program, and need to turn it into a C++ program. Can anyone...
I have this matlab program, and need to turn it into a C++ program. Can anyone help me with this? % Prompt the user for the values x and y x = input ('Enter the x coefficient: '); y = input ('Enter the y coefficient: '); % Calculate the function f(x,y) based upon % the signs of x and y. if x >= 0    if y >= 0        fun = x + y;    else        fun = x + y^2;    end...
What sort of multi-national businesses are out there? What are they doing? Take a look at...
What sort of multi-national businesses are out there? What are they doing? Take a look at the Fortune Global 500 list. This is a good start as you pay attention to multi-national enterprises (MNEs) throughout the world. Now select a company from the Fortune Global 500 list for 2017. Do NOT pick a company in the top 20, pick something a little more obscure. Do not select a company based in the United States. Describe this company by telling me...
Can anyone assist me with the following problem posted below? I just need some simple use...
Can anyone assist me with the following problem posted below? I just need some simple use case diagrams made for all the systems at play as described, ill do my best to answer any questions you may have, thank you! SYSTEM DETAILS: The warehouse stores items for purchase by customers. To expedite order fulfillment, stock of most items is kept and a minimum reorder is made when stocks are below a set trigger quantity. Items ordered that are not in...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else...
C++ program that can take in EITHER "infix" or "prefix" (NOT POSTFIX) and transforms it into...
C++ program that can take in EITHER "infix" or "prefix" (NOT POSTFIX) and transforms it into the other one. Should use stack and have infixToPrefix and prefixToInfix functions with a simple main function for execution.
Need to make Java code as following: Create a dice playing threading program to do the...
Need to make Java code as following: Create a dice playing threading program to do the following: 1. Start a thread for a process to simulate a computer rolling a die 1000 times. 2. Start another thread for a process to simulate a user rolling a die 1000 times. 3. Keep track of rolls for user and computer in an array(s). 4. Display on screen when the computer thread starts, the rolls, and when the computer thread ends. 5. Display...
Take the following program and include overload functions into it. Display result of function. C++ Program:...
Take the following program and include overload functions into it. Display result of function. C++ Program: #include <iostream> using namespace std; // this is the additional function string read() {     string input;     cout << "Enter input: ";     cin >> input;     return input; } int main() {     // call function here     string output = read();     cout << "You entered: " << output; }
Edit the given program to produce the following output in c++ mode: - Take in the...
Edit the given program to produce the following output in c++ mode: - Take in the name of a superhero & tell him how many villains he/she has to defeat today - The number of villains is randomly generated and should be a number between 11 and 42. - Use a seed of 7. Hint: Compile the program first before making edits What is your name? Hello Captain America There are 42 villains you need to defeat today Oops! one...
Take the following C++ program and translate it into assembly language( pep9 ) #include using namespace...
Take the following C++ program and translate it into assembly language( pep9 ) #include using namespace std; char ch; int main() {    cin >> ch;    cout << "You inputted " << ch << endl;    ch++;    cout << "Next character is " << ch << endl; if (ch <= ‘Z’)         cout << “Could be luppercase\n”;    return 0; }
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT