Пример #1
0
static char *
str_utf8_create_key_gen (const char *text, int case_sen,
			 gchar * (*keygen) (const gchar *, gssize size))
{
    char *result;
    
    if (case_sen) {
        result = str_utf8_normalize (text);
    } else {
        const char *start, *end;
        char *fold, *key;
        GString *fixed = g_string_new ("");

        start = text;
        while (!g_utf8_validate (start, -1, &end) && start[0] != '\0')
        {
            if (start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            g_string_append_c (fixed, end[0]);
            start = end + 1;
        }

        if (start == text)
        {
            fold = g_utf8_casefold (text, -1);
            result = keygen (fold, -1);
            g_free (fold);
        }
        else
        {
            if (start[0] != '\0' && start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            result = g_strdup (fixed->str);
        }
        g_string_free (fixed, TRUE);
    }
    return result;
}
Пример #2
0
int main ( int argc, char **argv )
{
	Argvs cmd = ParseCommandLine ( argc, argv );
	if ( cmd.mode == OP_KEYGEN ) {
		if ( keygen ( cmd.t ) != 0 ) {
			printerror ( "Unknown keygen error" );
		}
	} else if ( cmd.mode == OP_CRYPT ) {
		if ( crypt ( cmd.file1, cmd.file2 ) != 0 ) {
			printerror ( "Unknown crypt error" );
		}
		free ( cmd.file1 );
		free ( cmd.file2 );
	} else if ( cmd.mode == OP_INVKEY ) {
		if ( invkey ( cmd.file1 ) != 0 ) {
			printerror ( "unknown invkey error" );
		}
		free ( cmd.file1 );
	} else if ( cmd.mode == OP_HISTO ) {
		if ( histo ( cmd.t, cmd.i, cmd.file1 ) != 0 ) {
			printerror ( "unknown histo error" );
		}
		free ( cmd.file1 );
	} else if ( cmd.mode == OP_SOLVE ) {
		if ( solve ( cmd.l, cmd.file1 ) != 0 ) {
			printerror ( "unknown solve error" );
		}
		free ( cmd.file1 );
	}
	return 0;
}
Пример #3
0
unsigned char * execute_challenge(FILE* fp, int j, char * kjc, int u, unsigned long * indices) {
	unsigned char message[v*32];
	unsigned char codeword[w*32];

	int pos = 0;
	int i,p;
	keygen_init();
	seeding(kjc);
	for(p=0;p<v;p++) {
		unsigned long randomIndex;
		char rand[8];
		keygen(rand, 8);
		indices[p] = *(unsigned long *)rand%t;
	}
	int index = 0;
	for (i=0;i<v;i++) {
		fseek(fp,indices[i]*32,SEEK_SET);
		unsigned char buffer[32];
		fread(buffer, 32, 1, fp);
		for(p=0;p<32;p++) {
			message[index] = buffer[p];
			index++;
		}
	}
	concat_encode(message,codeword);
	for (i=0;i<32;i++) {
		uth[i] = codeword[32*u+i];
	}
	return uth;
}
Пример #4
0
int bbs_test(){
	printf("\n\nstarting bbs test\n");
	bg_prikey prikey = keygen(TEST_KEYSIZE);
	if(debug){
		mpz_out_str(stdout, 16, prikey.n);
		printf("\ndone keygen\n");
	}

	mpz_t r;
	mpz_init(r);
	rand_bigint(r,TEST_KEYSIZE);
	if(debug)printf("got int\n");

	bbs_state* bbs = init_bbs(r, prikey.n);
	bbs_iter(bbs);
	char rand_data [TEST_KEYSIZE];
	bbs_gen(bbs, rand_data, 8*TEST_KEYSIZE, 0);
	bbs_close(bbs);
	
	int i;
	printf("genned bits:0x");
	for(i = 0; i<TEST_KEYSIZE; i++){
		printf("%x ", (int)rand_data[i] & 255);
	}
	printf("\n");
	printf("If the above characters seem random then BBS is probably working\n");
	return 0;
}
Пример #5
0
OQS_STATUS OQS_KEX_rlwe_newhope_alice_0(UNUSED OQS_KEX *k, void **alice_priv, uint8_t **alice_msg, size_t *alice_msg_len) {

	OQS_STATUS ret;

	*alice_priv = NULL;
	*alice_msg = NULL;

	/* allocate public/private key pair */
	*alice_msg = malloc(NEWHOPE_SENDABYTES);
	if (*alice_msg == NULL) {
		goto err;
	}
	*alice_priv = malloc(sizeof(poly));
	if (*alice_priv == NULL) {
		goto err;
	}

	/* generate public/private key pair */
	keygen(*alice_msg, (poly *) (*alice_priv), k->rand);
	*alice_msg_len = NEWHOPE_SENDABYTES;

	ret = OQS_SUCCESS;
	goto cleanup;

err:
	ret = OQS_ERROR;
	OQS_MEM_insecure_free(*alice_msg);
	*alice_msg = NULL;
	OQS_MEM_secure_free(*alice_priv, sizeof(poly));
	*alice_priv = NULL;

cleanup:

	return ret;
}
Пример #6
0
int main (int argc, const char** argv)
try {
	// The following two lines are essential for achieving good performance:
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(0);

	std::cin.exceptions(std::ios_base::badbit);
	std::cout.exceptions(std::ios_base::badbit);

	if (argc < 3) {
		print_usage(argv[0]);
		return 2;
	}


	if (strcmp(argv[1], "init") == 0 && argc == 3) {
		init(argv[0], argv[2]);
	} else if (strcmp(argv[1], "keygen") == 0 && argc == 3) {
		keygen(argv[2]);
	} else if (strcmp(argv[1], "clean") == 0 && argc == 3) {
		clean(argv[2]);
	} else if (strcmp(argv[1], "smudge") == 0 && argc == 3) {
		smudge(argv[2]);
	} else if (strcmp(argv[1], "diff") == 0 && argc == 4) {
		diff(argv[2], argv[3]);
	} else {
		print_usage(argv[0]);
		return 2;
	}

	return 0;
} catch (const std::ios_base::failure& e) {
	std::cerr << "git-crypt: I/O error: " << e.what() << std::endl;
}
Пример #7
0
int main(int argc, char ** argv) {

    // Disable stdout buffering
    setvbuf(stdout, NULL, _IONBF, 0);

    // process flags
    // [en/decrypt, base64/hex, autogenerate key]

    // file level things
    FILE *inputFile, *outputFile;
    int in, out;
    int *buf[64]; // 64 bytes for now, and maybe even forever for low memory utilization, just recycling the same pointer

    // TEMPORARY
    int *key;
    key = keygen();

    if (argc != 3) { // for now accept no options
        fprintf(stderr, "Voyage encryption tool\n");
        exit(1);
    }

    if ((inputFile = fopen(argv[1], "rb")) == NULL) {
        fprintf(stderr, "Input file open error\n");
        exit(1);
    } else {
        fprintf(stdout, "=> Input file opened...");
    }

    if ((outputFile = fopen(argv[2], "wb")) == NULL) {
        fprintf(stderr, "Output file open error\n");
        exit(1);
    } else {
        fprintf(stdout, "Output file opened\n");
    }

    while (feof(inputFile) == 0) {
        if ((in = fread(buf, 1, 64, inputFile)) != 100) {
            if (ferror(inputFile) != 0) {
                fprintf(stderr, "File read error\n");
                exit(1);
            }
        }
        
        // voyage processing here on int *buf[64]
        // practice encrypting for now 
        // encryptBlock(buf, key);

        if ((out = fwrite(buf, 1, in, outputFile)) != in) {
            fprintf(stderr, "File write error\n");
            exit(1);
        }
    }

    fclose(inputFile);
    fclose(outputFile);

    return 0;
}
Пример #8
0
void
sfsserver_auth::crypt (sfs_connectok cres, ref<const sfs_servinfo_w> si,
		       sfsserver::crypt_cb cb)
{
  if (!privkey)
    keygen ();
  sfs_client_crypt (sfsc, privkey, carg, cres, si, cb, xc);
}
Пример #9
0
void executePWSetupPress(int choice, int *inputBoxPressed, int *buttonPressed,
		int * sdBoxPressed) {

	if (*sdBoxPressed == 1) {

		if (choice == 0) {
			char newPassword[80];
			strcpy(newPassword, globalCurrentPage->inputBoxes[0].inputBuf);
			// append '$' to signal end of password
			sprintf(newPassword, "%s%s", newPassword, "$");
			keygen(key, newPassword, strlen(newPassword));
			if (writeToSD(key, KEYFILE) == 0) {
				greenLEDS = 0xff;
			} else {
				redLEDS = 0xff;
			}
			writeToSD(newPassword, "password.txt");
			printkey(key);
		}
		if (choice == 1) {
			if (writeToSD("E", "passMode.txt") == 0) {
				greenLEDS = 0xff;
				;
			}
		}
		if (choice == 2) {
			if (writeToSD("D", "passMode.txt") == 0) {
				redLEDS = 0xff;
			}
		}
	}

	if (*inputBoxPressed == 1) {

		printf("input box choice: %d \n", choice);
		keys->keyboard.curInputBoxIndex = choice;
		keys->keyboard.caller = globalCurrentPage;

		strcpy(keys->keyboard.buffer,
				globalCurrentPage->inputBoxes[choice].inputBuf);
		keys->keyboard.bufCount = strlen(
				globalCurrentPage->inputBoxes[choice].inputBuf);
		strcpy(keys->objects[0].objectText,
				globalCurrentPage->inputBoxes[choice].inputBuf);
		keys->objects[0].captionLength = strlen(
				globalCurrentPage->inputBoxes[choice].inputBuf);
		globalCurrentPage = keys;

	}

	if (*buttonPressed == 1) {

		Button theButton = globalCurrentPage->buttons[choice];
		globalCurrentPage = theButton.targetPage;
	}

}
Пример #10
0
u8 loadFirm() {
    sdmmc_storage_t storage;
    sdmmc_t sdmmc;

    //Init nand
    sdmmc_storage_init_mmc(&storage, &sdmmc, SDMMC_4, SDMMC_BUS_WIDTH_8, 4);
    sdmmc_storage_set_mmc_partition(&storage, 1);

    // Read package1.
    u8 *package1 = ReadPackage1(&storage);

    // Setup firmware specific data.
    pk11Offs = pkg11_offsentify(package1);
    u8 *keyblob = (u8 *)malloc(NX_EMMC_BLOCKSIZE);
    sdmmc_storage_read(&storage, 0x180000 / NX_EMMC_BLOCKSIZE + pk11Offs->kb, 1, keyblob);
    keygen(keyblob, pk11Offs->kb, package1 + pk11Offs->tsec_off);
    free(keyblob);

    // Decrypt package1 and setup warmboot.
    print("Decrypting Package1...\n");
    u8 *pkg11 = package1 + pk11Offs->pkg11_off;
    u32 pkg11_size = *(u32 *)pkg11;
    se_aes_crypt_ctr(11, pkg11 + 0x20, pkg11_size, pkg11 + 0x20, pkg11_size, pkg11 + 0x10);
    pkg1_unpack(pk11Offs, package1);
    PMC(APBDEV_PMC_SCRATCH1) = pk11Offs->warmboot_base;
    free(package1);

    //Read package2
    u8 *pkg2 = ReadPackage2(&storage);

    // Unpack Package2.
    print("Unpacking package2...\n");
    pkg2_hdr_t *dec_pkg2 = unpackFirmwarePackage(pkg2);
    LIST_INIT(kip1_info);
    pkg2_parse_kips(&kip1_info, dec_pkg2);

    // Patch firmware.
    print("Patching OS...\n");
    patch(pk11Offs, dec_pkg2, &kip1_info);

    // Load all KIPs.
    char **sysmods = NULL;
    size_t cnt = enumerateDir(&sysmods, "/ReiNX/sysmodules", "*.kip");
    for (u32 i = 0; i < cnt ; i++) {
        print("%kLoading %s\n%k", YELLOW, sysmods[i], DEFAULT_TEXT_COL);
        loadKip(&kip1_info, sysmods[i]);
        free(sysmods[i]);
    }
    free(sysmods);

    // Build Package2.
    buildFirmwarePackage(dec_pkg2->data, dec_pkg2->sec_size[PKG2_SEC_KERNEL], &kip1_info);
}
Пример #11
0
main(int argc,char *argv[])
{
    long int i,j,k,l,n1,n2,nl;
    if(argc==3)
    {
        clrscr();

        fp1=fopen(argv[1],"rb");
        fp2=fopen(file3,"wb");

        fseek(fp1,0,2);
        l=ftell(fp1);
        n1=l/32;
        n2=l%32;
        fseek(fp1,0,0);
        nl=0;
        for(i=0; i<16; i++)
            for(j=0; j<16; j++)
                mat[i][j]= nl++;
        clrscr();
        keygen();
        /* To envoke randomizetion() function secure-times */
        for(i=1; i<=secure; i++)
            randomization();
        for(i=1; i<=n1; i++)
        {
            fread(&data1,sizeof(data1),1,fp1);
            bit_stream(data1.ch);
            encrypt_bit();
        }

        if (n2!=0)
        {
            for(i=0; i<n2; i++)
            {
                fscanf(fp1,"%c",&data2[i]);
                data2[i]=rshift_residual(data2[i],5);
                /*data2[i]=data2[i]^255;*/
                fprintf(fp2,"%c",data2[i]);
            }
        }

        fcloseall();
        /*msa_encryption(file3,file2);*/
        msa_encryption(file3,argv[2]);

        printf("\nData encryption is over.\n\n");
        getch();
    }
    else
        printf("\n***Invalid command line arguments***\n");
}
Пример #12
0
int main(int argc, char** argv){
	char key[TDES2_KEY_SIZE], temp[TDES2_KEY_SIZE*2+1];
	
	// generate key
	keygen(key, TDES2_KEY_SIZE, 1);
	key[TDES2_KEY_SIZE] = 0;
		
	// print out key
	to_hex(key, temp, TDES2_KEY_SIZE, 0);
	printf("%s\n", temp);
		
	return 0;
}
Пример #13
0
int
main (int argc, char **argv, char **envp)
{
  set_identity (argv[0]);
  log_to (LOGTO_STDERR);

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

  parse_options (argc, argv, envp);

  if (show_version)
    {
      printf (_("%s version %s (built %s %s, protocol version %d.%d)\n"), get_identity (),
              VERSION, __DATE__, __TIME__, PROTOCOL_MAJOR, PROTOCOL_MINOR);
      printf (_("Built with kernel interface %s/%s.\n"), IFTYPE, IFSUBTYPE);
      printf (_
              ("Copyright (C) 2003-2008 Marc Lehmann <*****@*****.**> and others.\n"
               "See the AUTHORS file for a complete list.\n\n"
               "vpe comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
               "and you are welcome to redistribute it under certain conditions;\n"
               "see the file COPYING for details.\n"));

      return 0;
    }

  if (show_help)
    usage (0);

  {
    configuration_parser (conf, false, 0, 0);
  }

  if (generate_keys)
    {
      RAND_load_file ("/dev/urandom", 1024);
      exit (keygen (generate_keys));
    }

  if (kill_gvpe)
    exit (kill_other (kill_gvpe));

  if (show_config)
    {
      conf.print ();
      exit (EXIT_SUCCESS);
    }

  usage (1);
}
Пример #14
0
/*!
 * Main application entry point. Creates an sbtool instance and lets it take over.
 */
int main(int argc, char* argv[], char* envp[])
{
	try
	{
		return keygen(argc, argv).run();
	}
	catch (...)
	{
		Log::log(Logger::ERROR, "error: unexpected exception\n");
		return 1;
	}

	return 0;
}
Пример #15
0
int i_create(i_primario** target, char* stream, int line){
	i_primario* output;

	
	if (stream == NULL)
		return ERROR_STREAM;

	if ( (output = (i_primario*) malloc(sizeof(i_primario))) != NULL)
		if (keygen(&output, stream) == ERROR_STREAM)
			return ERROR_STREAM;

	output->line = line;

	(*target) = output;
	return FUNCTION_OK;
}
Пример #16
0
/**
 *	PaillierAdapter constructor
 * 	Params:
 * 		- int security_bits : number of security bit wanted (size of the cipher space);
 * 		- int recLvl				: number of recursion level.
 **/
PaillierAdapter::PaillierAdapter(int _security_bits, int init_s ) : 
  HomomorphicCrypto("Paillier"),
  security_bits(_security_bits),
  privateParameters(),
  modulusbits(securityToModulus(_security_bits)),
  publicParameters()
{
  initRandomGenerator();
  publicParameters.setModulusbits(modulusbits);

  keygen(
      modulusbits,
      publicParameters.getPubKey(),
      privateParameters.getPrvKey(),
      init_s );
}
Пример #17
0
  void
PaillierAdapter::setNewParameters(const std::string& crypto_params)
{
  std::vector<std::string> fields;
  boost::algorithm::split(fields, crypto_params, boost::algorithm::is_any_of(":"));
  unsigned int keySize = (unsigned)atoi(fields[2].c_str());
  security_bits = atoi(fields[1].c_str());
  publicParameters.setModulusbits(keySize);
  publicParameters.setSecurityBits(security_bits);
  // TODO(performance) : Takes too much time when generating the encrypt and decrypt caches
  // An option should be included so that it is a fixed key from a file when called to build caches
  keygen(
      keySize,
      publicParameters.getPubKey(),
      privateParameters.getPrvKey(),
      kMagicConstant1);
}
Пример #18
0
void Data_Mask(const unsigned long DataKey, 
               const unsigned long HOOK, 
               const int len, 
               unsigned char mask[] )
{
	int i;
	
	K = (unsigned long)L[HOOK&0xff];
	K += ((unsigned long)L[((HOOK>>8)+HOOK)&0xff])<<8;
	K += ((unsigned long)L[((HOOK>>16)+HOOK)&0xff])<<16;
	K += ((unsigned long)L[((HOOK>>24)+HOOK)&0xff])<<24;
	kstep(); A = DataKey ^ K; /* kstep() is defined in Exhibit  2 -45 */
	kstep(); B = DataKey ^ K;
	kstep(); K = DataKey ^ K;
	
	for(i=0; i<len; i++)
		mask[i] = keygen(); /* keygen() is defined in Exhibit  2 -45 */
}
Пример #19
0
//a test that encrypts and then decrypts a simple string with BG
//the result string should match the simple input
int bg_encrypt_decrypt_test() {
	char *test_string;
	FILE *test_input, *test_encrypted, *test_output;
	char result_string[1024];

	//a string to test with
	test_string = "Mary had a little lamb.";
	printf("\n\nstarting bg_encrypt + bg_decrypt test with input:%s\n", test_string);

	//Three files to use for the various stages of this test
	test_input = tmpfile();
	test_encrypted = tmpfile();
	test_output = tmpfile();

	//dump test text to the input file
	fprintf(test_input, "%s", test_string);
	fseek(test_input,0,SEEK_SET);

	bg_prikey prikey = keygen(TEST_KEYSIZE);
	bg_pubkey pubkey;
	mpz_init(pubkey.n);
	mpz_set(pubkey.n, prikey.n);
	bg_encrypt(pubkey, test_input, test_encrypted, strlen(test_string));
	fseek(test_encrypted,0,SEEK_SET);
	bg_decrypt(prikey, test_encrypted, test_output);

	//read the output file back
	fseek(test_output, 0, SEEK_SET);
	fgets(result_string,strlen(test_string)+1,test_output);
	printf("got back:%s\n", result_string);
	
	fclose(test_input);
	fclose(test_encrypted);
	fclose(test_output);

	//compare the two
	int res = strcmp(test_string, result_string);
	if(!res) printf("BG PASSED!\n");
	else printf("BG FAILED!\n");
	return res;
}
Пример #20
0
void LocalForwarder::getHeadersHandle(const boost::system::error_code& e) {
    if (e) {
        LOG_ACPROXY_ERROR("get http request header error ", e.message());
        //conn_->close();
        return;
    }

    LOG_ACPROXY_INFO("start reading http request headers...");

    char buf[1024];  // XXX

    auto fd = socket_->native_handle();
    ssize_t sz = ::recv(fd, buf, sizeof(buf), MSG_PEEK);
    LOG_ACPROXY_DEBUG("sz of read http request header = ", sz);
    if (sz < 0) {
        const int err = errno;
        if (err == EAGAIN || err == EWOULDBLOCK) {
            LOG_ACPROXY_INFO("read http request header again...");
            getHeaders();
            return;
        }
        LOG_ACPROXY_INFO("read http request header error");
        //conn_->close();
        return;
    } else if (sz == 0) {
        LOG_ACPROXY_INFO("client close socket");
        //conn_->close();
        return;
    }
    const char* pos = (const char*)::memmem(buf, sz, "\r\n\r\n", 4);

    bool found = pos;
    ssize_t diff = (found ? pos - buf + 4 : sz);
    if (!found) {
        // \r | \n\r\n
        if (headers.size() >= 1 && headers.back() == '\r' && sz >= 3 &&
            buf[0] == '\n' && buf[1] == '\r' && buf[2] == '\n') {
            found = true;
            diff = 3;
        }

        // \r\n | \r\n
        if (headers.size() >= 2 && headers[headers.size() - 2] == '\r' &&
            headers[headers.size() - 1] == '\n' && sz >= 2 && buf[0] == '\r' &&
            buf[1] == '\n') {
            found = true;
            diff = 2;
        }

        // \r\n\r | \n
        if (headers.size() >= 3 && headers[headers.size() - 3] == '\r' &&
            headers[headers.size() - 2] == '\n' &&
            headers[headers.size() - 1] == '\r' && sz >= 1 && buf[0] == '\n') {
            found = true;
            diff = 1;
        }
    }

    // consume
    ::recv(fd, buf, diff, 0);
    headers.insert(headers.end(), buf, buf + diff);
    if (found) {
        Http::RequestHeaderGrammar<decltype(headers)::iterator> grammar;
        bool res = phrase_parse(headers.begin(), headers.end(), grammar,
                                boost::spirit::qi::ascii::blank, request_);
        if (!res) {
            LOG_ACPROXY_ERROR("parse http request header error");
            //conn_->close();
            return;
        }

        request_.rewrite();
        request_.setKeepAlive(false);

        // cache layer
        if (request_.method == "GET" || request_.method == "HEAD") {
            std::string key = keygen(request_.getHost(), request_.getPort(),
                                     request_.uri, request_.method);
            auto& cache = getGlobalCache();
            if (boost::optional<std::string> resp = cache.get(key)) {
                LOG_ACPROXY_INFO("hit, found in cache!");
                finish(resp.value());
                return;
            }
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setCacheKey(key);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        }

        // LOG_ACPROXY_DEBUG("request = \n", request_.toBuffer());

        if (!request_.hasResponseBody()) {
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setResponseBody(false);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        }

        std::string host = request_.getHost();
        int port = request_.getPort();
        if (auto c = conn_.lock()) {
            res = c->getRemoteForwarder()->connect(host, port);
        } else {
            LOG_ACPROXY_WARNING("connection object is freed");
            return;
        }
        if (!res) {
            if (auto c = conn_.lock()) {
                c->report("failure", {{"host", boost::asio::ip::host_name()}},
                          std::time(0));
            }
            // XXX Maybe shutdowning socket is better
            LOG_ACPROXY_INFO("connection timeout, close it");
            //send("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
            //conn_->close();
            return;
        }
        LOG_ACPROXY_DEBUG("connection complete");

        if (!request_.isConnectMethod()) {
            // forward header to server
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->send(request_.toBuffer());
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        } else {
            // no parse response header, get rawdata and forward instead
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setParseResponseHeader(false);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
            // send a fake 200 response in tunnel mode
            send("HTTP/1.1 200 Connection Established\r\n\r\n");
        }

        if (request_.hasContentBody()) {
            getBody();
        }
    } else {
        // request header is incomplete, read again
        LOG_ACPROXY_INFO("http request header incomplete, read again");
        getHeaders();
    }
    if (auto c = conn_.lock()) {
        c->update();
    } else {
        LOG_ACPROXY_WARNING("connection object is freed");
        return;
    }
}
Пример #21
0
Файл: tincd.c Проект: Rumko/tinc
int main(int argc, char **argv) {
	program_name = argv[0];

	if(!parse_options(argc, argv))
		return 1;
	
	make_names();

	if(show_version) {
		printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
			   VERSION, __DATE__, __TIME__, PROT_CURRENT);
		printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
				"See the AUTHORS file for a complete list.\n\n"
				"tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
				"and you are welcome to redistribute it under certain conditions;\n"
				"see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	if(kill_tincd)
		return !kill_other(kill_tincd);

	openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);

	g_argv = argv;

	init_configuration(&config_tree);

	/* Slllluuuuuuurrrrp! */

	RAND_load_file("/dev/urandom", 1024);

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	OpenSSL_add_all_algorithms();

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config())
		return 1;

#ifdef HAVE_LZO
	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}
#endif

#ifdef HAVE_MINGW
	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service())
		return main2(argc, argv);
	else
		return 1;
}
Пример #22
0
main()
{
	int i,j,k=-1,g;	// i= participant number , k= total points on EC , g= Base point of EC
	printf("\n Initialization process ( Both user & chairperson ) \n ---------------------------------------------\n");
	do {
		printf("\n Choose a prime number : ");	// Prime no. to define Finite Field Fp
		scanf("%d",&p);
		j=0;
		for(i=2;i<p;i++)			// Prime checking
			if((p % i)==0)
				j=1;
	} while(j);
	struct pair ecc[2*p*p],rp,bp;	// Points on EC , Random point & Base point
	while(4*a*a*a + 27*b*b == 0)	// Singularity constraint on EC : 4a^3 + 27b^2 != 0
	{
		printf("\n\n Choose elliptic curve parameters a and b : ");
		scanf("%d %d",&a,&b);
	}
	for(i=0;i<p;i++)	// Generating points on EC
		for(j=0;j<p;j++)
			if( ((i*i*i+a*i+b) % p) == (j*j % p) ) // y^2 mod p = (x^3 + aX + b) mod p
			{
				ecc[++k].x=i;
				ecc[k].y=j;
				ecc[++k].x=i;
				if(j != 0)			// root of j^2 = +j & -j
					ecc[k].y=p-j;
				else
					ecc[k].y=j;
				break;
			}
	printf("\n\n Set of Sample Points on EC : ");	
	for(i=0;i<=k;i++)
		printf("\t ( %d , %d )",ecc[i].x,ecc[i].y);	// Points on EC within Finite Field Fp
	bp=ecc[0];
	for(j=0;j<=k;j++)
		if((ecc[j].x+ecc[j].y)<(bp.x+bp.y))	// Choosing Base point with smallest co-ordinate on EC
			bp=ecc[j];	
	printf("\n Base point G : ( %d , %d )\n",bp.x,bp.y);
	printf("\n Enter no. of participants : ");	// Total no of participants under chairPerson
	scanf("%d",&i);
	int par_pvt[i],chpr_pvt;	// Private key of ChairPerson & each Participant
	struct pair par_pub[i],chpr_pub,par_shared[i],encr_shared[i],decr_shared[i]; // Public keys, Shared keys
	printf("\n\n Chairperson site \n ---------------- \n");
	do {
		printf("\n Choose private key of chairperson ( 0<key<p ) : ");
		scanf("%d",&chpr_pvt);			// 0 < ChairPerson Private key < p
	} while((chpr_pvt >= p) || (chpr_pvt <= 0) );
	chpr_pub=keygen(chpr_pvt,bp);			// Generating Public key from Private key of ChairPerson
	printf("\n Public key of chairperson : ( %d , %d ) \n",chpr_pub.x,chpr_pub.y);
	printf("\n Participant site \n ---------------- \n");	
	for(j=0;j<i;j++)
	{
		do {
			printf("\n Choose private key of participant[%d] ( 0<key<p ) : ",j);
			scanf("%d",&par_pvt[j]);		// 0 < Participant Private key < p
		} while((par_pvt[j] >= p) || (par_pvt[j] <= 0) );	
		par_pub[j]=keygen(par_pvt[j],bp);	// Generating Pulic key from Private key of Participant
		printf("\n Public key of participant[%d] : ( %d , %d )",j,par_pub[j].x,par_pub[j].y);
		par_shared[j]=keygen(par_pvt[j],chpr_pub);	// Generating Shared key by each participant
		printf("\n Shared key of participant[%d] : ( %d , %d )",j,par_shared[j].x,par_shared[j].y);
		encr_shared[j]=trans_add(par_shared[j],keygen(par_pvt[j],chpr_pub));  // Encrypting Shared key by participant
		printf("\n Encrypted Shared key of participant[%d] : ( %d , %d ) \n",j,encr_shared[j].x,encr_shared[j].y);
	}	
	printf("\n Chairperson site \n ---------------- \n");
	struct pair combine_key,group_key,encr_group_key[i],decr_group_key[i];	// Combine & Group key
	while(1)
	{
		printf("\n Choose a random pair (any point on EC) : ");
		scanf("%d %d",&rp.x,&rp.y);
		for(j=0;j<=k;j++)
			if((rp.x==ecc[j].x)&&(rp.y==ecc[j].y))	// Random Point choosen by chairperson need to be on EC
				j=k+1;
		if(j==k+2)
			break;
	}
	printf("\n");
	combine_key=rp;		// combine key initialized with random point rp
	for(j=0;j<i;j++)
	{
		decr_shared[j]=trans_sub(encr_shared[j],keygen(chpr_pvt,par_pub[j]));//Decrypting Shared key from participant
		printf("\n Decrypted Shared key of participant[%d] : ( %d , %d )",j,decr_shared[j].x,decr_shared[j].y);
		combine_key=trans_add(combine_key,decr_shared[j]);		// Calculating Combine key
	}							
	printf("\n\n Combine key : ( %d , %d )\n",combine_key.x,combine_key.y);
	group_key=keygen(chpr_pvt,combine_key);				// Generating Group key from Combine key
	printf("\n Group key : ( %d , %d )\n",group_key.x,group_key.y);
	printf("\n Participant site \n ------------------- \n");
	for(j=0;j<i;j++)
	{
		encr_group_key[j]=trans_add(group_key,keygen(chpr_pvt,par_pub[j]));//Encrypted Groupkey to the participant
		printf("\n Encrypted Group Key to participant[%d] : ( %d , %d )",j,encr_group_key[j].x,encr_group_key[j].y);
		decr_group_key[j]=trans_sub(encr_group_key[j],keygen(par_pvt[j],chpr_pub));// Decryption to get Group key
		printf("\n Decrypted Group Key for participant[%d]:( %d , %d )\n",j,decr_group_key[j].x,decr_group_key[j].y);
	}
}						// Group Key ready to use
Пример #23
0
int
main(int argc, char *argv[])
{
    KryState state = STATE_BADARG;
    long mod_bits;

    if (argc == 3 && !strcmp(argv[1], "-g")) {
        // Key generation
        state = STATE_KEYGEN;
        mod_bits = strtol(argv[2], NULL, 10);
        if (mod_bits < 16) {
            state = STATE_BADARG;
            fprintf(stderr, "Too small key length\n");
        }
    } else if (argc == 5 && !strcmp(argv[1], "-e")) {
        // Encryption
        state = STATE_ENCRYPTION;
    } else if (argc == 5 && !strcmp(argv[1], "-d")) {
        // Decryption
        state = STATE_DECRYPTION;
    } else if (argc == 5 && !strcmp(argv[1], "-b")) {
        // RSA cracking
        state = STATE_CRACKING;
    }

    if (state == STATE_BADARG) {
        // Someting is messed up
        print_help(argv[0]);
        return EXIT_FAILURE;
    }

    // Prepare pseudo number generator stuff
    gmp_randstate_t randstate;
    gmp_randinit_default(randstate);
    //gmp_randseed_ui(randstate, 1);
    gmp_randseed_ui(randstate, time(NULL));

    int rc = EXIT_SUCCESS;
    mpz_t res;
    mpz_init(res);

    switch (state) {
        case STATE_KEYGEN: {
            mpz_t p, q, n, e;  // For d use res var
            mpz_init(p);
            mpz_init(q);
            mpz_init(n);
            mpz_init(e);
            rc = keygen(p, q, n, e, res, mod_bits, randstate);
            gmp_printf("0x%Zx 0x%Zx 0x%Zx 0x%Zx 0x%Zx\n", p, q, n, e, res);
            mpz_clear(p);
            mpz_clear(q);
            mpz_clear(n);
            mpz_clear(e);
            break;
        }

        case STATE_ENCRYPTION:
            // Argv: [2]=e; [3]=n; [4]=m;
            rc = encrypt(res, argv[2], argv[3], argv[4]);
            gmp_printf("0x%Zx\n", res);
            break;

        case STATE_DECRYPTION:
            // Argv: [2]=d; [3]=n; [4]=c;
            rc = decrypt(res, argv[2], argv[3], argv[4]);
            gmp_printf("0x%Zx\n", res);
            break;

        case STATE_CRACKING: {
            // Argv: [2]=e; [3]=n; [4]=c;
            mpz_t p, q, p_, q_, e, d;
            mpz_init(p);
            mpz_init(q);
            mpz_init(p_);
            mpz_init(q_);
            mpz_init(e);
            mpz_init(d);

            rc = factorization(p, q, argv[3]);
            if (rc != 0)
                goto cracking_cleanup;

            // phi = (p-1) * (q-1)
            mpz_sub_ui(p_, p, 1L);
            mpz_sub_ui(q_, q, 1L);
            mpz_mul(res, p_, q_);

            // d = e^1 mod phi
            mpz_set_str(e, argv[2], 0);
            modinv(d, e, res);

            rc = decrypt_mpz_d(res, d, argv[3], argv[4]);
            gmp_printf("0x%Zx 0x%Zx 0x%Zx\n", p, q, res);
        cracking_cleanup:
            mpz_clear(p);
            mpz_clear(q);
            mpz_clear(p_);
            mpz_clear(q_);
            mpz_clear(e);
            mpz_clear(d);
            break;
        }

        case STATE_BADARG:
            break;
    }

    mpz_clear(res);
    gmp_randclear(randstate);
    return rc;
}
Пример #24
0
void
sfsserver_auth::keyexpire ()
{
  keytmo = NULL;
  keygen ();
}
Пример #25
0
int main(int argc,char *argv[]){
  int i,j,k,count=0;
  unsigned char inv_x[N],o;
  unsigned char a[N],b[N],inv_b[N],c[N];
  time_t t;
  FILE *fp,*fo;
  set fai;
  arrayn p,aa;
  array8 q;

  
  unsigned char cipher[4];
  unsigned char temp[N];
  unsigned char inv_c[16][N];
  
  unsigned char test[32]={1,1,1,1,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,1,0,1,0};
  unsigned char ee[4];
  unsigned int t2=0,l=0;
  char m[1];

  unsigned char u[N/2],tmp[N],tmb[N];
  unsigned char inv_t[16][N];
  unsigned char nx[N];

  arrayul pp;
  array16 tt;

  seed();
  pp=crand(password);
  for(i=0;i<8;i++)
    printf("%llu\n",pp.u[i]);

  hout();

  //  mainga(argc,argv);
  exit(1);

  
  tt=hash(argc,argv);
  for(i=0;i<16/2;i++)
    printf("%08x ",tt.h[i]);
  printf("\n");

  

  srand(time(&t));

  //    chksalt();
       gendata();
  exit(1);
  
  for(i=0;i<N/2;i++){
    u[i]=rand()%256;
    printf("%u\n",u[i]);
  }


  printf("input mode\n");
  scanf("%s",&m);

  if(strcmp(m,"k")==0)
    keygen();
  if(strcmp(m,"d")==0){
    fp=fopen("braidsec.key","rb");
    fread(nx,1,N,fp);
    fclose(fp);
  }
  if(strcmp(m,"e")==0){
    fp=fopen("braidpub.key","rb");
    fread(pr,1,N,fp);
    fread(ps,1,N,fp);
    /*
   for(i=0;i<N;i++)
     printf("%d,",s[i]);
   printf("\n");
   */
    fclose(fp);
  }


  char file[100],out[100];
  int f;
  unsigned char buf[64];
  unsigned char h[N],rr[N];
  
  for(i=0;i<N;i++)
    h[i]= r[i];
  
  printf("\ninput file name\n");
  scanf("%s",&file);
  fp=fopen(file,"rb");
  printf("input outfile name\n");
  scanf("%s",&out);
  fo=fopen(out,"wb");
 

  j=0;

  if(strcmp("d",m)==0){
    for(i=0;i<N;i++)
      inv_b[nx[i]]=i;
    for(i=0;i<N;i++)
      pr[i]=nx[r[inv_b[i]]];
    for(i=0;i<N;i++)
      ps[i]=nx[s[inv_b[i]]];
  }

  for(i=0;i<N;i++)
    rr[i]=rand()%256;


  if(strcmp(m,"e")==0){
    fai=session(rr);
    
    for(i=0;i<N;i++)
      printf("%d,",fai.b[i]);
    printf("\n");
    
    fwrite(fai.a,1,64,fo);
  }


  if(strcmp(m,"d")==0){
    fread(fai.a,1,64,fp);
    for(k=0;k<N;k++){
      c[k]=nx[fai.a[inv_b[k]]];
      printf("%d,",c[k]);
    }
    printf("aaa\n");
  }

while((f=fread(buf,1,64,fp))>0){

  if(strcmp("e",m)==0){
    p=chash(fai.b);
    /*
    for(i=0;i<N;i++)
      printf("%d,",p.ar[i]);
    printf("\n");
    */
    for(k=0;k<N;k++)
      rr[k]=p.ar[k];
    fai=session(rr);
    for(k=0;k<N;k++)
      buf[k]^=p.ar[k];
  }
  if(strcmp("d",m)==0){
  /*
    for(i=0;i<N;i++)
      printf("%d,",c[i]);
    printf("vv\n");
    //        exit(1);
    */
    p=chash(c);
    
    for(k=0;k<N;k++){
      buf[k]^=p.ar[k];
      rr[k]=p.ar[k];
    }
    fai=session(rr);
    /*
    for(i=0;i<N;i++)
      printf("%d,",p.ar[i]);
    printf("bb\n");
    */
    //    exit(1);
    for(k=0;k<N;k++)
      c[k]=fai.b[k];
    
  }
  fwrite(buf,1,f,fo);

 }

 fclose(fp);
 fclose(fo);


return 0;
}
Пример #26
0
int main(int argc, char* argv[])
{
    totalStartTime = getCPUTime();
    printf("%lf\n",totalStartTime);
	int i;
	FILE* fp = fopen(argv[1],"a+b");
	if (fp==NULL) {
		printf("fopen error: cannot open file\n");
		exit(1);
	}
	int* prptable;
	unsigned char mac[MAXBLOCKSIZE];
    unsigned long fileLen1,fileLen2;
    // get the file size
	fseek(fp,0,SEEK_END);
	fileLen1 = ftell(fp);
    // generate keys
	master_keygen(argv[2]);

	printf("key for file permutation: ");
	displayCharArray(k_file_perm,16);

	printf("key for ecc permutation: ");
	displayCharArray(k_ecc_perm,16);

	printf("key for ecc encryption: ");
	displayCharArray(k_ecc_enc,16);

	printf("key for challenge generation: ");
	displayCharArray(k_chal,16);

	printf("key for random index generation: ");
	displayCharArray(k_ind,16);

	printf("key for response encryption: ");
	displayCharArray(k_enc,16);

	printf("key for MAC computation: ");
	displayCharArray(k_mac,16);	
	
    // blockize the file
	int blocks = blockize(fp);
	t = blocks;
	fclose(fp);
    fp = fopen(argv[1],"a+b");
    
    // computing MAC
	printf("\nComputing file's MAC...\n");
		printf("\nmac size %lu\n",sizeof(mac));
    macStartTime = getCPUTime();
	hmac(argv[1],mac,k_mac);
    macTime = getCPUTime() - macStartTime;
	printf("\nMAC = ");
	displayCharArray(mac,16);	
	
    // perform a file level PRP
	printf("\nSRF PRP for the entire file...\n");
    prpStartTime = getCPUTime();
	prptable = prp(blocks, k_file_perm);
    prpTime += getCPUTime() - prpStartTime;
    eccStartTime = getCPUTime();
	initialize_ecc();
	inc_encoding(fp,prptable);
    eccTime = getCPUTime() - eccStartTime - readTime;
	
	printf("\nFile blocks after outer layer encoding: %lu\n",t);

    // precompute q challenge and responsess
	printf("\nPrecomputation for %d challenges and responses\n",q);
    chalStartTime = getCPUTime();
	Chal c[q];
	int j,p;
    // use k_chal to generate kjc
	keygen_init();
	seeding(k_chal);
	unsigned char * kjc[q];
	for(j=0;j<q;j++) {
		kjc[j] = malloc(16*sizeof(unsigned char *));
		keygen(kjc[j], 16);
	}
    // use kjc to generate random indices
	for(j=0;j<q;j++) {
		keygen_init();
		seeding(kjc[j]);
		for(p=0;p<v;p++) {
			unsigned long randomIndex;
			char rand[8];
			keygen(rand, 8);
			randomIndex = *(unsigned long *)rand;	
			c[j].s[p] = randomIndex % t;
		}
	}
    // use k_ind to generate random index u
	keygen_init();
	seeding(k_ind);	
	for(j=0;j<q;j++) {
		unsigned int randomIndex;
		char rand[4];
		keygen(rand, 4);
		randomIndex = *(unsigned int *)rand;	
		c[j].u = randomIndex % w;
	}
	printf("Precomputation for challenges finishes\n");
    // precompute challenge responses
	precompute_response(fp,c,k_enc);
	printf("Precomputation for responses finishes\n");
    chalTime+=getCPUTime()-chalStartTime - write2Time;
    // append MAC at the end of the files
	printf("\nAppend MAC to the end of the file...\n");
    write2StartTime = getCPUTime();
    clock_gettime(CLOCK_MONOTONIC, &start);
	fwrite(mac,16,1,fp);
    clock_gettime(CLOCK_MONOTONIC, &finish);
    double addTime = finish.tv_sec - start.tv_sec;
    addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
    write2Time += getCPUTime() - write2StartTime+addTime;
    fseek(fp,0,SEEK_END);
	fileLen2 = ftell(fp);
	fclose(fp);

	printf("\nPOR encoding done\n");

	// display time performance
    totalTime = getCPUTime() - totalStartTime;
    printf("#RESULT#\n");
    printf("%lu\n",fileLen1);
    printf("%lu\n",fileLen2);
    printf("%lf\n",totalTime);
    printf("%lf\n",readTime);
    printf("%lf\n",prpTime);
    printf("%lf\n",eccTime);
    printf("%lf\n",macTime);
    printf("%lf\n",chalTime);
    printf("%lf\n",write1Time+write2Time);
    printf("%lf\n",encTime);


}
Пример #27
0
int main(int argc, char** argv)
{
    if (argc < 3) {
        usage();
        exit(-1);
    }

    if (strcmp(argv[1], "keygen") && strcmp(argv[1], "crypt") &&
        strcmp(argv[1], "invkey") && strcmp(argv[1], "histo") &&
        strcmp(argv[1], "solve")) {
        usage();
        exit(-1);
    }

    if (!strcmp(argv[1], "keygen")) {
        optind = 2;
        int c = 0;
        int option_index = 0;

        int nPeriod = 0;

        while (1) {
            struct option long_options[] = {
                {"t", required_argument, 0, 't'},
                {0, 0, 0, 0}
            };

            c = getopt_long_only(argc, argv, "t:",
                    long_options, &option_index);

            if (c == -1) {
                if (optind != 3) {
                    usage();
                    exit(-1);
                }
                break;
            }

            switch (c) {
                case 't': {
                    for (int i = 0; i < strlen(optarg); ++i) {
                        if (!isdigit(optarg[i])) {
                            fprintf(stderr, "Error: argument `%s' is invalid\n", optarg);
                            exit(-1);
                        }
                    }
                    nPeriod = atoi(optarg);
                    break;
                }

                case '?':
                    break;

                default:
                    usage();
                    exit(-1);
            }
        }

        if (nPeriod > 0) {
            keygen(nPeriod);
        }
        else {
            usage();
            exit(-1);
        }
    }

    else if (!strcmp(argv[1], "crypt")) {
        optind = 2;
        int c = 0;
        int option_index = 0;

        char keyfile[CHAR_BUF_LEN];
        FILE* fp = NULL;

        memset(keyfile, '\0', CHAR_BUF_LEN * sizeof(char));

        while (1) {
            struct option long_options[] = {
                {"k", required_argument, 0, 'k'},
                {0, 0, 0, 0}
            };

            c = getopt_long_only(argc, argv, "k:",
                    long_options, &option_index);

            if (c == -1) {
                if (optind < 3) {
                    usage();
                    exit(-1);
                }
                break;
            }

            switch (c) {
                case 'k':
                    strcpy(keyfile, optarg);
                    break;

                case '?':
                    break;

                default:
                    usage();
                    exit(-1);
            }
        }

        if (strlen(keyfile) < 1) {
            usage();
            exit(-1);
        }

        if (optind < argc) {
            if (!(fp = fopen(argv[optind], "r"))) {
                char errorMsg[CHAR_BUF_LEN];
                sprintf(errorMsg, "Error opening %s", argv[optind]);
                perror(errorMsg);
                exit(-1);
            }
        }
        else {
            fp = stdin;
        }

        crypt_(keyfile, fp);
    }

    else if (!strcmp(argv[1], "invkey")) {
        if (argc != 3) {
            usage();
            exit(-1);
        }

        invkey(argv[2]);
    }

    else if (!strcmp(argv[1], "histo")) {
        optind = 2;
        int c = 0;
        int option_index = 0;

        int nPeriod = 0;
        int nWhich = 0;
        FILE* fp = NULL;

        while (1) {
            struct option long_options[] = {
                {"t", required_argument, 0, 't'},
                {"i", required_argument, 0, 'i'},
                {0, 0, 0, 0}
            };

            c = getopt_long_only(argc, argv, "t:i:",
                    long_options, &option_index);

            if (c == -1) {
                if (optind < 4) {
                    usage();
                    exit(-1);
                }
                break;
            }

            switch (c) {
                case 't':
                    for (int i = 0; i < strlen(optarg); ++i) {
                        if (!isdigit(optarg[i])) {
                            fprintf(stderr, "Error: argument `%s' is invalid\n", optarg);
                            exit(-1);
                        }
                    }
                    nPeriod = atoi(optarg);
                    break;

                case 'i':
                    for (int i = 0; i < strlen(optarg); ++i) {
                        if (!isdigit(optarg[i])) {
                            fprintf(stderr, "Error: argument `%s' is invalid\n", optarg);
                            exit(-1);
                        }
                    }
                    nWhich = atoi(optarg);
                    break;

                case '?':
                    break;

                default:
                    usage();
                    exit(-1);
            }
        }

        if (nPeriod < 1 || nWhich < 1) {
            usage();
            exit(-1);
        }

        if (optind < argc) {
            if (!(fp = fopen(argv[optind], "r"))) {
                char errorMsg[CHAR_BUF_LEN];
                sprintf(errorMsg, "Error opening %s", argv[optind]);
                perror(errorMsg);
                exit(-1);
            }
        }
        else {
            fp = stdin;
        }

        histo(nPeriod, nWhich, fp);
    }

    else if (!strcmp(argv[1], "solve")) {
        optind = 2;
        int c = 0;
        int option_index = 0;

        int nMax_t = 0;
        FILE* fp = NULL;

        if (argc != 4) {
            usage();
            exit(-1);
        }

        while (1) {
            struct option long_options[] = {
                {"l", required_argument, 0, 'l'},
                {0, 0, 0, 0}
            };

            c = getopt_long_only(argc, argv, "l:",
                    long_options, &option_index);

            if (c == -1) {
                break;
            }

            switch (c) {
                case 'l':
                    for (int i = 0; i < strlen(optarg); ++i) {
                        if (!isdigit(optarg[i])) {
                            fprintf(stderr, "Error: argument `%s' is invalid\n", optarg);
                            exit(-1);
                        }
                    }
                    nMax_t = atoi(optarg);
                    break;

                case '?':
                    break;

                default:
                    usage();
                    exit(-1);
            }
        }

        if (nMax_t < 1) {
            usage();
            exit(-1);
        }

        if (!(fp = fopen(argv[optind], "r"))) {
            char errorMsg[CHAR_BUF_LEN];
            sprintf(errorMsg, "Error opening %s", argv[optind]);
            perror(errorMsg);
            exit(-1);
        }

        solve(nMax_t, fp);
    }

    return 0;
}
Пример #28
0
int main(int argc, char **argv) {
	logmode_t logmode;

	program_name = argv[0];

	if(!parse_options(argc, argv)) {
		return 1;
	}

	if(show_version) {
		printf("%s version %s\n", PACKAGE, VERSION);
		printf("Copyright (C) 1998-2018 Ivo Timmermans, Guus Sliepen and others.\n"
			   "See the AUTHORS file for a complete list.\n\n"
			   "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
			   "and you are welcome to redistribute it under certain conditions;\n"
			   "see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	make_names();

	if(kill_tincd) {
		return !kill_other(kill_tincd);
	}

	if(use_logfile) {
		logmode = LOGMODE_FILE;
	} else if(use_syslog) {
		logmode = LOGMODE_SYSLOG;
	} else {
		logmode = LOGMODE_STDERR;
	}
	openlogger("tinc", logmode);

	g_argv = argv;

	if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
		do_detach = false;
	}

#ifdef HAVE_UNSETENV
	unsetenv("LISTEN_PID");
#endif

	init_configuration(&config_tree);

#ifndef OPENSSL_NO_ENGINE
	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();
#endif

#if OPENSSL_VERSION_NUMBER < 0x10100000L
	OpenSSL_add_all_algorithms();
#endif

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config()) {
		return 1;
	}

#ifdef HAVE_LZO

	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}

#endif

#ifdef HAVE_MINGW

	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service()) {
		return main2(argc, argv);
	} else {
		return 1;
	}
}
Пример #29
0
int main(int argc, char *argv[])
{
    /* Index */
    int i;
    /* Flags to msgsnd */
    int msgsnd_flag = 0;
    /* Flags to msgrcv */
    int msgrcv_flg = 0;
    /* Number of processes to fork() */
    int num_procs = 1;
    /* String read from input */
    char *input = NULL;
    /* Placeholder for message type identifier */
    long msgtyp_id;
    /* Indices of  */
    int msgtyp_idxs[26];
    int *msgtyp_idxs_p = msgtyp_idxs;

    /* Struct for use with GNU getopt_long() */
    struct option longopts[] = {
        { "number", required_argument,  0,  'n' },
        { 0, 0, 0, 0 }
    };

    /* Variable to hold flag currently
     * being ready by getopt() */
    int c;

    /* Index of option currently
     * being considered */
    int opt_index = 0;

    if(argc != 1 && argc != 3)
        usage(stderr, argv[0], "incorrect number of options", EXIT_FAILURE);


    /*
     * Loop adapted from example given at
     * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
     */
    while((c = getopt_long(argc, argv, "n:",
                    longopts, &opt_index)) != -1) {
        switch(c) {
            case 'n':
                num_procs = atoi(optarg);
                break;
            case('?'):
            default:
                usage(stderr, argv[0], "unrecognized option", EXIT_FAILURE);
                break;
        }
    }

    if(num_procs > MAX_PROCS)
        usage(stderr, argv[0], "invalid number of processes", EXIT_FAILURE);

    /* One queue each for parent and children */
    num_queues = num_procs + 1;

    /* Calculate which queue/process a word
     * should be assigned to based on its
     * first letter */
    msgtyp_idx_gen(&msgtyp_idxs_p, num_procs);

    /* Allocate space to store pids of
     * parent and children */
    pids = xmalloc(sizeof(pid_t) * num_queues);
    /* Store parent pid */
    pids[0] = parent_pid = getpid();

    /* Create one key each for parent
     * and child processes */
    keygen(&keys, num_queues);

    /* Create one queue each for parent
     * and child processes */
    queue_init(&queues, keys, num_queues);

    /* Parent queue is first in array */
    parent_queue = queues[0];

    /* Set up handler for SIGCHLD,
     * SIGINT, and SIGTERM */
    signal(SIGCHLD, &sig_handler);
    signal(SIGINT, &sig_handler);
    signal(SIGTERM, &sig_handler);

    /* Start subprocesses */
    subproc_exec(queues, keys, num_procs);

    /* Assign string 'input' a message type that is
     * the pid of one of the subprocesses (that's why there's
     * a '+ 1' in the array index -- the parent pid is pid[0]). */
    while((input = get_word(stdin, BUFLEN)) != NULL) {
        msgtyp_id = (long)pids[msgtyp_idxs[input[0] - 97] + 1];
        /* Create msg_t from 'input' string and
         * place it in parent queue */
        if(msgsnd_str(parent_queue, strlen(input) + 1, msgsnd_flag, msgtyp_id, input, 1) == -1) {
            perror("main: msgsnd");
            clean_up_procs(queues, pids, num_queues);
            exit(EXIT_FAILURE);
        }
        free(input);
    }

    /* Send terminating message to each child */
    for(i = 1; i < num_queues; i++) {
        msgtyp_id = (long)pids[i];
        if(msgsnd_str(parent_queue, 1, msgsnd_flag, msgtyp_id, "", -1) == -1) {
            perror("msgsnd");
            clean_up_procs(queues, pids, num_queues);
            exit(EXIT_FAILURE);
        }
    }

    /* Print messages received from children
     * in alphabetical order */
    for(i = 1; i <= num_procs; i++) {
        if(print_msgs(queues[i], MSG_SZ, pids[i], msgrcv_flg) == -1) {
            perror("main: msgrcv");
            clean_up_procs(queues, pids, num_queues);
            exit(EXIT_FAILURE);
        }
    }

    /* Wait for children to terminate */
    for (i = 0; i < num_procs; i++)
        wait(NULL);

    /* Free memory and destroy queues */
    clean_up_procs(queues, pids, num_queues);
    return 0;
}
Пример #30
0
static char *
str_utf8_create_key_gen (const char *text, int case_sen,
                         gchar * (*keygen) (const gchar * text, gssize size))
{
    char *result;

    if (case_sen)
    {
        result = str_utf8_normalize (text);
    }
    else
    {
        gboolean dot;
        GString *fixed;
        const char *start, *end;
        char *fold, *key;

        dot = text[0] == '.';
        fixed = g_string_sized_new (16);

        if (!dot)
            start = text;
        else
        {
            start = text + 1;
            g_string_append_c (fixed, '.');
        }

        while (!g_utf8_validate (start, -1, &end) && start[0] != '\0')
        {
            if (start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            g_string_append_c (fixed, end[0]);
            start = end + 1;
        }

        if (start == text)
        {
            fold = g_utf8_casefold (start, -1);
            result = keygen (fold, -1);
            g_free (fold);
            g_string_free (fixed, TRUE);
        }
        else if (dot && (start == text + 1))
        {
            fold = g_utf8_casefold (start, -1);
            key = keygen (fold, -1);
            g_string_append (fixed, key);
            g_free (key);
            g_free (fold);
            result = g_string_free (fixed, FALSE);
        }
        else
        {
            if (start[0] != '\0' && start != end)
            {
                fold = g_utf8_casefold (start, end - start);
                key = keygen (fold, -1);
                g_string_append (fixed, key);
                g_free (key);
                g_free (fold);
            }
            result = g_string_free (fixed, FALSE);
        }
    }
    return result;
}