int main(int argc, char *argv[])
{
	int count = argc;
	const char *file;
    file = _PATH_UTMP;
	list = (char**)malloc(SIZE*sizeof(char*));
	for(i = 0;i<SIZE;i++)
	{
		list[i] = (char*)malloc(SIZE*sizeof(char));
	}
	pid_list = (char**)malloc(SIZE*sizeof(char*));
	for(i = 0;i<SIZE;i++)
	{
		pid_list[i] = (char*)malloc(SIZE*sizeof(char));
	}
	buff = (char*)malloc(SIZE*sizeof(char));
    name = (char*)malloc(SIZE*sizeof(char));
    temp = (char*)malloc(SIZE*sizeof(char));
    ptrmsg_copy = (char*)malloc(SIZE*sizeof(char));
    sender_pid = (char*)malloc(SIZE*sizeof(char));
    bzero(sender_pid,SIZE);
	// now set up the ipc for communication
	if ((msgid = msgget(msgkey, msgflg )) < 0) 
	{
        perror("msgget");
        exit(EXIT_FAILURE);
    }
    if ((sem1 = semget(sem1key,1, msgflg )) < 0) 
    {
        perror("semget");
        exit(EXIT_FAILURE);
    }
    if ((semctl(sem1, 0, SETVAL, 1)) < 0) 
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }
    if ((sem2 = semget(sem2key,1, msgflg )) < 0) 
    {
        perror("semget");
        exit(EXIT_FAILURE);
    }
    if ((semctl(sem2, 0, SETVAL, 0)) < 0) 
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }
    if ((shm1 = shmget(shm1key,500, msgflg )) < 0) 
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }
    if ((shm2 = shmget(shm2key,5000, msgflg )) < 0) 
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }
    ptrpid=shmat(shm1,NULL,0);
    ptrmsg=shmat(shm2,NULL,0);
    bzero(ptrpid,500);
    bzero(ptrmsg,5000);
    printf("--- Initialization complete\n");
    // done 
    // then read all names 
    j = 0;
	while(argc>1)
	{
		strcpy(list[j],argv[--argc]);
		j++;
	}
	listsize = j;

	// open a file in excl to ensure that only one server is running
	fp = fopen("ser.txt","wx");
	if(fp == NULL)
	{
		perror("server already running");
		exit(EXIT_FAILURE);
	}
	bzero(buff,SIZE);
	sprintf(buff,"%d",getpid());
	fwrite(buff,SIZE,1,fp);

	// here comes the UTMP part
	// we need to open the file in the linux for the various terminals opened 
	if ((fputmp = fopen(file, "r")) == NULL)
    {
    	err(1, "%s", file);
    }
    while (fread(&u, sizeof(u), 1, fputmp) == 1)
	{
		if (u.ut_name != NULL) 
		{
			if(getpwnam(u.ut_name) != NULL) // means the file is not arbit 
			{
				// printf("%s\n",u.ut_line );
				for(i = 0;i<listsize;i++)
				{
					if(((strcmp(u.ut_name,list[i])) == 0) && (count > 1) && ((strcmp(u.ut_line,":0")) != 0)) 
						// means it points to real user who should be in conference
					{
						// so we need to send the commencement notification to the corresponding user
						printf("--Sending commence notification to %s\n",u.ut_line );
						sprintf(name, "./commence > /dev/%s", u.ut_line);
						system(name);
						count--;
						break;
					}
				}
			}
		}
	}
	// from here the infinite loop begins to broadcast the message to all 
	// it waits until the value of the sem2 = 2 which indicates client has written the message
	while(1)
	{
		wait_for(sem2,2);
		// now read message
		strcpy(ptrmsg_copy,ptrmsg);
		printf("%s\n",ptrmsg_copy );
		setvalue(sem2,0);
		// case 1 if the message is '.' then we need to simply ignore it
		if((strcmp(ptrmsg_copy,".")) == 0)
		{

		} 
		// case 2 if the message is '*' then we need to terminate server as there is no client 
		else if((strcmp(ptrmsg_copy,"*")) == 0)
		{
			terminate();
		}
		// case 3 now we need to broadcast the message to all the clients available except 
		// the one who send the message
		else
		{
			down(sem1);
			read_pid();
			up(sem1);
			strcpy(msg_send.mtext,ptrmsg_copy);
			int l = strlen(ptrmsg_copy)+1;
			k = 0,j = 0;
			while(ptrmsg_copy[j] != '/')
			{
				j++;
			}
			j++;
			while(ptrmsg_copy[j] != ':')
			{
				sender_pid[k] = ptrmsg_copy[j];
				j++;
				k++;
			}
			sender_pid[k] = '\0';
			for(i = 0;i<pid_list_size;i++)
			{
				if((strcmp(pid_list[i],sender_pid)) != 0)
				{
					// then send message as it is different user 
					sscanf(pid_list[i],"%d",&send_pid);
					printf("%d  %d  %d\n%s\n", msgid,l,send_pid,msg_send.mtext);
					msg_send.mtype = (long)send_pid;
					if(msgsnd(msgid,&msg_send,l,0)==-1) 		//User to Kernel memory space 
					{
						printf("error in msg_send\n");
						exit(1);
					}
					else
					{
						printf("sending message to %d\n",send_pid );
					}
				}
			}
		}
	}
	// deleting all the ipc
	
	return 0;
}
Esempio n. 2
0
static LinphoneCoreManager* configure_lcm(void) {
	LinphoneCoreManager *mgr=linphone_core_manager_new( "multi_account_rc");
	stats *counters=&mgr->stat;
	CU_ASSERT_TRUE(wait_for(mgr->lc,mgr->lc,&counters->number_of_LinphoneRegistrationOk,ms_list_size(linphone_core_get_proxy_config_list(mgr->lc))));
	return mgr;
}
Esempio n. 3
0
void MainFrame::InstallPkg(wxCommandEvent& WXUNUSED(event))
{
	const bool was_running = Emu.Pause();

	wxFileDialog ctrl(this, L"Select PKG", wxEmptyString, wxEmptyString, "PKG files (*.pkg)|*.pkg|All files (*.*)|*.*", wxFD_OPEN | wxFD_FILE_MUST_EXIST);
	
	if (ctrl.ShowModal() == wxID_CANCEL)
	{
		if (was_running) Emu.Resume();
		return;
	}

	Emu.Stop();

	Emu.GetVFS().Init("/");
	std::string local_path;
	Emu.GetVFS().GetDevice("/dev_hdd0/game/", local_path);

	// Open PKG file
	fs::file pkg_f(ctrl.GetPath().ToStdString());

	// Open file mapping (test)
	fs::file_read_map pkg_ptr(pkg_f);

	if (!pkg_f || !pkg_ptr)
	{
		LOG_ERROR(LOADER, "PKG: Failed to open %s", ctrl.GetPath().ToStdString());
		return;
	}

	// Append title ID to the path
	local_path += '/';
	local_path.append(pkg_ptr + 55, 9);

	if (!fs::create_dir(local_path))
	{
		if (fs::is_dir(local_path))
		{
			if (wxMessageDialog(this, "Another installation found. Do you want to overwrite it?", "PKG Decrypter / Installer", wxYES_NO | wxCENTRE).ShowModal() != wxID_YES)
			{
				LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path);
				return;
			}
		}
		else
		{
			LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path);
			return;
		}
	}

	wxProgressDialog pdlg("PKG Decrypter / Installer", "Please wait, unpacking...", 1000, this, wxPD_AUTO_HIDE | wxPD_APP_MODAL);

	volatile f64 progress = 0.0;

	// Run PKG unpacking asynchronously
	auto result = std::async(std::launch::async, WRAP_EXPR(pkg_install(pkg_f, local_path + '/', progress)));

	// Wait for the completion
	while (result.wait_for(15ms) != std::future_status::ready)
	{
		// Update progress window
		pdlg.Update(progress * pdlg.GetRange());

		// Update main frame
		Update();
		wxGetApp().ProcessPendingEvents();
	}

	pdlg.Close();

	if (result.get())
	{
		LOG_SUCCESS(LOADER, "PKG: Package successfully installed in %s", local_path);

		// Refresh game list
		m_game_viewer->Refresh();
	}
}
Esempio n. 4
0
static void presence_information(void) {
	const char *bike_description = "Riding my bike";
	const char *vacation_note = "I'm on vacation until July 4th";
	const char *vacation_lang = "en";
	const char *contact = "sip:[email protected]";
	LinphoneCoreManager *marie = presence_linphone_core_manager_new("marie");
	LinphoneCoreManager *pauline = presence_linphone_core_manager_new("pauline");
	LinphonePresenceModel *presence;
	LinphonePresenceActivity *activity = NULL;
	LinphonePresenceNote *note = NULL;
	const char *description = NULL;
	const char *note_content = NULL;
	char *contact2;
	time_t current_timestamp, presence_timestamp;

	BC_ASSERT_TRUE(subscribe_to_callee_presence(marie, pauline));

	/* Presence activity without description. */
	presence = linphone_presence_model_new_with_activity(LinphonePresenceActivityDinner, NULL);
	linphone_core_set_presence_model(pauline->lc, presence);
	wait_for(marie->lc,pauline->lc,&marie->stat.number_of_LinphonePresenceActivityDinner,1);
	BC_ASSERT_EQUAL(marie->stat.number_of_LinphonePresenceActivityDinner, 1, int, "%d");
	activity = linphone_presence_model_get_activity(marie->stat.last_received_presence);
	BC_ASSERT_PTR_NOT_NULL(activity);
	BC_ASSERT_EQUAL(linphone_presence_activity_get_type(activity), LinphonePresenceActivityDinner, int, "%d");
	description = linphone_presence_activity_get_description(activity);
	BC_ASSERT_PTR_NULL(description);

	/* Presence activity with description. */
	presence = linphone_presence_model_new_with_activity(LinphonePresenceActivitySteering, bike_description);
	linphone_core_set_presence_model(pauline->lc, presence);
	wait_for(marie->lc,pauline->lc,&marie->stat.number_of_LinphonePresenceActivitySteering,1);
	BC_ASSERT_EQUAL(marie->stat.number_of_LinphonePresenceActivitySteering, 1, int, "%d");
	activity = linphone_presence_model_get_activity(marie->stat.last_received_presence);
	BC_ASSERT_PTR_NOT_NULL(activity);
	BC_ASSERT_EQUAL(linphone_presence_activity_get_type(activity), LinphonePresenceActivitySteering, int, "%d");
	description = linphone_presence_activity_get_description(activity);
	BC_ASSERT_PTR_NOT_NULL(description);
	if (description != NULL) BC_ASSERT_STRING_EQUAL(description, bike_description);

	/* Presence activity with description and note. */
	presence = linphone_presence_model_new_with_activity_and_note(LinphonePresenceActivityVacation, NULL, vacation_note, vacation_lang);
	linphone_core_set_presence_model(pauline->lc, presence);
	wait_for(marie->lc,pauline->lc,&marie->stat.number_of_LinphonePresenceActivityVacation,1);
	BC_ASSERT_EQUAL(marie->stat.number_of_LinphonePresenceActivityVacation, 1, int, "%d");
	activity = linphone_presence_model_get_activity(marie->stat.last_received_presence);
	BC_ASSERT_PTR_NOT_NULL(activity);
	BC_ASSERT_EQUAL(linphone_presence_activity_get_type(activity), LinphonePresenceActivityVacation, int, "%d");
	description = linphone_presence_activity_get_description(activity);
	BC_ASSERT_PTR_NULL(description);
	note = linphone_presence_model_get_note(marie->stat.last_received_presence, NULL);
	BC_ASSERT_PTR_NOT_NULL(note);
	if (note != NULL) {
		note_content = linphone_presence_note_get_content(note);
		BC_ASSERT_PTR_NOT_NULL(note_content);
		if (note_content != NULL) {
			BC_ASSERT_STRING_EQUAL(note_content, vacation_note);
		}
	}

	/* Presence contact. */
	presence = linphone_presence_model_new_with_activity(LinphonePresenceActivityOnThePhone, NULL);
	linphone_presence_model_set_contact(presence, contact);
	linphone_core_set_presence_model(pauline->lc, presence);
	wait_for(marie->lc,pauline->lc,&marie->stat.number_of_LinphonePresenceActivityOnThePhone,1);
	BC_ASSERT_EQUAL(marie->stat.number_of_LinphonePresenceActivityOnThePhone, 1, int, "%d");
	contact2 = linphone_presence_model_get_contact(presence);
	BC_ASSERT_PTR_NOT_NULL(contact2);
	if (contact2 != NULL) {
		BC_ASSERT_STRING_EQUAL(contact, contact2);
		ms_free(contact2);
	}

	/* Presence timestamp. */
	current_timestamp = ms_time(NULL);
	presence = linphone_presence_model_new_with_activity(LinphonePresenceActivityShopping, NULL);
	linphone_core_set_presence_model(pauline->lc, presence);
	wait_for(marie->lc,pauline->lc,&marie->stat.number_of_LinphonePresenceActivityShopping,1);
	BC_ASSERT_EQUAL(marie->stat.number_of_LinphonePresenceActivityShopping, 1, int, "%d");
	presence_timestamp = linphone_presence_model_get_timestamp(presence);
	BC_ASSERT_GREATER((unsigned)presence_timestamp , (unsigned)current_timestamp, unsigned, "%u");

	linphone_core_manager_destroy(marie);
	linphone_core_manager_destroy(pauline);
}
Esempio n. 5
0
void mastermind_t::data::reconnect() {
	std::lock_guard<std::mutex> lock(m_reconnect_mutex);
	(void) lock;

	size_t end = m_next_remote;
	size_t index = m_next_remote;
	size_t size = m_remotes.size();

	do {
		auto &remote = m_remotes[index];
		try {
			COCAINE_LOG_INFO(m_logger,
					"libmastermind: reconnect: try to connect to locator %s:%d",
					remote.first.c_str(), static_cast<int>(remote.second));

			m_app.reset();
			m_service_manager = cocaine::framework::service_manager_t::create(
				cocaine::framework::service_manager_t::endpoint_t(remote.first, remote.second));

			COCAINE_LOG_INFO(m_logger,
					"libmastermind: reconnect: connected to locator, getting mastermind service");

			auto g = m_service_manager->get_service_async<cocaine::framework::app_service_t>(m_worker_name);
			g.wait_for(reconnect_timeout);
			if (g.ready() == false){
				COCAINE_LOG_ERROR(
					m_logger,
					"libmastermind: reconnect: cannot get mastermind-service in %d milliseconds from %s:%d",
					static_cast<int>(reconnect_timeout.count()),
					remote.first.c_str(), static_cast<int>(remote.second));
				g = decltype(g)();
				m_service_manager.reset();
				index = (index + 1) % size;
				continue;
			}
			m_app = g.get();

			COCAINE_LOG_INFO(m_logger,
					"libmastermind: reconnect: connected to mastermind via locator %s:%d"
					, remote.first.c_str(), static_cast<int>(remote.second));

			m_current_remote = remote;
			m_next_remote = (index + 1) % size;
			return;
		} catch (const cocaine::framework::service_error_t &ex) {
			COCAINE_LOG_ERROR(
				m_logger,
				"libmastermind: reconnect: service_error: %s; host: %s:%d",
				ex.what(), remote.first.c_str(), static_cast<int>(remote.second));
		} catch (const std::exception &ex) {
			COCAINE_LOG_ERROR(
				m_logger,
				"libmastermind: reconnect: %s; host: %s:%d",
				ex.what(), remote.first.c_str(), static_cast<int>(remote.second));
		}

		index = (index + 1) % size;
	} while (index != end);

	m_current_remote = remote_t();
	m_app.reset();
	m_service_manager.reset();
	COCAINE_LOG_ERROR(m_logger, "libmastermind: reconnect: cannot recconect to any host");
	throw std::runtime_error("reconnect error: cannot reconnect to any host");
}
Esempio n. 6
0
		json request( const std::string& url, bool retry )
		{
			// If we've already cached a response for this URL, skip the HTTP request
			if( m_cache.find( url ) != m_cache.end() )
			{
				json cached( 200 );
				cached.parse( m_cache[url] );
				return cached;
			}

			CURL* curl = curl_easy_init();

			if( curl == NULL )
			{
				throw dto_exception( dto_exception::REQUEST_EXCEPTION, "Failed to Send Request" );
			}

			CURLcode result;
			long status_code = 0;
			std::string read_buffer, header_buffer;

			curl_easy_setopt( curl, CURLOPT_URL, url.c_str() );
			curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1 );
			curl_easy_setopt( curl, CURLOPT_WRITEDATA, &read_buffer );
			curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, request_write_callback );
			curl_easy_setopt( curl, CURLOPT_HEADERFUNCTION, &request_header_callback ); // our static function
			curl_easy_setopt( curl, CURLOPT_WRITEHEADER, &header_buffer );

			result = curl_easy_perform( curl );

			curl_easy_getinfo( curl, CURLINFO_RESPONSE_CODE, &status_code );

			json response( status_code );

			if( result == CURLE_OK && status_code == 200 )
			{
				response.parse( read_buffer );

				// Add the response to the cache
				m_cache[url] = read_buffer;
			}
			else if( status_code == 400 )
			{
				throw dto_exception( dto_exception::REQUEST_EXCEPTION, "Bad Request" );
			}
			else if( status_code == 401 )
			{
				throw dto_exception( dto_exception::AUTHORIZATION_EXCEPTION, "Authorization Error - Check API Key" );
			}
			else if( status_code == 429 )
			{
				auto headers = parse_headers( header_buffer );

				if( headers.find( "Retry-After" ) != headers.end() )
				{
					try
					{
						std::chrono::seconds wait_for( std::stoi( headers["Retry-After"] ) );

						if( retry )
						{
							std::this_thread::sleep_for( wait_for );
							return request( url, retry );
						}
						throw dto_rate_exception( wait_for );
					}
					catch( std::invalid_argument e )
					{
						std::cerr << "Failed to parse Retry-After header, aborting request..." << std::endl;
					}				
				}
				
				throw dto_exception( dto_exception::RATE_LIMIT_EXCEPTION, "Rate Limit Exceeded" );
			}
			
			curl_easy_cleanup( curl );

			return response;
		}	
Esempio n. 7
0
	bool ready_all() const {
		for (auto it = futures.begin(); it != futures.end(); ++it)
			if (it->wait_for(std::chrono::seconds(0)) != std::future_status::ready)
				return false;
		return true;
	}
Esempio n. 8
0
static int g33_do_reset(struct drm_device *dev)
{
	pci_write_config_byte(dev->pdev, I915_GDRST, GRDOM_RESET_ENABLE);
	return wait_for(g4x_reset_complete(dev), 500);
}
static void refresher_base_with_body(endpoint_t* client
										,endpoint_t *server
										, const char* method
										, belle_sip_header_content_type_t* content_type
										,const char* body) {
	belle_sip_request_t* req;
	belle_sip_client_transaction_t* trans;
	belle_sip_header_route_t* destination_route;
	belle_sip_refresher_t* refresher;
	const char* identity = "sip:" USERNAME "@" SIPDOMAIN ;
	const char* domain="sip:" SIPDOMAIN ;
	belle_sip_header_contact_t* contact=belle_sip_header_contact_new();
	belle_sip_uri_t *dest_uri;
	uint64_t begin;
	uint64_t end;
	if (client->expire_in_contact) belle_sip_header_contact_set_expires(contact,1);


	dest_uri=(belle_sip_uri_t*)belle_sip_object_clone((belle_sip_object_t*)belle_sip_listening_point_get_uri(server->lp));
	if (client->connection_family==AF_INET6)
		belle_sip_uri_set_host(dest_uri,"::1");
	else
		belle_sip_uri_set_host(dest_uri,"127.0.0.1");
	destination_route=belle_sip_header_route_create(belle_sip_header_address_create(NULL,dest_uri));


	req=belle_sip_request_create(
		                    belle_sip_uri_parse(domain),
		                    method,
		                    belle_sip_provider_create_call_id(client->provider),
		                    belle_sip_header_cseq_create(20,method),
		                    belle_sip_header_from_create2(identity,BELLE_SIP_RANDOM_TAG),
		                    belle_sip_header_to_create2(identity,NULL),
		                    belle_sip_header_via_new(),
		                    70);
	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(contact));
	if (!client->expire_in_contact)
		belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(belle_sip_header_expires_create(1)));

	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(destination_route));
	if (content_type && body) {
		size_t body_lenth=strlen(body);
		belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(content_type));
		belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(belle_sip_header_content_length_create(body_lenth)));
		belle_sip_message_set_body(BELLE_SIP_MESSAGE(req),body,body_lenth);
	}
	trans=belle_sip_provider_create_client_transaction(client->provider,req);
	belle_sip_object_ref(trans);/*to avoid trans from being deleted before refresher can use it*/
	belle_sip_client_transaction_send_request(trans);
	if (client->early_refresher) {
		client->refresher= refresher = belle_sip_client_transaction_create_refresher(trans);
	} else {
		if (server->auth == none) {
			BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.twoHundredOk,1,1000));
		} else {
			BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.fourHundredOne,1,1000));
			/*update cseq*/
			req=belle_sip_client_transaction_create_authenticated_request(trans,NULL,NULL);
			belle_sip_object_unref(trans);
			trans=belle_sip_provider_create_client_transaction(client->provider,req);
			belle_sip_object_ref(trans);
			belle_sip_client_transaction_send_request(trans);
			BC_ASSERT_TRUE_FATAL(wait_for(server->stack,client->stack,&client->stat.twoHundredOk,1,1000));
		}
		client->refresher= refresher = belle_sip_client_transaction_create_refresher(trans);
	}
	BC_ASSERT_TRUE_FATAL(refresher!=NULL);
	belle_sip_object_unref(trans);
	belle_sip_refresher_set_listener(refresher,belle_sip_refresher_listener,client);

	begin = belle_sip_time_ms();
	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.refreshOk,client->register_count+(client->early_refresher?1:0),client->register_count*1000 + 1000));
	end = belle_sip_time_ms();
	BC_ASSERT_TRUE(end-begin>=client->register_count*1000*.9); /*because refresh is at 90% of expire*/
	BC_ASSERT_TRUE(end-begin<(client->register_count*1000 + 2000));
	/*unregister twice to make sure refresh operation can be safely cascaded*/
	belle_sip_refresher_refresh(refresher,0);
	belle_sip_refresher_refresh(refresher,0);
	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.refreshOk,client->register_count+1,1000));
	BC_ASSERT_EQUAL(client->stat.refreshOk,client->register_count+1,int,"%d");
	belle_sip_refresher_stop(refresher);
	belle_sip_object_unref(refresher);
}
static void subscribe_test(void) {
	belle_sip_listener_callbacks_t client_callbacks;
	belle_sip_listener_callbacks_t server_callbacks;
	belle_sip_request_t* req;
	belle_sip_client_transaction_t* trans;
	belle_sip_header_route_t* destination_route;
	const char* identity = "sip:" USERNAME "@" SIPDOMAIN ;
	const char* domain="sip:" SIPDOMAIN ;
	endpoint_t* client,*server;
	belle_sip_uri_t *dest_uri;
	belle_sip_refresher_t* refresher;
	belle_sip_header_contact_t* contact=belle_sip_header_contact_new();
	uint64_t begin;
	uint64_t end;
	memset(&client_callbacks,0,sizeof(belle_sip_listener_callbacks_t));
	memset(&server_callbacks,0,sizeof(belle_sip_listener_callbacks_t));

	client_callbacks.process_dialog_terminated=client_process_dialog_terminated;
	client_callbacks.process_response_event=client_process_response_event;
	client_callbacks.process_auth_requested=client_process_auth_requested;
	server_callbacks.process_request_event=server_process_request_event;
	server_callbacks.process_dialog_terminated=server_process_dialog_terminated;
	
	client = create_udp_endpoint(3452,&client_callbacks);
	server = create_udp_endpoint(6788,&server_callbacks);
	server->expire_in_contact=0;
	server->auth=digest_auth;

	dest_uri=(belle_sip_uri_t*)belle_sip_object_clone((belle_sip_object_t*)belle_sip_listening_point_get_uri(server->lp));
	belle_sip_uri_set_host(dest_uri,"127.0.0.1");
	destination_route=belle_sip_header_route_create(belle_sip_header_address_create(NULL,dest_uri));


	req=belle_sip_request_create(
		                    belle_sip_uri_parse(domain),
		                    "SUBSCRIBE",
		                    belle_sip_provider_create_call_id(client->provider),
		                    belle_sip_header_cseq_create(20,"SUBSCRIBE"),
		                    belle_sip_header_from_create2(identity,BELLE_SIP_RANDOM_TAG),
		                    belle_sip_header_to_create2(identity,NULL),
		                    belle_sip_header_via_new(),
		                    70);
	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(contact));
	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(belle_sip_header_expires_create(1)));
	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(belle_sip_header_create("Event","Presence")));

	belle_sip_message_add_header(BELLE_SIP_MESSAGE(req),BELLE_SIP_HEADER(destination_route));
	trans=belle_sip_provider_create_client_transaction(client->provider,req);
	belle_sip_object_ref(trans);/*to avoid trans from being deleted before refresher can use it*/
	belle_sip_client_transaction_send_request(trans);

	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.fourHundredOne,1,1000));

	req=belle_sip_client_transaction_create_authenticated_request(trans,NULL,NULL);
	belle_sip_object_unref(trans);
	trans=belle_sip_provider_create_client_transaction(client->provider,req);
	belle_sip_object_ref(trans);
	belle_sip_client_transaction_send_request(trans);
	BC_ASSERT_TRUE_FATAL(wait_for(server->stack,client->stack,&client->stat.twoHundredOk,1,1000));
	 /*maybe dialog should be automatically created*/
	BC_ASSERT_PTR_NOT_NULL_FATAL(belle_sip_transaction_get_dialog(BELLE_SIP_TRANSACTION(trans)));

	refresher = belle_sip_client_transaction_create_refresher(trans);
	belle_sip_object_unref(trans);
	belle_sip_refresher_set_listener(refresher,belle_sip_refresher_listener,client);

	begin = belle_sip_time_ms();
	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.refreshOk,3,4000));
	end = belle_sip_time_ms();
	BC_ASSERT_TRUE(end-begin>=3000);
	BC_ASSERT_TRUE(end-begin<5000);
	/*unsubscribe twice to make sure refresh operation can be safely cascaded*/
	belle_sip_refresher_refresh(refresher,0);
	belle_sip_refresher_refresh(refresher,0);

	belle_sip_refresher_stop(refresher);
	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&client->stat.dialogTerminated,1,4000));
	BC_ASSERT_TRUE(wait_for(server->stack,client->stack,&server->stat.dialogTerminated,1,4000));
	belle_sip_object_unref(refresher);
	destroy_endpoint(client);
	destroy_endpoint(server);
}
Esempio n. 11
0
int main(int argc, const char *argv[])
{
    try
    {
        LogPolicy::GetInstance().Unmute();

        bool use_shared_memory = false, trial_run = false;
        std::string ip_address;
        int ip_port, requested_thread_num;

        ServerPaths server_paths;

        const unsigned init_result = GenerateServerProgramOptions(argc,
                                                                  argv,
                                                                  server_paths,
                                                                  ip_address,
                                                                  ip_port,
                                                                  requested_thread_num,
                                                                  use_shared_memory,
                                                                  trial_run);
        if (init_result == INIT_OK_DO_NOT_START_ENGINE)
        {
            return 0;
        }
        if (init_result == INIT_FAILED)
        {
            return 1;
        }

#ifdef __linux__
        const int lock_flags = MCL_CURRENT | MCL_FUTURE;
        if (-1 == mlockall(lock_flags))
        {
            SimpleLogger().Write(logWARNING) << argv[0] << " could not be locked to RAM";
        }
#endif
        SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION << ", "
                               << "compiled at " << __DATE__ << ", " __TIME__;

        if (use_shared_memory)
        {
            SimpleLogger().Write(logDEBUG) << "Loading from shared memory";
        }
        else
        {
            SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
            SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
            SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
            SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
            SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
            SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
            SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
            SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
            SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num;
            SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address;
            SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port;
        }
#ifndef _WIN32
        int sig = 0;
        sigset_t new_mask;
        sigset_t old_mask;
        sigfillset(&new_mask);
        pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

        OSRM osrm_lib(server_paths, use_shared_memory);
        Server *routing_server =
            ServerFactory::CreateServer(ip_address, ip_port, requested_thread_num);

        routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib);

        if (trial_run)
        {
            SimpleLogger().Write() << "trial run, quitting after successful initialization";
        }
        else
        {
            std::packaged_task<int()> server_task([&]()->int{ routing_server->Run(); return 0; });
            auto future = server_task.get_future();
            std::thread server_thread(std::move(server_task));

#ifndef _WIN32
            sigset_t wait_mask;
            pthread_sigmask(SIG_SETMASK, &old_mask, 0);
            sigemptyset(&wait_mask);
            sigaddset(&wait_mask, SIGINT);
            sigaddset(&wait_mask, SIGQUIT);
            sigaddset(&wait_mask, SIGTERM);
            pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
            SimpleLogger().Write() << "running and waiting for requests";
            sigwait(&wait_mask, &sig);
#else
            // Set console control handler to allow server to be stopped.
            console_ctrl_function = std::bind(&Server::Stop, routing_server);
            SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
            SimpleLogger().Write() << "running and waiting for requests";
            routing_server->Run();
#endif
            SimpleLogger().Write() << "initiating shutdown";
            routing_server->Stop();
            SimpleLogger().Write() << "stopping threads";

            auto status = future.wait_for(std::chrono::seconds(2));

            if (status != std::future_status::ready)
            {
                SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!";
                server_task.reset(); // just kill it
            }
            else
            {
                server_thread.join();
            }
        }

        SimpleLogger().Write() << "freeing objects";
        delete routing_server;
        SimpleLogger().Write() << "shutdown completed";
    }
    catch (const std::exception &e)
    {
        SimpleLogger().Write(logWARNING) << "exception: " << e.what();
        return 1;
    }
#ifdef __linux__
    munlockall();
#endif

    return 0;
}
Esempio n. 12
0
int 
main(void)
{
	unsigned int cycles = 1;
	unsigned int run_for = 2;
	unsigned int i;

	
	STOPWATCH_INIT(a);
	STOPWATCH_START(a);

	/**
	 * Calibrating the number of cycles so that the whole wait_for() process takes
	 * more than 400ms.
	 * This is not, and is not supposed to be, scientifically accurate. F.ex. possible
	 * application scheduling may mess this up.
	 *
	*/
	do {
		cycles *= 10;
		wait_for(cycles);

		STOPWATCH_STOP(a);
		i = STOPWATCH_ELAPSED_US(a);

	} while (i < 400000);

	printf("Cycles calibrated to %u\nRunning for %d+ seconds\n\n", cycles, run_for);


	/**
	 * Do wait_for() loops until run_for seconds has passed.
	 * Then print out the elapsed time and do some simple comparison.
	 *
	*/
	STOPWATCH_START(a);

	do {
		wait_for(cycles);
		
		STOPWATCH_STOP(a);
		i = STOPWATCH_ELAPSED_S(a);
	} while (i < run_for);

	STOPWATCH_PRINT(a);

	double const elap = STOPWATCH_ELAPSED_F(a);
	int const elap_s = STOPWATCH_ELAPSED_S(a);
	int const elap_us = STOPWATCH_ELAPSED_US(a);
	
	struct timeval *const tval = (struct timeval *) malloc(sizeof(struct timeval));
	STOPWATCH_TO_TIMEVAL(*tval, a);

	printf("Elapsed in floating point value: %f\n", elap);
	printf("Elapsed seconds: %d%s\n", elap_s, elap_s != (int) elap ? " <== BUG!": "");
	printf("Elapsed micro seconds: %d%s\n", elap_us, elap_us != ((int) (elap * 1000000 + 0.5)) % 1000000 ? " <== BUG!": "");
	printf("Copy to timeval %ld.%06lu%s\n", tval->tv_sec, tval->tv_usec, tval->tv_sec != elap_s  ||  tval->tv_usec != elap_us ? " <== BUG!" : "");

	free(tval);
	return 0;
}
Esempio n. 13
0
 bool waitForSyncEnd() {
   auto future = syncPromise.get_future();
   return future.wait_for(std::chrono::seconds(3)) == std::future_status::ready;
 }
Esempio n. 14
0
static void call_with_transport_base(LinphoneTunnelMode tunnel_mode, bool_t with_sip, LinphoneMediaEncryption encryption) {
	if (linphone_core_tunnel_available()){
		LinphoneCoreManager *pauline = linphone_core_manager_new( "pauline_rc");
		LinphoneCoreManager *marie = linphone_core_manager_new( "marie_rc");
		LinphoneCall *pauline_call;
		LinphoneProxyConfig *proxy = linphone_core_get_default_proxy_config(pauline->lc);
		LinphoneAddress *server_addr = linphone_address_new(linphone_proxy_config_get_server_addr(proxy));
		LinphoneAddress *route = linphone_address_new(linphone_proxy_config_get_route(proxy));
		const char * tunnel_ip = get_ip_from_hostname("tunnel.linphone.org");
		char *public_ip, *public_ip2=NULL;

		CU_ASSERT_TRUE(wait_for(pauline->lc,NULL,&pauline->stat.number_of_LinphoneRegistrationOk,1));
		public_ip = get_public_contact_ip(pauline->lc);
		CU_ASSERT_STRING_NOT_EQUAL(public_ip, tunnel_ip);

		linphone_core_set_media_encryption(pauline->lc, encryption);

		if (tunnel_mode != LinphoneTunnelModeDisable){
			LinphoneTunnel *tunnel = linphone_core_get_tunnel(pauline->lc);
			LinphoneTunnelConfig *config = linphone_tunnel_config_new();

			linphone_tunnel_config_set_host(config, "tunnel.linphone.org");
			linphone_tunnel_config_set_port(config, 443);
			linphone_tunnel_config_set_remote_udp_mirror_port(config, 12345);
			linphone_tunnel_add_server(tunnel, config);
			linphone_tunnel_set_mode(tunnel, tunnel_mode);
			linphone_tunnel_enable_sip(tunnel, with_sip);

			/*
			 * Enabling the tunnel with sip cause another REGISTER to be made.
			 * In automatic mode, the udp test should conclude (assuming we have a normal network), that no 
			 * tunnel is needed. Thus the number of registrations should stay to 1.
			 * The library is missing a notification of "tunnel connectivity test finished" to enable the 
			 * full testing of the automatic mode.
			 */

			if(tunnel_mode == LinphoneTunnelModeEnable && with_sip) {
				CU_ASSERT_TRUE(wait_for(pauline->lc,NULL,&pauline->stat.number_of_LinphoneRegistrationOk,2));
				/* Ensure that we did use the tunnel. If so, we should see contact changed from:
				Contact: <sip:[email protected]>;.[...]
				To:
				Contact: <sip:[email protected]:43867>;[....] (91.121.209.194 must be tunnel.liphone.org)
				*/
				ms_free(public_ip);
				public_ip = get_public_contact_ip(pauline->lc);
				CU_ASSERT_STRING_EQUAL(public_ip, tunnel_ip);
			} else {
				public_ip2 = get_public_contact_ip(pauline->lc);
				CU_ASSERT_STRING_EQUAL(public_ip, public_ip2);
			}
		}

		CU_ASSERT_TRUE(call(pauline,marie));
		pauline_call=linphone_core_get_current_call(pauline->lc);
		CU_ASSERT_PTR_NOT_NULL(pauline_call);
		if (pauline_call!=NULL){
			CU_ASSERT_EQUAL(linphone_call_params_get_media_encryption(linphone_call_get_current_params(pauline_call)),
				encryption);
		}
		end_call(pauline,marie);

		ms_free(public_ip);
		if(public_ip2 != NULL) ms_free(public_ip2);
		linphone_address_destroy(server_addr);
		linphone_address_destroy(route);
		linphone_core_manager_destroy(pauline);
		linphone_core_manager_destroy(marie);
	}else{
		ms_warning("Could not test %s because tunnel functionality is not available",__FUNCTION__);
	}
}
Esempio n. 15
0
	int ready_any() const {
		for (auto it = futures.begin(); it != futures.end(); ++it)
			if (it->wait_for(std::chrono::seconds(0)) == std::future_status::ready)
				return static_cast<int>(it - futures.begin());
		return -1;
	}
Esempio n. 16
0
int main(int argc, char * argv[]){
	int i;	

	if ((argc!=3)&&(argc!=4)) {
		printf("Usage:%s numer_of_readers number_of_writers [--test]\n", argv[0]);
		exit(1);
	}

	int readers= atoi(argv[1]);
	int writers= atoi(argv[2]);

	if ((readers<=0) || (writers<=0)){
		printf("Invalid numbers.\n", argv[0]);
		exit(1);
	}
	
	int test=0;
	if ((argc==4)&&(strncmp("--test", argv[3],7)==0)){
		test=1;
	}

	// generate producers and writers

	close(3); close(4);
	fcntl(0,F_DUPFD,3);
	fcntl(0,F_DUPFD,4);

	for (i=0; i< writers; i++){
		int fd1[2];
		int fd2[2];

		if (pipe(fd1)==-1) exit(1);
		if (pipe(fd2)==-1) exit(1);

		if (!fork()){
			close(fd2[0]); close(fd2[1]);
			producer(fd1,2*i);
		}

		if (!fork()){
			close(fd1[0]); close(fd1[1]);
			producer(fd2,2*i+1);
		}

		if (!fork()){
			close(3);
			close(4);
			fcntl(fd1[0],F_DUPFD,3);
			fcntl(fd2[0],F_DUPFD,4);
			close(0); 
			close(fd1[0]); close(fd1[1]);
			close(fd2[0]); close(fd2[1]);
			if (!test){
				close(1); 
				int er=execl(WRITER,WRITER,argv[1],argv[2],NULL);
			    fprintf(stderr,"writer exec failed with: %s\n",strerror(errno));
			} else {
				int er=execl(TEST_WRITER,TEST_WRITER,NULL);
			    fprintf(stderr,"test writer exec failed with: %s\n",strerror(errno));
			}

			exit(1);
		}	
		close(fd1[0]); close(fd1[1]);
		close(fd2[0]); close(fd2[1]);		
	}

	if (test) wait_for(3*writers);

	// generate readers

    printf("readers\n");

	char buf[20];
	int o=	sprintf(buf,"%s.out.",READER);
	for (i=0; i< readers; i++){
        printf("readersi loop %d\n",1);
		if (!fork()){
			sprintf(buf+o, "%d",i);
			close(1);
			int fd=open( buf, O_CREAT|O_TRUNC|O_WRONLY,S_IWUSR|S_IRUSR);
			
			fprintf(stderr,"reader open at: %d\n",fd);

			close(0);
			int er= execl(READER,READER,argv[1],argv[2],NULL);
			fprintf(stderr,"reader exec failed with: %s\n",strerror(errno));
			exit(1);
		}		
	}
	wait_for(3*writers+readers);
}
Esempio n. 17
0
 /** 
  * waits for begin() to be valid and then
  * returns it.  This is only safe for
  * single producers, multi-producers should
  * use claim(1) instead.
  */
 int64_t wait_next() {
   wait_for(begin_);
   return begin_;
 }
static void two_incoming_early_media_video_calls_test(void) {
	char *ringback_path;
	LinphoneCoreManager *marie;
	LinphoneCoreManager *pauline;
	LinphoneCoreManager *laure;
	LinphoneCallParams *marie_params;
	LinphoneCallParams *pauline_params;
	LinphoneCallParams *laure_params;
	LinphoneCall *call;
	const MSList *calls_list;

	marie = linphone_core_manager_new("marie_rc");
	pauline = linphone_core_manager_new("pauline_tcp_rc");
	laure = linphone_core_manager_new("laure_rc");
	marie_params = configure_for_early_media_video_receiving(marie);
	pauline_params = configure_for_early_media_video_sending(pauline);
	laure_params = configure_for_early_media_video_sending(laure);

	/* Configure early media audio to play ring during early-media and send remote ring back tone. */
	linphone_core_set_ring_during_incoming_early_media(marie->lc, TRUE);
	ringback_path = bc_tester_res("sounds/ringback.wav");
	linphone_core_set_remote_ringback_tone(marie->lc, ringback_path);
	ms_free(ringback_path);

	/* Early media video call from pauline to marie. */
	BC_ASSERT_TRUE(video_call_with_params(pauline, marie, pauline_params, NULL, FALSE));

	/* Wait for 2s. */
	wait_for_three_cores(marie->lc, pauline->lc, NULL, 2000);

	/* Early media video call from laure to marie. */
	BC_ASSERT_TRUE(video_call_with_params(laure, marie, laure_params, NULL, FALSE));

	/* Wait for 2s. */
	wait_for_three_cores(marie->lc, pauline->lc, laure->lc, 2000);

	BC_ASSERT_EQUAL(linphone_core_get_calls_nb(marie->lc), 2, int, "%d");
	if (linphone_core_get_calls_nb(marie->lc) == 2) {
		calls_list = linphone_core_get_calls(marie->lc);
		call = (LinphoneCall *)ms_list_nth_data(calls_list, 0);
		BC_ASSERT_PTR_NOT_NULL(call);
		if (call != NULL) {
			LinphoneCallParams *params = linphone_call_params_copy(linphone_call_get_current_params(call));
			linphone_call_params_set_audio_direction(params, LinphoneMediaDirectionSendRecv);
			linphone_call_params_set_video_direction(params, LinphoneMediaDirectionSendRecv);
			linphone_core_accept_call_with_params(marie->lc, call, params);

			/* Wait for 5s. */
			wait_for_three_cores(marie->lc, pauline->lc, laure->lc, 5000);
		}
	}

	linphone_core_terminate_all_calls(marie->lc);
	BC_ASSERT_TRUE(wait_for(marie->lc, pauline->lc, &marie->stat.number_of_LinphoneCallEnd, 1));
	BC_ASSERT_TRUE(wait_for(marie->lc, pauline->lc, &pauline->stat.number_of_LinphoneCallEnd, 1));
	BC_ASSERT_TRUE(wait_for(marie->lc, pauline->lc, &marie->stat.number_of_LinphoneCallReleased, 1));
	BC_ASSERT_TRUE(wait_for(marie->lc, pauline->lc, &pauline->stat.number_of_LinphoneCallReleased, 1));
	BC_ASSERT_TRUE(wait_for(marie->lc, laure->lc, &marie->stat.number_of_LinphoneCallEnd, 1));
	BC_ASSERT_TRUE(wait_for(marie->lc, laure->lc, &laure->stat.number_of_LinphoneCallEnd, 1));

	BC_ASSERT_EQUAL(marie->stat.number_of_video_windows_created, 2, int, "%d");
	BC_ASSERT_EQUAL(pauline->stat.number_of_video_windows_created, 1, int, "%d");
	BC_ASSERT_EQUAL(laure->stat.number_of_video_windows_created, 1, int, "%d");

	linphone_call_params_unref(marie_params);
	linphone_call_params_unref(pauline_params);
	linphone_call_params_unref(laure_params);
	linphone_core_manager_destroy(marie);
	linphone_core_manager_destroy(pauline);
	linphone_core_manager_destroy(laure);
}
Esempio n. 19
0
 /** 
  * When there are multiple writers they cannot both
  * assume the right to write to begin () to end (),
  * instead they must first claim some slots in an
  * atomic manner.
  *
  * After pos().aquire() == claim(slots) - 1 the claimer
  * is free to call publish up to start + slots - 1
  *
  * @return the first slot the caller may write to.
  */
 int64_t claim (size_t num_slots) {
   auto pos = claim_cursor_.atomic_increment_and_get(num_slots);
   // make sure there is enough space to write
   wait_for (pos);
   return pos - num_slots;
 }
Esempio n. 20
0
File: bpp.c Progetto: 274914765/C
static long read_ecp(unsigned minor, char __user *c, unsigned long cnt)
{
      unsigned long remaining;
      long rc;

        /* Turn ECP mode from forward to reverse if needed. */
      if (! instances[minor].direction) {
          unsigned short pins = get_pins(minor);

            /* Event 38: Turn the bus around */
          instances[minor].direction = 0x20;
          pins &= ~BPP_PP_nAutoFd;
          set_pins(pins, minor);

            /* Event 39: Set pins for reverse mode. */
          snooze(TIME_PSetup, minor);
          set_pins(BPP_PP_nStrobe|BPP_PP_nSelectIn, minor);

            /* Wait for event 40: Peripheral ready to be strobed */
          rc = wait_for(0, BPP_GP_PError, TIME_PResponse, minor);
          if (rc == -1) return -ETIMEDOUT;
      }

      remaining = cnt;

      while (remaining > 0) {

            /* If there is a run length for a repeated byte, repeat */
            /* that byte a few times. */
          if (instances[minor].run_length && !instances[minor].run_flag) {

              char buffer[128];
              unsigned idx;
              unsigned repeat = remaining < instances[minor].run_length
                                     ? remaining
                               : instances[minor].run_length;

              for (idx = 0 ;  idx < repeat ;  idx += 1)
                buffer[idx] = instances[minor].repeat_byte;

              if (copy_to_user(c, buffer, repeat))
              return -EFAULT;
              remaining -= repeat;
              c += repeat;
              instances[minor].run_length -= repeat;
          }

          if (remaining == 0) break;


            /* Wait for Event 43: Data active on the bus. */
          rc = wait_for(0, BPP_GP_nAck, TIME_IDLE_LIMIT, minor);
          if (rc == -1) break;

          if (rc & BPP_GP_Busy) {
                /* OK, this is data. read it in. */
              unsigned char byte = bpp_inb(base_addrs[minor]);
              if (put_user(byte, c))
              return -EFAULT;
              c += 1;
              remaining -= 1;

              if (instances[minor].run_flag) {
                  instances[minor].repeat_byte = byte;
                  instances[minor].run_flag = 0;
              }

          } else {
              unsigned char byte = bpp_inb(base_addrs[minor]);
              if (byte & 0x80) {
                  printk("bpp%d: "
                         "Ignoring ECP channel %u from device.\n",
                         minor, byte & 0x7f);
              } else {
                  instances[minor].run_length = byte;
                  instances[minor].run_flag = 1;
              }
          }

            /* Event 44: I got it. */
          set_pins(BPP_PP_nStrobe|BPP_PP_nAutoFd|BPP_PP_nSelectIn, minor);

            /* Wait for event 45: peripheral handshake */
          rc = wait_for(BPP_GP_nAck, 0, TIME_PResponse, minor);
          if (rc == -1) return -ETIMEDOUT;

             /* Event 46: Finish handshake */
          set_pins(BPP_PP_nStrobe|BPP_PP_nSelectIn, minor);

      }


      return cnt - remaining;
}
Esempio n. 21
0
Bool TERMWINDOWMEMBER parseLine(char *line)
    {
    int i, j, k;
    char *words[128];
    char newline[82];
    char done;

    const int count = parse_it(words, line);

    i = -1;

    while (++i < count)
        {
        switch (tolower(*words[i++]))
            {
            case 'd':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(6), words[i], words[i + 1], words[i + 2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                const protocols *theProt = GetProtocolByKey(words[i][0], TRUE);

                if (!theProt)
                    {
                    return (FALSE);
                    }

                wxrcv(words[i + 1], words[i + 2], theProt);

                i += 2;
                break;
                }

            case 'p':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(7), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                netpause(atoi(words[i]) * 100);
                break;
                }

            case 'r':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(8), words[i], words[i+1], words[i+2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                k = atoi(words[i+2]);

                for (done = FALSE, j = 0; j < k && !done; j++)
                    {
                    if (debug)
                        {
                        OC.ansiattr = cfg.wattr;
                        cPrintf(getdbmsg(9), words[i]);
                        OC.ansiattr = cfg.attr;
                        cPrintf(spc);
                        }
                    else
                        {
                        cPrintf(getmsg(433));
                        }

                    if (!wait_for(words[i], node->GetWaitTimeout()))
                        {
                        if (debug)
                            {
                            OC.ansiattr = cfg.wattr;
                            cPrintf(getdbmsg(10), words[i+1]);
                            OC.ansiattr = cfg.attr;
                            cPrintf(spc);
                            }
                        else
                            {
                            cPrintf(getmsg(433));
                            }

                        CommPort->OutString(words[i + 1], node->GetOutputPace());
                        }
                    else
                        {
                        done = TRUE;
                        }
                    }

                i += 2;

                if (!done)
                    {
                    return (FALSE);
                    }

                break;
                }

            case 's':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(10), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                CommPort->OutString(words[i], node->GetOutputPace());
                break;
                }

            case 'u':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(11), words[i], words[i + 1],
                            words[i + 2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                const protocols *theProt = GetProtocolByKey(words[i][0],
                        TRUE);

                if (!theProt)
                    {
                    return (FALSE);
                    }

                wxsnd(words[i + 1], words[i + 2], theProt, 0);

                i += 2;
                break;
                }

            case 'w':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(9), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                if (!wait_for(words[i], node->GetWaitTimeout()))
                    {
                    return (FALSE);
                    }

                break;
                }

            case '!':
                {
                RunApplication(words[i], NULL, TRUE, TRUE);
                break;
                }

            case '@':
                {
                FILE *file;

                if ((file = fopen(words[i], FO_R)) != NULL)
                    {
                    while (fgets(newline, 80, file))
                        {
                        if (!parseLine(newline))
                            {
                            fclose(file);
                            return (FALSE);
                            }
                        }

                    fclose(file);
                    }
                else
                    {
                    return (FALSE);
                    }

                break;
                }

            default:
                {
                OC.ansiattr = (uchar)(cfg.cattr | 128);
                cPrintf(getnetmsg(52), words[i-1], words[i]);
                OC.ansiattr = cfg.attr;
                cPrintf(spc);
                break;
                }
            }
        }

    return (TRUE);
    }