示例#1
0
void RSAZCryptor::init()
{
    m_trace_level = 0;
    m_encoding = true;

    bio_err = NULL;
    priv_mem = NULL;
    pub_mem = NULL;
    privkey = NULL;
    pubkey = NULL;
    priv_rsa = NULL;
    pub_rsa = NULL;
    priv_size = 0;
    pub_size = 0;

    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
    bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);

#if defined(_WIN32) || defined(__linux__)
    OpenSSL_add_all_ciphers();
#else
    SSL_library_init();
#endif

    ERR_load_crypto_strings ();

    seed_prng();

    m_keycache = new ZKeyCache();

    m_filesToBeZIP = NULL;

}
示例#2
0
//=========================================
// Constructor
//-----------------------------------------
SSLClient::SSLClient ( QObject* parent ) : SSLCommon ( parent ) {
	BIO *sbio = NULL;
	printf ("Initialize openssl\n");
	init_OpenSSL ();
	seed_prng ();
	printf ("Setup client context\n");
	setupClientCTX ();
	printf ("Connecting TCP socket\n");
	connectTCP ();

	printf ("Creating new SSL object\n");
	ssl = SSL_new (ctx);
	printf ("Creating new SSL BIO socket: %d\n",mSocket);
	sbio= BIO_new_socket (mSocket,BIO_NOCLOSE);
	printf ("Setup SSL BIO socket\n");
	SSL_set_bio (ssl,sbio,sbio);
	printf ("Connecting SSL socket\n");
	if (SSL_connect(ssl) <=0) {
		qerror ("Error creating connection BIO");
	}
	int ofcmode = fcntl (mSocket,F_GETFL,0);
	if (fcntl (mSocket,F_SETFL,ofcmode | O_NDELAY)) {
		qerror ("Couldn't make socket nonblocking");
	}
	FD_ZERO (&readFDs);
	printf ("SSL Connection created\n");
}
示例#3
0
文件: tls.c 项目: yomei-o/msmtp
int tls_lib_init(char **errstr)
{
#ifdef HAVE_LIBGNUTLS
    int error_code;

    if ((error_code = gnutls_global_init()) != 0)
    {
        *errstr = xasprintf("%s", gnutls_strerror(error_code));
        return TLS_ELIBFAILED;
    }

    return TLS_EOK;
#endif /* HAVE_LIBGNUTLS */

#ifdef HAVE_LIBSSL
    int e;

    SSL_load_error_strings();
    SSL_library_init();
    if ((e = seed_prng(errstr)) != TLS_EOK)
    {
        return e;
    }

    return TLS_EOK;
#endif /* HAVE_LIBSSL */
}
示例#4
0
文件: key_utils.c 项目: Emat12/PyCCN
int
generate_key(int length, PyObject **py_private_key_ccn,
		PyObject **py_public_key_ccn, PyObject **py_public_key_digest,
		int *public_key_digest_len)
{
	RSA *private_key_rsa;
	int r;

	seed_prng();
	private_key_rsa = RSA_generate_key(length, 65537, NULL, NULL);
	save_seed();

	if (!private_key_rsa) {
		unsigned int err;

		err = ERR_get_error();
		PyErr_Format(g_PyExc_CCNKeyError, "Unable to generate digest from the"
				" key: %s", ERR_reason_error_string(err));
		return -1;
	}

	r = ccn_keypair_from_rsa(0, private_key_rsa, py_private_key_ccn,
			py_public_key_ccn);
	if (r < 0)
		return -1;

	r = create_public_key_digest(private_key_rsa, py_public_key_digest,
			public_key_digest_len);
	if (r < 0)
		return -1;

	return 0;
}
示例#5
0
int main(int argc, char **argv)
{
    BIO *acc, *client;
    SSL *ssl;
    SSL_CTX *ctx;
    pthread_t tid;

    init_openssl();
    seed_prng(64);

    ctx = setup_server_ctx();
    acc = BIO_new_accept(PORT);
    if(!acc)
        log_err("Error creating server socket.");

    /* first call BIO_do_accept() setup accept BIO */
    if(BIO_do_accept(acc) <= 0)
        log_err("Error binding server socket.");

    for(;;) {
        if(BIO_do_accept(acc) <= 0)
            log_err("Error accepting connection.");
        client = BIO_pop(acc);
        if(!(ssl = SSL_new(ctx)))
            log_err("Error creating SSL context.");
        SSL_set_bio(ssl, client, client);
        pthread_create(&tid, NULL, server_thread, ssl);
    }

    SSL_CTX_free(ctx);
    BIO_free(acc);
    return 0;
}
/*
 * Class:     EmU_Login
 * Method:    init_backend
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_EmU_1Login_init_1backend(JNIEnv *env, jobject obj)
{
	set_using_safety_threads_for_openssl(true);
	seed_prng();
	init_openssl();

	assert_cache_directory_existence();
}
示例#7
0
int main(void) {
    int quit = 0;
    
    // Initialize mail server
    seed_prng(*(uint32_t *)FLAG_PAGE);
    int num_mailq = 0;
    abook = calloc(sizeof(address_book));
    initialize_address_book();
    initialize_mail_queues();

    // run a mail server
    char line[MAX_LINE+1];
    int line_size = 0;
    printf("sendmail:");
    do {
        // Read a line
        if ((line_size = receive_until(line, MAX_LINE, '\n')) <= 0) {
            break;
        }
        line[line_size] = '\0';
        // Process the command
        char *next = line;
        // Terminate first command word
        while ((*next != ' ') && (*next != '\0')) next++;
        *next++ = '\0';
        if (strcmp(line, "LIST")==0) {
            // List one mail queue
            list_queue(next);
        } else if (strcmp(line, "LISTALL")==0) {
            // List all mail queues
            list_all_queues();
        } else if (strcmp(line, "POST")==0) {
            // Post a message
            sendmail_post(next);
        } else if (strcmp(line, "READ")==0) {
            // Read a message
            read_message(next);
        } else if (strcmp(line, "ADDRESSBOOK")==0) {
            // Print address book
            print_address_book();
        } else if (strcmp(line, "QUIT")==0) {
            // Quit mail server
            break;
        } else {
            // Invalid command
            printf("Invalid Command!\n");
            quit = 1;
        }

    } while (quit == 0);

    printf("Goodbye.\n");
}
示例#8
0
static void init_server()
{
	set_using_safety_threads_for_openssl(true);
	seed_prng();
    	init_openssl();

	assert_cache_directory_existence();
	get_necessary_info();
	load_pub_key();

	// Initial the e-mail sending lock mutex
	if(sem_init(&email_sending_lock_mutex, 0, 1) != 0)
		int_error("Initial a mutex failed");
}
示例#9
0
int main(int argc, char *argv[])
{
     init_OpenSSL(  );
     seed_prng(  );

     if(argc < 4) 
     {
	  fprintf(stderr, "usage: ./client start-session host port\n");
	  exit(1);
     }
     if(0 == strcmp(argv[1], "start-session"))
	  start_session(argv[2], argv[3]);

     return 0;
}
示例#10
0
SSL *
connect_client (int port, const char *addr, int addr_family)
{
  int sd;
  int err;
  int result = -1;
  /* SSL preliminaries */
  SSL_CTX* ctx;
  SSL*     ssl;
  init_OpenSSL ();			  
  seed_prng ();
  
  sd = crv_client_create(port, addr, addr_family);
  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
	fprintf ( stderr, "%s\n", "Create new ssl failed");
  }
		
  /* connect the SSL object with a file descriptor */
  err = SSL_set_fd (ssl, sd);
  if ((err)==0) {
	fprintf ( stderr, "%s\n", "Put SSL on socket failed \n");
	close(sd);
  }

  result = SSL_connect (ssl);
  if (result == 0)	{
	SSL_get_error(ssl, result);
	return (NULL);
  } else
  if (result == -1) {
	fprintf( stderr, "%s\n", "client_(): Err[003] SSL_connect() failed");
	return (NULL);
  }
  return (ssl);
}
示例#11
0
int main_ssl(int argc, char **argv)
{
	BIO *conn;
	SSL *ssl;
	SSL_CTX *ctx;
	long err;

	init_OpenSSL();
	seed_prng();

	ctx = setup_client_ctx();

	fprintf(stderr, "SERVER= %s:%s\n", SERVER, PORT);
	conn = BIO_new_connect(SERVER ":" PORT);
	if (!conn)
		int_error("Error creating connection BIO");

	if (BIO_do_connect(conn) <= 0)
		int_error("Error connecting to remote machine");

	ssl = SSL_new(ctx);
	SSL_set_bio(ssl, conn, conn);
	if (SSL_connect(ssl) <= 0)
		int_error("Error connecting SSL object");
	if ((err = post_connection_check(ssl, SERVER)) != X509_V_OK) {
		fprintf(stderr, "-Error: peer certificate: %s\n",
			X509_verify_cert_error_string(err));
		int_error("Error checking SSL object after connection");
	}
	fprintf(stderr, "SSL Connection opened\n");
	if (do_client_loop(ssl))
		SSL_shutdown(ssl);
	else
		SSL_clear(ssl);
	fprintf(stderr, "SSL Connection closed\n");

	SSL_free(ssl);
	SSL_CTX_free(ctx);
	return 0;
}
示例#12
0
文件: key_utils.c 项目: cawka/PyNDN
int
generate_key(int length, PyObject **py_private_key_ndn,
             PyObject **py_public_key_ndn, PyObject **py_public_key_digest,
             int *public_key_digest_len)
{
	RSA *private_key_rsa;
        struct ndn_pkey *private_key = NULL;
	int r;

	seed_prng();
	private_key_rsa = RSA_generate_key(length, 65537, NULL, NULL);
        private_key = (struct ndn_pkey *)EVP_PKEY_new();
        EVP_PKEY_assign_RSA ((EVP_PKEY *)private_key, private_key_rsa);
	save_seed ();

	if (!private_key_rsa || !private_key) {
		unsigned int err;

		err = ERR_get_error();
		PyErr_Format(g_PyExc_NDNKeyError, "Unable to generate the"
                             " key: %s", ERR_reason_error_string(err));
		return -1;
	}

	r = ndn_keypair(0, private_key, py_private_key_ndn,
                        py_public_key_ndn);
	if (r < 0)
		return -1;

	r = create_public_key_digest(private_key, py_public_key_digest,
                                     public_key_digest_len);
	if (r < 0)
		return -1;

        EVP_PKEY_free ((EVP_PKEY*)private_key);
        
	return 0;
}
示例#13
0
int main(int argc, char * argv[]) {
    BIO * acc, * client;
    THREAD_TYPE tid;
    SSL * ssl;
    SSL_CTX * ctx;

    init_OpenSSL();
    seed_prng();

    ctx = setup_server_ctx();
    
    acc = BIO_new_accept(PORT);
    if (!acc)
        int_error("Error creating server socket");
    if (BIO_do_accept(acc) <= 0)
        int_error("Error binding server socket");
    // BIO_do_accept() will block and wait for a remote connection.
    while (1) {
        if (BIO_do_accept(acc) <= 0)
            int_error("Error accepting connection");
        // get the client BIO
        client = BIO_pop(acc);
        if (!(ssl = SSL_new(ctx)))
            int_error("Error creating SSL context");
        SSL_set_accept_state(ssl);
        SSL_set_bio(ssl, client, client);
        // create a new thread to handle the new connection,
        // The thread will call do_server_loop with the client BIO.
        // THREAD_CREATE(tid, entry, arg);
        // tid is the id of the new thread.
        // server_thread is the function defined above, which will call
        // do_server_loop() with the client BIO.
        THREAD_CREATE(tid, server_thread, ssl);
    }
    SSL_CTX_free(ctx);
    BIO_free(acc);
    return 0;
}
示例#14
0
int main(int argc, char *argv[])
{
    BIO     *acc, *client;
    SSL     *ssl;
    SSL_CTX *ctx;
    THREAD_TYPE tid;

    init_OpenSSL(  );
    seed_prng();

 
    ctx = setup_server_ctx(  );
 
    acc = BIO_new_accept(PORT);
    if (!acc)
        int_error("Error creating server socket");
 
    if (BIO_do_accept(acc) <= 0)
        int_error("Error binding server socket");
 
    while(1)
    {
        if (BIO_do_accept(acc) <= 0)
            int_error("Error accepting connection");
 
        client = BIO_pop(acc);
        if (!(ssl = SSL_new(ctx)))
        int_error("Error creating SSL context");
        SSL_set_accept_state(ssl);
        SSL_set_bio(ssl, client, client);
        THREAD_CREATE(tid, (void *)server_thread, ssl);
    }
 
    SSL_CTX_free(ctx);
    BIO_free(acc);
    return 0;
}
示例#15
0
int main(int argc, char **argv)
{
    BIO *conn;
    SSL *ssl;
    SSL_CTX *ctx;

    init_openssl();
    seed_prng(64);

    ctx = setup_client_ctx();

    conn = BIO_new_connect(SERVER ":" PORT);
    if(!conn)
        log_err("Failed create bio connection");

    if(BIO_do_connect(conn) <= 0)
        log_err("Failed connecting to remote host");

    if(!(ssl = SSL_new(ctx)))
        log_err("Error creating an SSL context.");
    SSL_set_bio(ssl, conn, conn);
    if(SSL_connect(ssl) <= 0)
        log_err("Error connecting SSL object.");

    fprintf(stderr, "Connection opened\n");
    if(do_client(ssl))
        SSL_shutdown(ssl);
    else
        SSL_clear(ssl);
    fprintf(stderr, "Connection closed\n");

    //BIO_free(conn);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    return 0;
}
示例#16
0
文件: put.c 项目: Creuvard/Creuvux
static int Put(sqlite3 *db, const char *filename, const char *server, const char *grp, const char *username, const char *genre)
{
  SSL_CTX* ctx = NULL;
  SSL*     ssl = NULL;
	FILE *fd = NULL;
  int sd = -1;
  int port = -1;
  char *ep;
  long lval;
  int code = -1;
  off_t size = 0;
  char command[SIZE];
  char buf[SIZE];
  char size_c [SIZE];
  char *dscr = NULL;
  char *sha1 = NULL;
  char **a = NULL;
  char *blob = NULL;
  char dbname[SIZE];
  char msg[4096];
  int descr_fd = 0;
  errno = 0;

  /* ETA */
  struct timeval tv1, tv2;
  int sec1;
 
	/* On ouvre le fichier pour voir si il existe */
  if ((fd = fopen (filename, "rb")) == NULL)
    {
      fprintf (stderr, "Le fichier '%s' peut pas etre ouvert\n", filename);
      fprintf (stderr, "Verifiez les droits et son emplacements\n");
      exit (EXIT_FAILURE);
    }
	fclose (fd);
	
	char *real_name = NULL;
	real_name = basename((const char *)filename);
	if (real_name == NULL)
		return (NULL);
  
  size = crv_du (filename);
  if (size == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[007] crv_du() can't get size");
		return(-1);
  }
  snprintf(size_c, sizeof(size), "%lld", size);

	fprintf(stdout, "%s\n", "Determination de la signature numerique du fichier en cours ...");
	sha1 = crv_sha1(filename);

  /* Create info's file */
  (void)crv_strncpy (dbname, sha1, sizeof(dbname));
  (void)crv_strncat (dbname, ".db",  sizeof (dbname));

	if (many_files != 1) {
		int rep;
		fprintf (stdout, "Voulez-vous mettre des informations ? (o/n) :"); fflush(stdout);
		rep = fgetc (stdin);
		rep = toupper (rep);
		if (rep == 'O')
		{
			(void)crv_strncpy(msg, "", sizeof(msg));
			fprintf(stdout, "%s", "\nEntrez les informations du fichier (':wq' pour quitter)\n");
			fprintf(stdout, "%s", ">");
			memset(buf, 0, sizeof(buf));
			while (fgets(buf, sizeof(buf), stdin) != NULL) {
				if (!crv_strncmp(buf, ":wq\n"))
					break;
				(void)crv_strncat(msg, buf, sizeof(msg));
				fprintf(stdout, "%s", ">");
			}
		}
	}

	{
		int rep1;
		rep1 = -1;
		fprintf (stdout, "Voulez-vous mettre un Thumbnail ? (o/n) :"); fflush(stdout);
		rep1 = fgetc (stdin);
		rep1 = toupper (rep1);
		if (rep1 == 'O')
		{
			fprintf(stdout, "%s", "\nEntrez le chemin du fichier ('Enter' pour valider)\n");
			fprintf(stdout, "%s", ">");
			memset(buf, 0, sizeof(buf));
			while (fgets(buf, sizeof(buf), stdin) != NULL) {
				buf[strcspn(buf, "\n")] = '\0';
				if (strlen(buf) > 1)
					break;
			}
			blob = crv_strdup(buf);
		}

	}

	size = crv_du (filename);
  if (size == -1) {
		fprintf( stderr, "%s\n", "Put(): Err[007] crv_du() can't get size");
		return(-1);
  }
  memset(size_c, 0, sizeof(size_c));
  snprintf(size_c, sizeof(size_c), "%lld", size);
	/*
	fprintf (stdout, "DEBUG: DB Name='%s'\n", dbname);
	fprintf (stdout, "DEBUG: Sha1='%s'\n", sha1); 
  	fprintf (stdout, "DEBUG: Titre='%s'\n", real_name);
	fprintf (stdout, "DEBUG: Size='%s'\n", size_c);
	fprintf (stdout, "DEBUG: Pseudo='%s'\n", username);
	fprintf (stdout, "DEBUG: Message=\n`-> %s\n", msg);
	*/
	/*
	 * Database for file creation
	 */
	char *zErrMsg = 0;
	int rc = -1;
	char *req = NULL;
	sqlite3 *db_put;
	/* Open MAIN Database */
	rc = sqlite3_open( dbname, &db_put);
	if( rc ){
		fprintf(stderr, "Can't open database: %s", sqlite3_errmsg(db_put));
		sqlite3_close(db_put);
		return (-1);
	}
	
	/* Create Tables */
	if (create_db (db_put) == -1) {
		fprintf(stderr, "%s\n", "Put(): Database creation Failed");
		return (-1);
	}

	/* Fill Files tables*/
	/* CREATE TABLE Files (Sha1 TEXT NOT NULL, Name TEXT NOT NULL, Size NUMERIC NOT NULL); */
	req = sqlite3_mprintf("INSERT into Files (Sha1, Name, Size) values ('%q', '%q', '%q')", sha1, real_name, size_c);
	rc = sqlite3_exec(db_put, req, NULL, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}

	/* CREATE TABLE Categories (Sha1 TEXT NOT NULL, Cat TEXT NOT NULL); */
	req = sqlite3_mprintf("INSERT into Categories (Sha1, Cat) values ('%q', '%q')", sha1, genre);
	rc = sqlite3_exec(db_put, req, NULL, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}

	/* CREATE TABLE Descr (Sha1 TEXT NOT NULL, Descr LONGTEXT NOT NULL); */
	if (strlen(msg) > 0) {
		req = sqlite3_mprintf("INSERT into Descr (Sha1, Descr) values ('%q', '%q')", sha1, msg);
	} else
		req = sqlite3_mprintf("INSERT into Descr (Sha1, Descr) values ('%q', '')", sha1);
	rc = sqlite3_exec(db_put, req, NULL, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}

	/* CREATE TABLE Grp_Sha1 (groupname TEXT NOT NULL, sha1 TEXT NOT NULL); */
	req = sqlite3_mprintf("INSERT into Grp_Sha1 (groupname, sha1) values ('%q', '%q')", grp, sha1);
	rc = sqlite3_exec(db_put, req, NULL, 0, &zErrMsg);
	if( rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	}

	/* CREATE TABLE Grp_User (groupname TEXT NOT NULL, username TEXT NOT NULL); */
	if (username != NULL) {
		req = sqlite3_mprintf("INSERT into Grp_User (groupname, username) values ('%q', '%q')", grp, username);
		rc = sqlite3_exec(db_put, req, NULL, 0, &zErrMsg);
		if( rc!=SQLITE_OK ){
			fprintf(stderr, "SQL error: %s\n", zErrMsg);
			sqlite3_free(zErrMsg);
		}
	}

	/* CREATE TABLE Blob_Data (blob_title varchar(80), b blob); */
	/* insert into blobtest (des,b) values ('A test file: test.png',?); */
	if (blob != NULL) {
		int fd, n, i;
		long buflen = 0, totread = 0;
		char *bbuf = NULL, *pbuf = NULL;
		sqlite3_stmt *plineInfo = 0;

		if ((fd = open( blob, O_RDWR | O_CREAT, 0600)) == -1) {
			fprintf(stderr, "Can't open Blob: %s\n", strerror(errno));
			return 1;
		}
		while (buflen - totread - 1 < 1024)
		buflen = addmem(&bbuf, buflen);
		pbuf = bbuf;
		totread = 0;
		while ((n = read(fd, pbuf, 1024)) > 0) {
			totread += n;
			pbuf[n] = '\0';	// This is for printing test
			while (buflen - totread - 1 < 1024)
				buflen = addmem(&bbuf, buflen);
			pbuf = &bbuf[totread];
		}
		close(fd);
		req = sqlite3_mprintf("INSERT into Blob_Data (blob_title, b) values ('%q', ?)", "blob");
		rc = sqlite3_prepare(db_put, req, -1, &plineInfo, 0);
		if (rc == SQLITE_OK && plineInfo != NULL) {
			//fprintf(stderr, "SQLITE_OK\n");
			sqlite3_bind_blob(plineInfo, 1, bbuf, totread, free);
			sqlite3_step(plineInfo);
			rc = sqlite3_finalize(plineInfo);
		}	
		
	}
	sqlite3_close(db_put);

	/* Network zone */
	init_OpenSSL ();			  
  seed_prng ();
	a = crv_cut(server, ":");
  
	lval = strtol(a[1], &ep, 10);
  if (a[1][0] == '\0' || *ep != '\0') {
		fprintf(stderr, "%s\n", "Put(): Err[001] port is not a number");
		return (-1);
  }

  if ((errno == ERANGE && (lval == LONG_MAX
	  || lval == LONG_MIN)) ||
	  (lval > 65535 || lval < 0))
  {
		fprintf(stderr, "%s\n", "Put(): Err[002] port is out of range");
		return (-1);
  }
  port = lval;
  sd = crv_client_create( port, a[0], options.address_family);
  
  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Put() Err[003] Create new ssl failed");
		return(-1);
  }

  /* connect the SSL object with a file descriptor */
  code = SSL_set_fd (ssl, sd);
  if ( code == 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Put() Err[004] Put SSL on socket failed \n");
		return(-1);
  }

  code = SSL_connect (ssl);
  if (code == 0)	{
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[005] SSL_connect() failed");
		return(-1);
  } else
  if (code == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[006] SSL_connect() failed");
		return(-1);
  }

  /* Build command -> GET#version#sha1#begin#end */
  (void)crv_strncpy(command, "PUT#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, sha1, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, "0", sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, size_c, sizeof(command));
  
  /* Time initialisation */
  gettimeofday (&tv1, NULL);

  code = SSL_write (ssl, command, (int)strlen(command));
  if ( code <= 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed.");
	return(-1);
  }

  code = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[code] = '\0';

  if(!crv_strncmp (buf, "PUT_ACK"))
  {
		fprintf(stdout, "\n\n");
		code = SSL_sendfile(ssl, sha1, filename, (off_t)0, size);	
		if (code == -1) {
			close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed");
			return(-1);
		}
  }
  
  code = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END"));
  if ( code <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed.");
		return(-1);
  }


  gettimeofday (&tv2, NULL);
  /* compute difference */
  sec1 = tv2.tv_sec - tv1.tv_sec;
  int min;
  float average;
  average = ((float) size / (float) sec1) / 1024;
  min = sec1 / 60;
  sec1 = sec1 - min * 60;
  fprintf (stdout,
	     "\n\nFile download in %d min  %d sec \nSpeed average -> %.f KBps\n\n",
	     min, sec1, average);

  close(sd); SSL_free (ssl); SSL_CTX_free (ctx);crv_free(sha1);


  /* Send file's decription */
  init_OpenSSL ();			  
  seed_prng ();
  sd = crv_client_create( port, a[0], options.address_family);
  
  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "Put() Err[003] Create new ssl failed");
	return(-1);
  }

  /* connect the SSL object with a file descriptor */
  code = SSL_set_fd (ssl, sd);
  if ( code == 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "Put() Err[004] Put SSL on socket failed \n");
	return(-1);
  }

  code = SSL_connect (ssl);
  if (code == 0)	{
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "Put(): Err[005] SSL_connect() failed");
	return(-1);
  } else
  if (code == -1) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "Put(): Err[006] SSL_connect() failed");
	return(-1);
  }

	size = crv_du (dbname);
  if (size == -1) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "Put(): Err[007] crv_du() can't get size");
	return(-1);
  }
  memset(size_c, 0, sizeof(size_c));
  snprintf(size_c, sizeof(size), "%lld", size);

	sha1 = crv_sha1(dbname);
  
  /* Build command -> GET#version#sha1#begin#end */
  (void)crv_strncpy(command, "COMMENT#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, sha1, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, "0", sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, size_c, sizeof(command));
  
  code = SSL_write (ssl, command, (int)strlen(command));
  if ( code <= 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed.");
	return(-1);
  }

  code = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[code] = '\0';

  if(!strncmp (buf, "PUT_ACK", strlen("PUT_ACK")))
  {
		code = SSL_sendfile(ssl, sha1, dbname, (off_t)0, size);	
		if (code == -1) {
			close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed");
			return(-1);
		}
  }
  
  code = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END"));
  if ( code <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed.");
		return(-1);
  }


	fprintf(stdout, "%s", "Information about file is uploaded\n"); 

  /* Delete DB Meta Data */
  
  code = unlink((const char *)dbname);
  if (code == -1) {
		fprintf(stderr, "%s%s\n", 
			"Put(): Err[010] unlink() failed with error -> ",
			strerror(errno));
		return (-1);
  }
  

  close(sd); SSL_free (ssl); SSL_CTX_free (ctx);crv_free(sha1);
  return (0);

}
示例#17
0
void srand( unsigned int seed )
{
	seed_prng( seed );
}
示例#18
0
文件: sync.c 项目: Creuvard/Creuvux
static void 
receive_sync_file (void *arg)
{
  int sd;
  int code = 0;
  int port;
  int i;
  long lval;
  char command[SIZE];
  char *sync_arg = arg;
  char buf[4096];
  char *ep = NULL;
  char host_port[SIZE];
  char **c = NULL;
  FILE *fd = NULL;
  SSL_CTX* ctx;
  SSL*     ssl;


  c = crv_cut (sync_arg, ":");
  lval = strtol(c[1], &ep, 10);
  if (c[0][0] == '\0' || *ep != '\0') {
    fprintf(stderr, "%s\n", "Sync(): Err[002] Check port on serveur_liste");
    return ;
  }
  if (lval > 65535 || lval < 0) {
    fprintf(stderr, "%s\n", "Sync(): Err[003] Check port on serveur_liste");
    return ;
  }
  port = lval;

  crv_strncpy (host_port, "./listing/", sizeof(host_port));
  crv_strncat (host_port, c[0], sizeof(host_port));	/* put server name in host_port */
  crv_strncat (host_port, ".db", sizeof(host_port));	/* add : behind server name */
  fprintf (stdout, "%s", "Listing reception on ");
  fflush(stdout);

#ifndef WIN32
      couleur ("33;31");
#else
      couleur (12, 0);
#endif
      fprintf (stdout, "'%s'", c[0]);
	  fflush(stdout);
#ifndef WIN32
      couleur ("0");
#else
      couleur (15, 0);
#endif
      fprintf (stdout, "%s\n", " is running ...");

  /* SSL preliminaries */
  init_OpenSSL ();			  
  seed_prng ();
  
  sd = crv_client_create(port, c[0], options.address_family);
	if (sd == -1) {
		close(sd);
		pthread_exit(NULL);
	}

  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_sync_file() Err[001] Create new ssl failed");
	pthread_exit(NULL);
  }
		
  /* connect the SSL object with a file descriptor */
  code = SSL_set_fd (ssl, sd);
  if ( code == 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_sync_file() Err[002] Put SSL on socket failed \n");
	pthread_exit(NULL);
  }

  code = SSL_connect (ssl);
  if (code == 0)	{
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "receive_sync_file(): Err[003] SSL_connect() failed");
	pthread_exit (NULL);
  } else
  if (code == -1) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "receive_sync_file(): Err[004] SSL_connect() failed");
	pthread_exit (NULL);
  }
 
  
  #ifndef WIN32
  /* 
  code = post_connection_check (ssl, c[0]);
  if (code != X509_V_OK)
  {
	fprintf (stderr, "-Error: peer certificate: %s\n", X509_verify_cert_error_string (code));
	  close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "receive_sync_file(): Err[004'] post_connection_check() failed");
	  pthread_exit (NULL);
  }
  */
  #endif
  for (i = 0; c[i]; i++)
	crv_free(c[i]); 

  fd = crv_fopen(host_port, "w");
  if (fd == NULL) {
	fclose(fd); close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_sync_file(): Err[005] crv_fopen() failed");
	pthread_exit (NULL);
  }
  
  /* Build command -> SYNC#version */
  (void)crv_strncpy(command, "SYNC#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  
  code = SSL_write (ssl, command, (int)strlen(command));
  if ( code <= 0) {
	fclose(fd); close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_sync_file(): Err[006] SSL_write() failed.");
	pthread_exit(NULL);
  }

  code = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[code] = '\0';
  if(!strncmp (buf, "SYNC_ACK", strlen("SYNC_ACK")))
  {
	for (;;)
	{
		code = SSL_read (ssl, buf, sizeof (buf));
		switch (SSL_get_error (ssl, code))
        {
		  case SSL_ERROR_NONE:
		  case SSL_ERROR_ZERO_RETURN:
		  case SSL_ERROR_WANT_READ:
		  case SSL_ERROR_WANT_WRITE:
			break;
		  default:
			fclose(fd); close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "0)Can't receive LISTING\n");
			pthread_exit (NULL);
		}

	  if (!strncmp (buf, "SYNC_END", strlen("SYNC_END"))) {
	    break;
	  }
	  code = fwrite (&buf, (size_t) code, 1, fd);
	  if (code <= 0) {
		fclose(fd); close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	    fprintf(stderr, "1)Can't write LISTING file\n");
		pthread_exit (NULL);
	  }
	}
  }

  fclose(fd);
  close (sd);
  SSL_free (ssl);
  SSL_CTX_free (ctx);

  pthread_exit (NULL);
}
示例#19
0
int Gtk_Put(const char *filename, const char *file_descrip, const char *server, const char *Sha1)
{
  SSL_CTX* ctx = NULL;
  SSL*     ssl = NULL;
  int sd = -1;
  int port = -1;
  char *ep;
  long lval;
  int code = -1;
  off_t size = 0;
  char command[SIZE];
  char buf[SIZE];
  char size_c [SIZE];
  char *dscr = NULL;
	char *sha1 = NULL;
	char **a = NULL;
	int descr_fd = 0;
  errno = 0;

  /* ETA */
  struct timeval tv1, tv2;
  int sec1;
  
  
  init_OpenSSL ();			  
  seed_prng ();
	
  size = crv_du (filename);
  if (size == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[007] crv_du() can't get size");
		return(-1);
  }
  snprintf(size_c, sizeof(size), "%lld", size);

  a = crv_cut(server, ":");
  
	lval = strtol(a[1], &ep, 10);
  if (a[1][0] == '\0' || *ep != '\0') {
		fprintf(stderr, "%s\n", "Put(): Err[001] port is not a number");
		return (-1);
  }

  if ((errno == ERANGE && (lval == LONG_MAX
	  || lval == LONG_MIN)) ||
	  (lval > 65535 || lval < 0))
  {
		fprintf(stderr, "%s\n", "Put(): Err[002] port is out of range");
		return (-1);
  }
  port = lval;
  sd = crv_client_create( port, a[0], options.address_family);
  
  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Put() Err[003] Create new ssl failed");
		return(-1);
  }

  /* connect the SSL object with a file descriptor */
  code = SSL_set_fd (ssl, sd);
  if ( code == 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Put() Err[004] Put SSL on socket failed \n");
		return(-1);
  }

  code = SSL_connect (ssl);
  if (code == 0)	{
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[005] SSL_connect() failed");
		return(-1);
  } else
  if (code == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[006] SSL_connect() failed");
		return(-1);
  }

  /* Build command -> GET#version#sha1#begin#end */
  (void)crv_strncpy(command, "PUT#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, Sha1, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, "0", sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, size_c, sizeof(command));
  
  /* Time initialisation */
  gettimeofday (&tv1, NULL);

  code = SSL_write (ssl, command, (int)strlen(command));
  if ( code <= 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed.");
	return(-1);
  }

  code = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[code] = '\0';

  if(!crv_strncmp (buf, "PUT_ACK"))
  {
		fprintf(stdout, "\n\n");
		code = SSL_sendfile(ssl, Sha1, filename, (off_t)0, size);	
		if (code == -1) {
			close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed");
			return(-1);
		}
  }
  
  code = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END"));
  if ( code <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed.");
		return(-1);
  }


  gettimeofday (&tv2, NULL);
  /* compute difference */
  sec1 = tv2.tv_sec - tv1.tv_sec;
  int min;
  float average;
  average = ((float) size / (float) sec1) / 1024;
  min = sec1 / 60;
  sec1 = sec1 - min * 60;
  fprintf (stdout,
	     "\n\nFile download in %d min  %d sec \nSpeed average -> %.f KBps\n\n",
	     min, sec1, average);

  close(sd); SSL_free (ssl); SSL_CTX_free (ctx);


  /* Send file's decription */
  init_OpenSSL ();			  
  seed_prng ();
  sd = crv_client_create( port, a[0], options.address_family);
  
  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "Put() Err[003] Create new ssl failed");
	return(-1);
  }

  /* connect the SSL object with a file descriptor */
  code = SSL_set_fd (ssl, sd);
  if ( code == 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "Put() Err[004] Put SSL on socket failed \n");
	return(-1);
  }

  code = SSL_connect (ssl);
  if (code == 0)	{
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "Put(): Err[005] SSL_connect() failed");
	return(-1);
  } else
  if (code == -1) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf( stderr, "%s\n", "Put(): Err[006] SSL_connect() failed");
	return(-1);
  }

	fprintf(stderr, "File: '%s'\n", file_descrip);
	size = -1;
	size = crv_du (file_descrip);
	fprintf(stderr, "Size: '%lld'\n", size);
  if (size == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Put(): Err[007] crv_du() can't get size");
		return(-1);
  }
  memset(size_c, 0, sizeof(size_c));
  snprintf(size_c, sizeof(size), "%lld", size);

	sha1 = crv_sha1(file_descrip);
  
  /* Build command -> GET#version#sha1#begin#end */
  (void)crv_strncpy(command, "COMMENT#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, sha1, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, "0", sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, size_c, sizeof(command));
	fprintf(stderr, "CMD:'%s'\n", command);
  
  code = SSL_write (ssl, command, (int)strlen(command));
  if ( code <= 0) {
	close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
	fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed.");
	return(-1);
  }

  code = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[code] = '\0';

  if(!strncmp (buf, "PUT_ACK", strlen("PUT_ACK")))
  {
		code = SSL_sendfile(ssl, sha1, file_descrip, (off_t)0, size);	
		if (code == -1) {
			close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed");
			return(-1);
		}
  }
  
  code = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END"));
  if ( code <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed.");
		return(-1);
  }


	fprintf(stdout, "%s", "Information about file is uploaded\n"); 

	code = unlink((const char *)file_descrip);
  if (code == -1) {
		fprintf(stderr, "%s%s\n", 
			"Put(): Err[010] unlink() failed with error -> ",
			strerror(errno));
		return (-1);
  }

  close(sd); SSL_free (ssl); SSL_CTX_free (ctx);crv_free(sha1);
  return (0);

}
示例#20
0
文件: msg.c 项目: Creuvard/Creuvux
int Msg(const char *id)
{
	FILE *fd = NULL;
	char buf[SIZE];
	char command[SIZE];
	int result = -1;
	off_t size;
	char size_c[SIZE];
	SSL_CTX* ctx = NULL;
  SSL*     ssl = NULL;
  int sd = -1;
	
	errno = 0;
	sha1 = NULL;  /* Sha1 for wanted ID */
	server = NULL;/* server for wanted ID */
	port = 0;			/* port for Wanted ID*/


	/* Get info about file */
	get_server_info(id);
	get_sha1(id);



	fd = crv_fopen(sha1, "w");
  if (fd == NULL) {
		fprintf( stderr, "%s\n", "Msg(): Err[001] crv_fopen() failed");
		return (-1);
	}
	fprintf(fd, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
	fprintf(fd, "<comment><![CDATA[");
	fprintf(stdout, "%s", "\nEntrez votre reponse(':wq' pour quitter)\n");
	fprintf(stdout, "%s", ">");
	while (fgets(buf, sizeof(buf), stdin) != NULL) {
		buf[strcspn(buf, "\n")] = '\0';
		if (!crv_strncmp(buf, ":wq"))
			break;
		fprintf(fd, "%s\n", buf);
		fprintf(stdout, "%s", ">");
	}
	fprintf(fd, "]]></comment>\n");
	fclose(fd);
	

	/*
	 * Build command -> GET#version#sha1#begin#end 
	 */
	size = crv_du (sha1);
  if (size == -1) {
		fprintf( stderr, "%s\n", "Put(): Err[002] crv_du() can't get size");
		return(-1);
  }
  snprintf(size_c, sizeof(size), "%lld", size);

  (void)crv_strncpy(command, "MSG_REPLY#", sizeof(command));
  (void)crv_strncat(command, CREUVUX_VERSION, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, sha1, sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, "0", sizeof(command));
  (void)crv_strncat(command, "#", sizeof(command));
  (void)crv_strncat(command, size_c, sizeof(command));
	/*
	 * Connection.
	 */
	init_OpenSSL ();			  
  seed_prng ();
	sd = crv_client_create( port, server, options.address_family);

  /* We keep the certificate and key with the context. */
  ctx = setup_client_ctx ();

  /* TCP connection is ready. Do server side SSL. */
  ssl = SSL_new (ctx);
  if ((ssl)==NULL) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Msg() Err[003] Create new ssl failed");
		return(-1);
  }

  /* connect the SSL object with a file descriptor */
  result = SSL_set_fd (ssl, sd);
  if ( result == 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "Msg() Err[004] Put SSL on socket failed \n");
		return(-1);
  }

  result = SSL_connect (ssl);
  if (result == 0)	{
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Msg(): Err[005] SSL_connect() failed");
		return(-1);
  } else
  if (result == -1) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf( stderr, "%s\n", "Msg(): Err[006] SSL_connect() failed");
		return(-1);
  }

	result = SSL_write (ssl, command, (int)strlen(command));
  if ( result <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[011] SSL_write() failed.");
		return(-1);
  }

  result = SSL_read (ssl, buf, sizeof(buf) - 1);
  buf[result] = '\0';

  if(!strncmp (buf, "PUT_ACK", strlen("PUT_ACK")))
  {
		fprintf(stdout, "\n\n");
		result = SSL_sendfile(ssl, NULL, sha1, (off_t)0, size);	
		if (result == -1) {
			close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
			fprintf(stderr, "%s\n", "Put() Err[012] SSL_sendfile() failed");
			return(-1);
		}
  }
  
  result = SSL_write (ssl, "PUT_END", (int)strlen("PUT_END"));
  if ( result <= 0) {
		close(sd); SSL_free (ssl); SSL_CTX_free (ctx);
		fprintf(stderr, "%s\n", "receive_get_file(): Err[013] SSL_write() failed.");
		return(-1);
  }

	result = unlink((const char *)sha1);
  if (result == -1) {
		fprintf(stderr, "%s%s\n", 
					"Msg(): Err[007] unlink() failed with error -> ",
					strerror(errno));
		return (-1);
  }
	
	return (0);
}
示例#21
0
int
main(int argc, char *argv[])
{
    int opt;
    char *config_file = NULL;
    int i = 0;
    unsigned rnd_seed = 0;
    int seed_set = 0;

    program_name = argv[0];

    while ((opt = getopt(argc, argv, "ae:hioqR:s:v")) != EOF) {
	switch (opt) {
	case 'a':
	    AIRPORT_MARKER = 1;
	    break;
	case 'e':
	    config_file = optarg;
	    break;
	case 'i':
	    DISTINCT_ISLANDS = 0;
	    break;
	case 'o':
	    ORE = 0;
	    break;
	case 'q':
	    quiet = 1;
	    break;
	case 'R':
	    rnd_seed = strtoul(optarg, NULL, 10);
	    seed_set = 1;
	    break;
	case 's':
	    outfile = optarg;
	    break;
	case 'h':
	    usage();
	    exit(0);
	case 'v':
	    printf("%s\n\n%s", version, legal);
	    exit(0);
	default:
	    help(NULL);
	    exit(1);
	}
    }
    parse_args(argc - optind, argv + optind);

    if (!seed_set)
	rnd_seed = pick_seed();
    seed_prng(rnd_seed);
    empfile_init();
    if (emp_config(config_file) < 0)
	exit(1);
    empfile_fixup();

    allocate_memory();
    print_vars();

    qprint("\n        #*# ...fairland rips open a rift in the datumplane... #*#\n\n");
    qprint("seed is %u\n", rnd_seed);
    do {
	init();
	if (i)
	    qprint("\ntry #%d (out of %d)...\n", i + 1, NUMTRIES);
	qprint("placing capitals...\n");
	if (!drift())
	    qprint("fairland: unstable drift -- try increasisg DRIFT_MAX\n");
	qprint("growing continents...\n");
	grow_continents();
    } while (fl_status && ++i < NUMTRIES);
    if (fl_status) {
	fputs("ERROR: World not large enough to hold continents\n",
	      stderr);
	exit(1);
    }
    qprint("growing islands:");
    grow_islands();
    qprint("\nelevating land...\n");
    create_elevations();
    qprint("designating sectors...\n");
    if (ORE)
	qprint("adding resources...\n");
    write_newcap_script();

    if (chdir(gamedir)) {
	fprintf(stderr, "Can't chdir to %s (%s)\n", gamedir, strerror(errno));
	exit(EXIT_FAILURE);
    }
    if (!ef_open(EF_SECTOR, EFF_MEM | EFF_NOTIME))
	exit(1);
    write_sects();
    qprint("writing to sectors file...\n");
    if (!ef_close(EF_SECTOR))
	exit(1);

    output();
    qprint("\n\nA script for adding all the countries can be found in \"%s\".\n",
	   outfile);
    if (!ORE)
	qprint("\t*** Resources have not been added ***\n");
    exit(0);
}
示例#22
0
/*
 * The main TCP accpet loop
 */
void
server_accept_loop()
{
  fd_set *fdset;
  int maxfd, i, ret, err;
  int newsock;
  struct sockaddr_in from;
  socklen_t fromlen;
  int handcheck = -1;
  int sock;
  char **addr = NULL;
	int pfd[2];

	fdset = NULL;
	maxfd = 0;
	
	signal(SIGPIPE, SIG_IGN);
	signal(SIGTERM, ctr_c);
	signal(SIGQUIT, ctr_c);
	signal(SIGINT, ctr_c);

  /* SSL preliminaries */
  SSL_CTX* ctx;
  SSL*     ssl;
  init_OpenSSL ();			  
  seed_prng ();	

  /* We keep the certificate and key with the context. */
  ctx = setup_server_ctx ();
  
  addr = crv_cut(options.listen_addrs, " ");
  for (i = 0; addr[i]; i++)
  {
		/* Prepare TCP socket for receiving connections (change user for ROOT if port < 1024  )*/
		sock = crv_server_listen(options.num_ports, 5, addr[i], options.address_family, 1);
		if (sock == -1) {
			fprintf( stderr, "%s\n", "main(): server_listent() failed");
			exit (EXIT_FAILURE);
		}
		/* Add comment (listening on several adress )*/
		listen_socks[num_listen_socks] = sock;
		num_listen_socks++;
  }

  for( i = 0; addr[i]; i++)
		crv_free(addr[i]);
  crv_free(addr);

  for (i = 0; i < num_listen_socks; i++)
		if (listen_socks[i] > maxfd)
			maxfd = listen_socks[i];
 
  /* loop */
  for(;;)
  {
		newsock = -1;
		int pid;
		handcheck = -1;

		if (fdset != NULL)
			free(fdset);
	
		fdset = (fd_set *) calloc(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));

		for ( i = 0; i < num_listen_socks; i++)
			FD_SET(listen_socks[i], fdset);


		/* wait in select until there is a connection. */
		ret = select(maxfd+1, fdset, NULL, NULL, NULL);
		if (ret < 0 && errno != EINTR)  
			Log ( "WARNING", 0, "select: %.100s", strerror(errno));
	
		for ( i = 0; i < num_listen_socks; i++)
			if ( FD_ISSET(listen_socks[i], fdset)) {
				fromlen = sizeof(from);
				newsock = accept(listen_socks[i], (struct sockaddr *)&from, &fromlen);
				if (newsock < 0) {
					if (errno != EINTR && errno != EWOULDBLOCK )
						Log ( "WARNING", 0, "accept: %.100s", strerror(errno));
					continue;
				}

				if (received_sigterm) {
					fprintf( stderr, "Received signal %d; terminating.\n",
						(int) received_sigterm);
					close_listen_socks();
					unlink(options.pid);
					return;
				}
		
				if (crv_unset_nonblock(newsock) == -1) {
					Log ( "CRASH", 0, "Unset nonblock failed");
					continue;
				}
		
				/* TCP connection is ready. Do server side SSL. */
				ssl = SSL_new (ctx);
				if ((ssl)==NULL) {
					Log ( "CRASH", 0, "Create new ssl failed");
					continue;
				}
		
				/* connect the SSL object with a file descriptor */
				err = SSL_set_fd (ssl, newsock);
				if ((err)==0) {
					Log ( "CRASH", 0, "Put SSL on socket failed \n");
					close(newsock);
					continue;
				}

				/* TCP connection is ready. Do server side SSL. */
				err = SSL_accept (ssl);
				if ((err) <= 0) {
					Log ("HACK", 0, "%s handcheck failed", inet_ntoa(from.sin_addr));
					/* Free the allocated SSL structure */
					SSL_free (ssl);
					continue;
				} 
				else {
					handcheck = 0;
				}

				if ( handcheck != -1 )
				{
					/* Pipe creation */
					if (pipe(pfd) == -1)
					{
						fprintf( stderr, "%s\n", "server_accept_loop(): pipe() failed");
						return;
					}

					switch((pid = fork()))
					{
						/* fork() Error */
						case -1:
							Log ("CRASH", 0, "%s%s\n", "Error on fork() -> ", strerror(errno));
							exit (EXIT_FAILURE);
				
						/* First child process */
						case 0:
							/* Close socket that has been created in create_tcp_socket() */
							close_listen_socks();
							int result = 0;
							
							/* Chroot process */
							if (result != -1) 
								result = crv_drop_priv_perm_and_chroot (options.user , options.chroot_directory );

							initialize_command_opt(&command);
							command.addr = crv_strdup((const char *)inet_ntoa (from.sin_addr));
					
							if (options.sec == 1) {
								result = post_connection_check (ssl, command.addr);
								if (result != X509_V_OK) {
									Log ( "HACK", 0, 
									"-Error: peer certificate: %s\n",
									X509_verify_cert_error_string (result));
									result = -1;
								}
							}

							/* Time initialisation */
							gettimeofday (&tv1, NULL);

							/* Get client name*/
							char buff[SIZE];
							command.user = recup_pseudo (ssl);
							command.mail = recup_email (ssl);

							/* Send client pseudo to father */
							write(pfd[1], command.user, strlen(command.user)+1);
							close(pfd[1]); /* close write side */

							sleep(1);
							memset(buff, 0, sizeof(buff));
							
							/* Read repond from father */
							(void)read(pfd[0], buff, SIZE);
							close(pfd[0]);
							
							/* Get father respond about client pseudo */
							/* Les pipes sont à enlever car, la liste des utilisateurs autorisés
							 * sont contenue sur la base de données distante
							if (!crv_strncmp(buff, "no_register")) {
								Log ("WARNING", 0, "Username '%s' is not registered", command.user);
								result = -1;
							}
							*/
							printf("buff:%s\n", buff);
						
							/* Get CMD info (comd name, sha1 file, begin, end) */
							if (result != -1)
								result = pre_authcon( ssl, (const char *)buff);

							if ( result == -1)
								Log ("WARNING", 0, "Can't set command options");
				
							/* exec command give by client */
							if (result != -1)
								traitement_conec ( ssl);
					
							/* Free command structure */
							Free_cmd_struct();
					
							/* Close Socket , tube */
							shutdown (newsock, 2);
							close (newsock);
					
							/* Free the allocated SSL structure */
							SSL_free (ssl);
					
							/* Free the allocated SSL CONTEXT object */
							SSL_CTX_free (ctx);

							/* EXIT */
							exit (EXIT_SUCCESS);
			
						/* Father process */
						default:
							{	
								char *xpath = NULL;
								char Buffer[SIZE];

								/* Read client pseudo from son */
								(void)read(pfd[0], Buffer, SIZE);
								//xpath = get_grp_list(Buffer);
								close(pfd[0]); /* close read side */
								
								if (xpath == NULL)
									xpath = crv_strdup("no_register");
							
								(void)crv_strncpy(Buffer, xpath, sizeof(Buffer));
								(void)write(pfd[1], Buffer, strlen(Buffer)+1);
								close(pfd[1]);
								if (xpath != NULL)
									crv_free(xpath);

								SSL_free (ssl);
								close(newsock);
							}
					} /* End of fork() */

				} /* if handcheck is 0 */

			} /* FD_ISSET */

		} /* End of for() loop */
}