예제 #1
0
int
Thread_setup(void)
{
#ifdef _USE_OPENSSL
  int i;
  mutex_buf = (MUTEX_TYPE *)malloc(sizeof(MUTEX_TYPE) * CRYPTO_num_locks());

  if(!mutex_buf)
    return 0;
  for ( i = 0 ; i < CRYPTO_num_locks() ; i++)
    MUTEX_SETUP(mutex_buf[i]);
  CRYPTO_set_id_callback(id_function);
  CRYPTO_set_locking_callback(locking_function);
  /*
  **  Dynamic locking routine registration
  **/
#ifdef _DYNAMIC_LOCKING_MECHANISM_

  CRYPTO_set_dynlock_create_callback(dyn_create_function);
  CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
  CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
#endif
  return 1;
#else
  return -1;
#endif

}
예제 #2
0
파일: ehs.cpp 프로젝트: Audifire/mtasa-blue
EHSConnection::EHSConnection ( NetworkAbstraction * ipoNetworkAbstraction,
							   EHSServer * ipoEHSServer ) :
	m_nDoneReading ( 0 ),
	m_nDisconnected ( 0 ),
	m_nRequests ( 0 ),
	m_nResponses ( 0 ),
	m_poNetworkAbstraction ( ipoNetworkAbstraction ),
	m_poCurrentHttpRequest ( NULL ),
	m_poEHSServer ( ipoEHSServer ),
    m_iStopASAP ( 0 )
{
    m_UnusedSyncId = 0;
	UpdateLastActivity ( );

	// initialize mutex for this object
	MUTEX_SETUP ( m_oConnectionMutex );

	// get the address and port of the new connection
	m_sAddress = ipoNetworkAbstraction->GetAddress ( );
	m_nPort = ipoNetworkAbstraction->GetPort ( );
	
	// make sure the buffer is clear
	m_sBuffer = "";


#ifdef EHS_MEMORY
	fprintf ( stderr, "[EHS_MEMORY] Allocated: EHSConnection\n" );
#endif
}
예제 #3
0
파일: sslclient.c 프로젝트: JinpengLI/gsoap
static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
{ struct CRYPTO_dynlock_value *value;
  value = (struct CRYPTO_dynlock_value*)malloc(sizeof(struct CRYPTO_dynlock_value));
  if (value)
    MUTEX_SETUP(value->mutex);
  return value;
}
예제 #4
0
파일: list.c 프로젝트: hashyuan/corenova
static list_t *
_newList (void) {
	list_t *list = (list_t *) calloc (1, sizeof (list_t));
	if (list) {
		MUTEX_SETUP (list->lock);
	}
	return list;
}
예제 #5
0
static void setupMutex(void)
{
   mutex_buf = (MUTEX_TYPE*) malloc(sizeof(MUTEX_TYPE));

   if(!mutex_buf)
      throw SecurityException(MEMORY_ALLOC_FAILED, NULL);
   MUTEX_SETUP(*mutex_buf);

}
예제 #6
0
static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
{
	if (!file || !line)
		pmesg_safe(&global_flag, LOG_ERROR, __FILE__, __LINE__, "");
	struct CRYPTO_dynlock_value *value;
	value = (struct CRYPTO_dynlock_value *) malloc(sizeof(struct CRYPTO_dynlock_value));
	if (value)
		MUTEX_SETUP(value->mutex);
	return value;
}
예제 #7
0
파일: gps3ext.cpp 프로젝트: a320321wb/gpdb
int thread_setup(void) {
    int i;

    mutex_buf =
        (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
    if (!mutex_buf) return 0;
    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);
    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);
    return 1;
}
예제 #8
0
struct CRYPTO_dynlock_value *
CRYPTO_dynlock_value(const char *file,int line) {
  struct CRYPTO_dynlock_value *value;

  value = (CRYPTO_dynlock_value  *)malloc(sizeof(struct CRYPTO_dynlock_value));

  if(!value)
    return NULL;

  MUTEX_SETUP(value -> mutex);
  return value;
}
예제 #9
0
void thread_setup ()
{
#ifndef HAVE_CLIENT
  mutex_buf = malloc (CRYPTO_num_locks () * sizeof(MUTEX_TYPE));
  if (!mutex_buf) return;
  int i;
  for (i = 0;  i < CRYPTO_num_locks ();  i++)
    MUTEX_SETUP (mutex_buf[i]);
  CRYPTO_set_id_callback (id_function);
  CRYPTO_set_locking_callback (locking_function);
#endif
}
예제 #10
0
파일: sslclient.c 프로젝트: JinpengLI/gsoap
int CRYPTO_thread_setup()
{ int i;
  mutex_buf = (MUTEX_TYPE*)malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  if (!mutex_buf)
    return SOAP_EOM;
  for (i = 0; i < CRYPTO_num_locks(); i++)
    MUTEX_SETUP(mutex_buf[i]);
  CRYPTO_set_id_callback(id_function);
  CRYPTO_set_locking_callback(locking_function);
  CRYPTO_set_dynlock_create_callback(dyn_create_function);
  CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
  CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
  return SOAP_OK;
}
예제 #11
0
파일: ssl.c 프로젝트: N0NB/aprx
static int ssl_thread_setup(void)
{
	int i;
	
	hlog(LOG_DEBUG, "Creating OpenSSL mutexes (%d)...", CRYPTO_num_locks());
	
	mutex_buf = hmalloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
	
	for (i = 0;  i < CRYPTO_num_locks();  i++)
		MUTEX_SETUP(mutex_buf[i]);
	
	CRYPTO_set_id_callback(ssl_thread_id_function);
	CRYPTO_set_locking_callback(ssl_thread_locking_function);
	
	return 0;
}
예제 #12
0
int thread_openssl_setup(void)
{
    int i;

    mutex_arr = (MUTEX_TYPE *) malloc(CRYPTO_num_locks( ) * sizeof(MUTEX_TYPE));

    if (!mutex_arr)
        return -1;

    for (i = 0; i < CRYPTO_num_locks( ); i++)
        MUTEX_SETUP(mutex_arr[i]);

    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);
    return 0;
}
예제 #13
0
int CRYPTO_thread_setup()
{
   int i;
   //mutex_buf = (MUTEX_TYPE*)malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
   mutex_buf = (MUTEX_TYPE*)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
   if (!mutex_buf)
      return -1;
   for (i = 0; i < CRYPTO_num_locks(); i++)
      MUTEX_SETUP(mutex_buf[i]);
   CRYPTO_set_id_callback(id_function);
   CRYPTO_set_locking_callback(locking_function);
   //CRYPTO_set_dynlock_create_callback(dyn_create_function);
   //CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
   //CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
   return 0;
}
예제 #14
0
파일: common.c 프로젝트: modsix/destroyd
int THREAD_setup(void) {
	int i;

	mutex_buf = (MUTEX_TYPE *) malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
	if(!mutex_buf) {
		return 0; 
	}

	for(i = 0; i < CRYPTO_num_locks(); i++) {
		MUTEX_SETUP(mutex_buf[i]);
	}

	CRYPTO_set_id_callback(id_function);
	CRYPTO_set_locking_callback(locking_function);

	return 1;
}
예제 #15
0
int ezs_THREAD_setup(void)
{
  int i;
  mutex_buf = (MUTEX_T *)malloc(CRYPTO_num_locks() * sizeof(MUTEX_T));
  if (!mutex_buf) return 0;
  /* this should not be necessary */
  memset(mutex_buf, '\0', CRYPTO_num_locks()*sizeof(MUTEX_T));
  for (i = 0; i < CRYPTO_num_locks( ); i++) MUTEX_SETUP(mutex_buf[i]);
  CRYPTO_set_id_callback(id_function);
  CRYPTO_set_locking_callback(locking_function);
  /* The following three CRYPTO_... functions are the OpenSSL functions
     for registering the callbacks we implemented above */
  CRYPTO_set_dynlock_create_callback(dyn_create_function);
  CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
  CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
  return 1;
}
예제 #16
0
파일: ehs.cpp 프로젝트: Audifire/mtasa-blue
EHSServer::EHSServer ( EHS * ipoTopLevelEHS ///< pointer to top-level EHS for request routing
	) :
	m_nServerRunningStatus ( SERVERRUNNING_NOTRUNNING ),
	m_poTopLevelEHS ( ipoTopLevelEHS ),
	m_nRequestsPending ( 0 ),
	m_nIdleTimeout ( 15 )
{
	// you HAVE to specify a top-level EHS object
	//  compare against NULL for 64-bit systems
	assert ( m_poTopLevelEHS != NULL );

	
	MUTEX_SETUP ( m_oMutex );
	pthread_cond_init ( & m_oDoneAccepting, NULL );

	m_nAccepting = 0;
    m_iActiveThreadCount = 0;

	// grab out the parameters for less typing later on
	EHSServerParameters & roEHSServerParameters = 
		ipoTopLevelEHS->m_oEHSServerParameters;

	// whether to run with https support
	int nHttps = roEHSServerParameters [ "https" ];

#ifdef EHS_MEMORY
	fprintf ( stderr, "[EHS_MEMORY] Allocated: EHSServer\n" );
#endif		


	if ( nHttps ) {
		EHS_TRACE ( "EHSServer running in HTTPS mode\n");
	} else {
		EHS_TRACE ( "EHSServer running in plain-text mode (no HTTPS)\n");
	}

	

	// are we using secure sockets?
	if ( !nHttps ) {
		m_poNetworkAbstraction = new Socket ( );
	} else {

#ifdef COMPILE_WITH_SSL		


		EHS_TRACE ( "Trying to create secure socket with certificate='%s' and passphrase='%s'\n",
					(const char*)roEHSServerParameters [ "certificate" ],
					(const char*)roEHSServerParameters [ "passphrase" ] );

		
		SecureSocket * poSecureSocket = 
			new SecureSocket ( roEHSServerParameters [ "certificate" ],
							   roEHSServerParameters [ "passphrase" ] );
		
		// HIGHLY EXPERIMENTAL
		// scary shit
		EHS_TRACE ( "Thinking about loading callback - '%s'\n", 
					roEHSServerParameters [ "passphrasecallback" ].
					GetCharString ( ) );
		

		if ( roEHSServerParameters [ "passphrasecallback" ] != "" &&
			 dlsym ( RTLD_DEFAULT, 
					 roEHSServerParameters [ "passphrasecallback" ] ) == 
			 NULL ) {

			EHS_TRACE ( "Couldn't load symbol for '%s' -- make sure you extern \"C\" the function\n",
						roEHSServerParameters [ "passphrasecallback" ].
						GetCharString ( ) );
		}



		EHS_TRACE ( "done thinking about loading callback\n" );



		
		poSecureSocket->SetPassphraseCallback (  (int ( * ) ( char *, int, int, void * ))
												 dlsym ( RTLD_DEFAULT,
														 roEHSServerParameters [ "passphrasecallback" ] ) );
		// END EXPERIMENTAL
		
		m_poNetworkAbstraction = poSecureSocket;
#else // COMPILE_WITH_SSL
		fprintf ( stderr, "EHS not compiled with SSL support.  Cannot create HTTPS server.  Aborting\n" );
		exit ( 1 );
#endif // COMPILE_WITH_SSL



	}
	

	// initialize the socket
	assert ( m_poNetworkAbstraction != NULL );
	int nResult = m_poNetworkAbstraction->Init ( roEHSServerParameters [ "bindip" ], roEHSServerParameters [ "port" ] ); // initialize socket stuff

	

	
	if ( nResult != NetworkAbstraction::INITSOCKET_SUCCESS ) {

		EHS_TRACE ( "Error: Failed to initialize sockets\n" );

		return;
	}


	if ( roEHSServerParameters [ "mode" ] == "threadpool" ) {

		// need to set this here because the thread will check this to make
		//   sure it's supposed to keep running
		m_nServerRunningStatus = SERVERRUNNING_THREADPOOL;

		// create a pthread 
		int nResult = -1;

		EHS_TRACE ( "Starting %d threads\n", roEHSServerParameters [ "threadcount" ].GetInt ( ) );


		int nThreadsToStart = roEHSServerParameters [ "threadcount" ].GetInt ( );
		if ( nThreadsToStart == 0 ) {
			nThreadsToStart = 1;
		}

		for ( int i = 0; i < nThreadsToStart; i++ ) {

			EHS_TRACE ( "creating thread with %x, NULL, %x, %x\n",
					  &m_nAcceptThreadId,
					  EHSServer::PthreadHandleData_ThreadedStub,
					  (void *) this );

			// create new thread and detach so we don't have to join on it
			nResult = 
				pthread_create ( &m_nAcceptThreadId,
								 NULL,
								 EHSServer::PthreadHandleData_ThreadedStub,
								 (void *) this );
			pthread_detach ( m_nAcceptThreadId );

		}

		if ( nResult != 0 ) {
			m_nServerRunningStatus = SERVERRUNNING_NOTRUNNING;
		}


	} else if ( roEHSServerParameters [ "mode" ] == "onethreadperrequest" ) {

		m_nServerRunningStatus = SERVERRUNNING_ONETHREADPERREQUEST;

		// spawn off one thread just to deal with basic stuff
		nResult = pthread_create ( &m_nAcceptThreadId,
								   NULL,
								   EHSServer::PthreadHandleData_ThreadedStub,
								   (void *) this );
		pthread_detach ( m_nAcceptThreadId );
	
		// check to make sure the thread was created properly
		if ( nResult != 0 ) {
			m_nServerRunningStatus = SERVERRUNNING_NOTRUNNING;
		}

	} else if ( roEHSServerParameters [ "mode" ] == "singlethreaded" ) {

		// we're single threaded
		m_nServerRunningStatus = SERVERRUNNING_SINGLETHREADED;

	} else {

		EHS_TRACE ( "INVALID 'mode' SPECIFIED.\ntMust be 'singlethreaded', 'threadpool', or 'onethreadperrequest'\n" );

		assert ( 0 );
	}


	if ( m_nServerRunningStatus == SERVERRUNNING_THREADPOOL ) {
		EHS_TRACE ( "Info: EHS Server running in dedicated thread mode with '%s' threads\n",
				  roEHSServerParameters [ "threadcount" ] == "" ? 
				  roEHSServerParameters [ "threadcount" ].GetCharString ( ) : "1" );
	} else if ( m_nServerRunningStatus == SERVERRUNNING_ONETHREADPERREQUEST ) {
		EHS_TRACE ( "Info: EHS Server running with one thread per request\n" );
	} else if ( m_nServerRunningStatus == SERVERRUNNING_SINGLETHREADED ) {
		EHS_TRACE ( "Info: EHS Server running in non-dedicated thread mode\n" );
	} else {
		EHS_TRACE ( "Error: EHS Server not running.  Server initialization failed\n" );
	}

	return;


}
예제 #17
0
/* The main() function for setting up and running the tests.
 * Returns a CUE_SUCCESS on successful running, another
 * CUnit error code on failure.
 */
int main(int argc, char *argv[]) {
    int xml = 0;
    int con = 0;
    CU_pFailureRecord fr;
    int i;

    if (argc >= 2 && !strcmp(argv[1], "-xml")) {
        xml = 1;
    } else if (argc >= 2 && !strcmp(argv[1], "-con")) {
        con = 1;
    }
#ifdef HAVE_CUNIT
    int rv;

#ifndef WIN32
    struct sigaction sig_act;
    /*
     * Indicate that the broken pipe signal during writes should be
     * ignored
     */
    memset(&sig_act, 0, sizeof(struct sigaction));
    sig_act.sa_handler = SIG_IGN;
    sigemptyset(&sig_act.sa_mask);
    if (sigaction(SIGPIPE, &sig_act, NULL) == -1) {
        printf("\nCannot set ignore action for SIGPIPE\n");
    }
#endif 

    est_apps_startup();

    /*
     * Install thread locking mechanism for OpenSSL
     */
    mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
    if (!mutex_buf) {
        printf("Cannot allocate mutexes");
        exit(1);
    }
    for (i = 0; i < CRYPTO_num_locks(); i++)
    MUTEX_SETUP(mutex_buf[i]);
    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);

    /* initialize the CUnit test registry */
    if (CUE_SUCCESS != CU_initialize_registry()) {
        return CU_get_error();
    }
#ifdef ENABLE_ALL_SUITES
    rv = us748_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US748 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us893_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US893 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us894_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US894 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us895_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US895 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us896_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US896 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us897_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US897 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us898_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US898 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us899_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US899 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us900_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US900 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us901_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US901 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us902_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US902 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us903_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US903 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1005_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1005 (%d)", rv);
        exit(1);
    }
#endif
#if (DISABLE_SUITE != 0)
    rv = us1060_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1060 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1060c_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1060c (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES 
    rv = us1159_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1159 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1190_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1190 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1864_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1864 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1883_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1883 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us1884_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US1884 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us2174_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US2174 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us3496_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US3496 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us3512_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US3512 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us3612_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US3612 (%d)", rv);
        exit(1);
    }
#endif
#ifdef ENABLE_ALL_SUITES
    rv = us4020_add_suite();
    if (rv != CUE_SUCCESS) {
        printf("\nFailed to add test suite for US4020 (%d)", rv);
        exit(1);
    }
#endif

    if (xml) {
        /* Run all test using automated interface, which
         * generates XML output */
        CU_list_tests_to_file();
        CU_automated_run_tests();
    }
    else if (con) {
        CU_console_run_tests();
    }
    else {
        /* Run all tests using the CUnit Basic interface,
         * which generates text output */
        CU_basic_set_mode(CU_BRM_VERBOSE);
        CU_basic_run_tests();
        fr = CU_get_failure_list();
        if (fr) {
            printf("\n\nHere is a summary of the failed test cases:\n");
            CU_basic_show_failures(fr);
        }
    }

    /*
     * Tear down the mutexes used by OpenSSL
     */
    if (!mutex_buf)
    return 0;
    CRYPTO_set_id_callback(NULL);
    CRYPTO_set_locking_callback(NULL);
    for (i = 0; i < CRYPTO_num_locks(); i++)
    MUTEX_CLEANUP(mutex_buf[i]);
    free(mutex_buf);
    mutex_buf = NULL;

    CU_cleanup_registry();
    est_apps_shutdown();

    return CU_get_error();
#else
    printf("\nlibcunit not installed, unit test are not enabled\n");
#endif
}
예제 #18
0
/*
 * This is the main entry point into the example EST server.
 * This routine parses the command line options, reads in the
 * cert chains, creates an EST context, initializes the HTTP
 * layer (mongoose), and starts a simple TCP server to accept
 * incoming EST requests.
 */
int main (int argc, char **argv)
{
    char c;
    int i;

    X509 *x;
    EVP_PKEY * priv_key;
    BIO *certin;
    DH *dh;
    EST_ERROR rv;
    int sleep_delay = 0;
    int retry_period = 300;
    char vfile[255];
    int option_index = 0;
    pem_password_cb *priv_key_cb = NULL;

    static struct option long_options[] = {
        {"srp", 1, NULL, 0},
        {"enforce-csr", 0, NULL, 0},
        {"token", 1, 0, 0},
        {"keypass", 1, 0, 0},
        {"keypass_stdin", 1, 0, 0 },
        {"keypass_arg", 1, 0, 0 },
        {NULL, 0, NULL, 0}
    };

#ifdef WIN32
    InitializeCriticalSection(&enrollment_critical_section);
#endif

    /* Show usage if -h or --help options are specified */
    if ((argc == 1)
            || (argc == 2
                    && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")))) {
        show_usage_and_exit();
    }

    while ((c = getopt_long(argc, argv, "?fhbwnovr:c:k:m:p:d:lt6", long_options,
        &option_index)) != -1) {
        switch (c) {
        case 0:
#if 0
            printf("option %s", long_options[option_index].name);
            if (optarg) {
                printf(" with arg %s", optarg);
            }
            printf("\n");
#endif
            if (!strncmp(long_options[option_index].name, "srp",
                strlen("srp"))) {
                srp = 1;
                strncpy(vfile, optarg, 255);
            }
            if (!strncmp(long_options[option_index].name, "enforce-csr",
                strlen("enforce-csr"))) {
                enforce_csr = 1;
            }
            if (!strncmp(long_options[option_index].name, "token",
                strlen("token"))) {
                http_token_auth = 1;
                memset(valid_token_value, 0, MAX_AUTH_TOKEN_LEN + 1);
                strncpy(&(valid_token_value[0]), optarg, MAX_AUTH_TOKEN_LEN);
            }
            if (!strncmp(long_options[option_index].name,"keypass_stdin", strlen("keypass_stdin"))) {
                priv_key_cb = PEM_def_callback;
            }
            if (!strncmp(long_options[option_index].name,"keypass_arg", strlen("keypass_arg"))) {
                strncpy(priv_key_pwd, optarg, MAX_PWD_LEN);
                priv_key_cb = string_password_cb;
            }
            break;
        case 'm':
            manual_enroll = 1;
            retry_period = atoi(optarg);
            break;
        case 'h':
            http_digest_auth = 1;
            break;
        case 'b':
            http_basic_auth = 1;
            break;
        case 'w':
            write_csr = 1;
            break;
        case 'n':
            http_auth_disable = 1;
            break;
        case 'o':
            disable_forced_http_auth = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'l':
            crl = 1;
            break;
        case 't':
            pop = 1;
            break;
        case '6':
            v6 = 1;
            break;
#ifndef DISABLE_PTHREADS
        case 'd':
            sleep_delay = atoi(optarg);
            break;
#endif
        case 'p':
            tcp_port = atoi(optarg);
            break;
        case 'c':
            strncpy(certfile, optarg, EST_MAX_FILE_LEN);
            break;
        case 'k':
            strncpy(keyfile, optarg, EST_MAX_FILE_LEN);
            break;
        case 'r':
            if (strnlen(optarg, MAX_REALM_LEN+1) > MAX_REALM_LEN) {
                printf("\nRealm value is too large.  Max is 32 characters\n");
                exit(1);
            }
            
            strncpy(realm, optarg, MAX_REALM_LEN);
            break;
        case 'f':
            /* turn FIPS on if user requested it
             * and exit if failure.
             */
            set_fips_return = FIPS_mode_set(1);
            if (set_fips_return != 1) {
                set_fips_error = ERR_get_error();
                printf("\nERROR WHILE SETTING FIPS MODE ON exiting ....\n");
                exit(1);
            } else {
                printf("\nRunning EST Sample Server with FIPS MODE = ON !\n");
            }
            ;
            break;
        default:
            show_usage_and_exit();
            break;
        }
    }
    argc -= optind;
    argv += optind;

    if (verbose) {
        print_version(stdout);
    }

    if (getenv("EST_CSR_ATTR")) {
        printf("\nUsing CSR Attributes: %s", getenv("EST_CSR_ATTR"));
    }

    if (!getenv("EST_CACERTS_RESP")) {
        printf("\nEST_CACERTS_RESP file not set, set this env variable to resolve");
        exit(1);
    }
    if (!getenv("EST_TRUSTED_CERTS")) {
        printf("\nEST_TRUSTED_CERTS file not set, set this env variable to resolve");
        exit(1);
    }

    /*
     * Read in the CA certificates
     */
    cacerts_len = read_binary_file(getenv("EST_CACERTS_RESP"), &cacerts_raw);
    if (cacerts_len <= 0) {
        printf("\nEST_CACERTS_RESP file could not be read\n");
        exit(1);
    }
    /*
     * Read in the trusted CA certificates for the local TLS context
     */
    if (getenv("EST_TRUSTED_CERTS")) {
        trustcerts_len = read_binary_file(getenv("EST_TRUSTED_CERTS"),
            &trustcerts);
        if (trustcerts_len <= 0) {
            printf("\nEST_TRUSTED_CERTS file could not be read\n");
            exit(1);
        }
    }

    est_apps_startup();

    /*
     * Read in the local server certificate
     */
    certin = BIO_new(BIO_s_file_internal());
    if (BIO_read_filename(certin, certfile) <= 0) {
        printf("\nUnable to read server certificate file %s\n", certfile);
        exit(1);
    }
    /*
     * This reads the file, which is expected to be PEM encoded.  If you're using
     * DER encoded certs, you would invoke d2i_X509_bio() instead.
     */
    x = PEM_read_bio_X509(certin, NULL, NULL, NULL);
    if (x == NULL) {
        printf("\nError while reading PEM encoded server certificate file %s\n",
            certfile);
        exit(1);
    }
    BIO_free(certin);

    /*
     * Read in the server's private key
     */

    priv_key = read_private_key(keyfile, priv_key_cb);
    if (priv_key == NULL) {
        printf("\nError while reading PEM encoded server private key file %s\n",
            keyfile);
        ERR_print_errors_fp(stderr);
        exit(1);
    }

    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
    if (!bio_err) {
        printf("\nBIO not working\n");
        exit(1);
    }

    if (verbose) {
        est_init_logger(EST_LOG_LVL_INFO, NULL);
        est_enable_backtrace(1);
    } else {
        est_init_logger(EST_LOG_LVL_ERR, NULL);
    }
    ectx = est_server_init(trustcerts, trustcerts_len, cacerts_raw, cacerts_len,
        EST_CERT_FORMAT_PEM, realm, x, priv_key);
    if (!ectx) {
        printf("\nUnable to initialize EST context.  Aborting!!!\n");
        exit(1);
    }
    est_set_ex_data(ectx, &test_app_data);

    if (enforce_csr) {
        est_server_enforce_csrattr(ectx);
    }

    /*
     * Change the retry-after period.  This is not
     * necessary, it's only shown here as an example.
     */
    if (verbose)
        printf("\nRetry period being set to: %d \n", retry_period);
    est_server_set_retry_period(ectx, retry_period);

    if (crl) {
        est_enable_crl(ectx);
    }
    if (!pop) {
        if (verbose)
            printf("\nDisabling PoP check");
        est_server_disable_pop(ectx);
    }

    if (srp) {
        srp_db = SRP_VBASE_new(NULL);
        if (!srp_db) {
            printf("\nUnable allocate SRP verifier database.  Aborting!!!\n");
            exit(1);
        }
        if (SRP_VBASE_init(srp_db, vfile) != SRP_NO_ERROR) {
            printf("\nUnable initialize SRP verifier database.  Aborting!!!\n");
            exit(1);
        }

        if (est_server_enable_srp(ectx, &process_ssl_srp_auth)) {
            printf("\nUnable to enable SRP.  Aborting!!!\n");
            exit(1);
        }
    }

    if (est_set_ca_enroll_cb(ectx, &process_pkcs10_enrollment)) {
        printf(
            "\nUnable to set EST pkcs10 enrollment callback.  Aborting!!!\n");
        exit(1);
    }
    /*
     * We use the same handler for re-enrollment.  Our little toy
     * CA doesn't do anything special for re-enrollment.  A real
     * CA would need to implement the requirements in section
     * 4.2 of the EST draft.
     */
    if (est_set_ca_reenroll_cb(ectx, &process_pkcs10_enrollment)) {
        printf(
            "\nUnable to set EST pkcs10 enrollment callback.  Aborting!!!\n");
        exit(1);
    }
    if (est_set_csr_cb(ectx, &process_csrattrs_request)) {
        printf("\nUnable to set EST CSR Attributes callback.  Aborting!!!\n");
        exit(1);
    }
    if (!http_auth_disable) {
        if (est_set_http_auth_cb(ectx, &process_http_auth)) {
            printf("\nUnable to set EST HTTP AUTH callback.  Aborting!!!\n");
            exit(1);
        }
    }
    if (disable_forced_http_auth) {
        if (verbose)
            printf(
                "\nDisabling HTTP authentication when TLS client auth succeeds\n");
        if (est_set_http_auth_required(ectx, HTTP_AUTH_NOT_REQUIRED)) {
            printf("\nUnable to disable required HTTP auth.  Aborting!!!\n");
            exit(1);
        }
    }

    if (http_digest_auth) {
        
        MD5_CTX c;
        int len;
        static unsigned char ha1_input_buf[32*3+2];
        unsigned char md[17];
        int i;
        
        rv = est_server_set_auth_mode(ectx, AUTH_DIGEST);
        if (rv != EST_ERR_NONE) {
            printf(
                "\nUnable to enable HTTP digest authentication.  Aborting!!!\n");
            exit(1);
        }

        /*
         * Cache away the realm value and build the HA1
         */
        strncpy(digest_user[1], realm, MAX_REALM_LEN);

        len = sprintf((char *)ha1_input_buf, "%s:%s:%s", "estuser", realm, "estpwd");
        MD5_Init(&c);
        MD5_Update(&c, ha1_input_buf, len);
        MD5_Final((unsigned char *)md, &c);

        printf("\nDigest HA1 value = ");
        memset(digest_user[2], 0, 32);
        for(i = 0; i < 16; i++){
            
            sprintf(&(digest_user[2][i*2]),"%.2x", (unsigned char) md[i]);
            printf("%c%c", digest_user[2][i*2], digest_user[2][i*2+1]);
        }
        printf("\n");
    }

    if (http_basic_auth) {
        rv = est_server_set_auth_mode(ectx, AUTH_BASIC);
        if (rv != EST_ERR_NONE) {
            printf(
                "\nUnable to enable HTTP basic authentication.  Aborting!!!\n");
            exit(1);
        }
    }

    if (http_token_auth) {
        rv = est_server_set_auth_mode(ectx, AUTH_TOKEN);
        if (rv != EST_ERR_NONE) {
            printf(
                "\nUnable to enable HTTP token authentication.  Aborting!!!\n");
            exit(1);
        }
    }

    /*
     * Set DH parameters for TLS
     */
    dh = get_dh1024dsa();
    if (dh) {
        est_server_set_dh_parms(ectx, dh);
    }
    DH_free(dh);

    /*
     * Install thread locking mechanism for OpenSSL
     */
    mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
    if (!mutex_buf) {
        printf("Cannot allocate mutexes");
        exit(1);
    }
    for (i = 0; i < CRYPTO_num_locks(); i++)
        MUTEX_SETUP(mutex_buf[i]);
    CRYPTO_set_id_callback(id_function);
    CRYPTO_set_locking_callback(locking_function);

    printf("\nLaunching EST server...\n");

    rv = est_server_start(ectx);
    if (rv != EST_ERR_NONE) {
        printf("\nFailed to init mg (rv=%d)\n", rv);
        exit(1);
    }

    /*
     * Start the simple server, which opens a TCP
     * socket, waits for incoming connections, and
     * invokes the EST handler for each connection.
     */
    start_simple_server(ectx, tcp_port, sleep_delay, v6);

    cleanup();
    EVP_PKEY_free(priv_key);
    X509_free(x);
    return 0;
}
예제 #19
0
void *File_Process(void *arg)
{
	pthread_detach(pthread_self());

    // add by andy for more info
    THREAD_INFO *tinfo = (THREAD_INFO *)arg;

    //mqid = (int)arg;
    mqid = tinfo->mqid;
    struct threadpool *pool = tinfo->pool;

	PRINTF(LEVEL_INFORM,"thread mqid = %d \n",mqid);
	//fprintf(stderr,"--->test = %d \n",test);

    //init thread share info
    MUTEX_SETUP(share_info.lock);
    share_info.dir1 = strdup(tinfo->dir1);
    share_info.dir2 = strdup(tinfo->dir2);
    share_info.app_name = strdup(tinfo->app_name);
    share_info.move_file = tinfo->move_file;
    share_info.m_addr = tinfo->m_addr;

    share_info.m_sock = Socket(AF_INET,SOCK_DGRAM,0);
	int fd;
	FILE *fp;
	struct msgbuf *buff = malloc(MAXMSG);
	int n , ret;

	mode_t fdmode = (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
	int wlen;

	long long pack_total;
	long long pack_saved; 
	long long pack_move; 


	char *msg = NULL;

	//char save_path[512] ={0};
	//add by andy ,fix bug tcp_echo err ,2014-12-12
	char save_path[1024] ={0};

	/**UDP 数据包结构**/
	char protocol;

	long long file_size;
	int file_name_length;
	char *file_name;
	int pack_length;
	char *pack;

again:	
	pack_saved = 0;
	pack_move = 1;
	pack_total = 10;

	//这句可能是多余的	
	memset(buff,0,MAXMSG);	


	while(1)
	{	
		if((n = msgrcv(mqid,buff,MAXMSG,pack_move,IPC_NOWAIT)) < 0)
		//if((n = msgrcv(mqid,buff,MAXMSG,pack_move,0)) < 0)
		{
			n = msgrcv(mqid,buff,MAXMSG,0,0);
			if(n < 0)
			{
				//PRINTF(LEVEL_ERROR,"thread msgrcv error :%s\n",strerror(errno));
				//WriteSysLog(LOG_PATH,log);
				goto err_end;
				continue;
			}
			pack_move = buff->mtype;
		}

		pack_move ++;

		msg = buff->mtext;

		if((pack_saved == 0)||(pack_move == 2))
		{
			if((pack_move == 2)&&(pack_saved !=0))
			{
				//PRINTF(LEVEL_ERROR,"A file is incomplete because client stop transmite by accident\n");
				// write log

				pack_saved = 0;
				if(fp != NULL)
				{
					fclose(fp);
					fp = NULL;
				}
			}

			memcpy(&file_size,msg+10,8);
			pack_total = file_size/1024;
			if(file_size%1024 != 0)
				pack_total+=1;

			memcpy(&file_name_length,msg+18,4);
			file_name = (char *)malloc(file_name_length+1);
			memcpy(file_name,msg+22,file_name_length);
			*(file_name+file_name_length) = '\0';
            // usr dir install of true path ,andy,2015-03-07
            //sprintf(save_path,RUN_PATH);
            //strcat(save_path,file_name);
            sprintf(save_path,"%s/%s/",tinfo->dir1,tinfo->app_name);
            strcat(save_path,basename(file_name));

            //memcpy(&pack_length,msg+22+file_name_length,4);

			pack = msg +22 +file_name_length +4;

			ret = CreateDir(save_path);
			if(ret < 0)
			{
				;
			}
			fp = fopen(save_path,"w+");
			if(fp == NULL)
			{
				PRINTF(LEVEL_ERROR,"Open %s error:%s",file_name,strerror(errno)); 
 				goto err_end;
			}
		}


        memcpy(&pack_length,msg+22+file_name_length,4);

        int n = fwrite(pack,sizeof(char),pack_length,fp);
		if(n != pack_length)
		{
			PRINTF(LEVEL_ERROR,"Write %s error :%s\n",file_name,strerror(errno));
			goto err_end;
		}

		pack_saved++;				/**写文件成功,记录**/

		//检查文件大小
		if(pack_total == pack_saved )
		{
            //PRINTF(LEVEL_ERROR,"Last Pack Size :%d\n",pack_length);
			fclose(fp);
			fp = NULL;

            threadpool_add_job(pool,Recv_Finish,save_path);
            //tcp_echo(save_path,strlen(save_path),t_sockfd);
            free(file_name);

			goto again;
		}
		else if(pack_total == (pack_move -1))
		{
			//PRINTF(LEVEL_ERROR,"## lost package ## File %s is incomplete\n",file_name);

			fclose(fp);

			fp = NULL;
			//remove(save_path);
            //tcp_echo(save_path,strlen(save_path),t_sockfd);
			free(file_name);
			goto again;
		}


	}

err_end:	
	free(buff);
	free(file_name);
	exit(-1);
	return NULL;
}