Beispiel #1
0
/**
 * Check if X509Cert is signed by trusted issuer
 * @return 0 or openssl error_code. Get human readable cause with X509_verify_cert_error_string(code)
 * @throw IOException if error
 */
int digidoc::X509Cert::verify() const throw(IOException)
{
    X509_STORE_CTX *csc = X509_STORE_CTX_new(); X509_STORE_CTX_scope csct(&csc);
    if (!csc)
        THROW_IOEXCEPTION("Failed to create X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));

    X509_STORE *store = digidoc::X509CertStore::getInstance()->getCertStore();
    X509* x = getX509(); X509_scope xt(&x);
    if(!X509_STORE_CTX_init(csc, store, x, NULL))
        THROW_IOEXCEPTION("Failed to init X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));

    int ok = X509_verify_cert(csc);

    if(!ok)
    {
        int err = X509_STORE_CTX_get_error(csc);
        X509Cert cause(X509_STORE_CTX_get_current_cert (csc));
        std::ostringstream s;
        s << "Unable to verify " << cause.getSubject();
        s << ". Cause: " << X509_verify_cert_error_string(err);
        switch(err)
        {
        case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
        {
            IOException e(__FILE__, __LINE__, s.str());
            e.setCode( Exception::CertificateIssuerMissing );
            throw e;
            break;
        }
        default: THROW_IOEXCEPTION(s.str().c_str()); break;
        }
    }

    return ok;
}
Beispiel #2
0
void cause_rethrow() {
    try {
	cause();
    } catch( C const &r ) {
	if( r.s <= 0 ) fail(__LINE__);
	throw;
    }
}
Beispiel #3
0
void cause_throw_anew() {
    try {
	cause();
    } catch( C const &r ) {
	if( r.s <= 0 ) fail(__LINE__);
	throw r;
    }
}
Beispiel #4
0
int main (int argc, char*argv[]) {
	static int 	n,	/* # de nodos */
			token,
			event,
			r,
			i;
	static char fa_name[5];

	if (argc != 2) {
		printf("Uso incorreto. Sintaxe: '%s <# de nodos>'\n",argv[0]);
		exit(1);
	}

	n=atoi(argv[1]);
	smpl(0,"um exemplo de simulacao");
	reset();
	stream(1);
	
	/* INICIALIZACAO */
	nodo = (tnodo*) malloc(sizeof(tnodo)*n);
	for (i=0;i<n;i++) {
		memset(fa_name, 0, 5);
		sprintf(fa_name,"%d",i);
		nodo[i].id = facility(fa_name,1);
		/* Aqui inicializa as variáveis locais */
	}
	
	/* escalonamento ds eventos */
	for (i=0; i<n; i++)
		schedule(test,30.0,i);
	schedule(fault,50.0,2);
	schedule(repair,80.0,2);
	
	while(time() < 100) {
		cause(&event,&token);
		switch(event) {
			case test:
				if(status(nodo[token].id) != 0) break;
				printf("O nodo %d vai estar no tempo %5.1f\n",token,time());
				schedule(test,30.0,token);
				break;
			case fault:
				r=request(nodo[token].id,token,0);
				if(r!=0) {
					printf("Nao foi possivel falhar o nodo %d\n",token);
					exit(1);
				}
				printf("O nodo %d falhou no tempo %5.1f\n", token, time());
				break;
			case repair:
				printf("O nodo %d se recuperou no tempo %5.1f\n", token, time());
				release(nodo[token].id,token);
				schedule(test,30.0,token);
				break;
		}
	}
}
Beispiel #5
0
bool bdoc::X509Cert::verify(X509_STORE* aStore, struct tm* tm) const
{
	if (aStore == NULL) {
		THROW_STACK_EXCEPTION("Invalid argument to verify");
	}

	X509_STORE* store = aStore;
	X509_STORE** ppStore = NULL;
	X509_STORE_scope xst(ppStore);

	X509_STORE_CTX *csc = X509_STORE_CTX_new();
	X509_STORE_CTX_scope csct(&csc);
	if (csc == NULL) {
		THROW_STACK_EXCEPTION("Failed to create X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));
	}

	X509* x = getX509();
	X509_scope xt(&x);
	if (!X509_STORE_CTX_init(csc, store, x, NULL)) {
		THROW_STACK_EXCEPTION("Failed to init X509_STORE_CTX %s",ERR_reason_error_string(ERR_get_error()));
	}

	if (tm != NULL) {
		time_t t = timegm(tm);
		if (t == -1) {
			THROW_STACK_EXCEPTION("Given time cannot be represented as calendar time");
		}

		X509_VERIFY_PARAM *param = X509_STORE_CTX_get0_param(csc);
		if (param == NULL) {
			THROW_STACK_EXCEPTION("Failed to retrieve X509_STORE_CTX verification parameters %s",
				ERR_reason_error_string(ERR_get_error()));
		}
		X509_VERIFY_PARAM_set_time(param, t);
	}

	int ok = X509_verify_cert(csc);

	if (ok != 1) {
		int err = X509_STORE_CTX_get_error(csc);
		X509Cert cause(X509_STORE_CTX_get_current_cert (csc));
		std::ostringstream s;
		s << "Unable to verify " << cause.getSubject();
		s << ". Cause: " << X509_verify_cert_error_string(err);
		switch (err) {
			case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
				{
					THROW_STACK_EXCEPTION("Certificate issuer missing: %s", s.str().c_str());
				}
			default: THROW_STACK_EXCEPTION(s.str().c_str()); break;
		}
	}

	return (ok == 1);
}
	void Dss1CallForGate::WaitAnswerTimeout(iCore::MsgTimer *pT)
	{
		if(m_isConnected) return;

		if(m_log->LogActive(m_infoTag))
		{
			*m_log << m_infoTag << "Wait answer timer expired." << iLogW::EndRecord;
		}

		boost::shared_ptr<const ISDN::DssCause> 
			cause(Cause(ISDN::IeConstants::NoUserResponding));

		ClearUserCallRef(cause);

		ReleaseDss1(cause);
	}
    void Dss1CallForGate::Release(const IDss1CallEvents *id, int rejectCode)
    {
        ESS_ASSERT(m_userCall.IsEqualIntf(id));
        
        if(!m_userCall.IsEmpty()) 
		{
			SetupCallRecord();
			m_userCall.Clear();
		}

        boost::shared_ptr<const ISDN::DssCause> cause(Cause(rejectCode));
		if(m_log->LogActive(m_infoTag))
		{
			*m_log << m_infoTag << "Disconnent from user. " << cause->ToString() << iLogW::EndRecord;
        }

        ReleaseDss1(cause);
    }
	void Dss1CallForGate::ChannelDeleted(iCmpExt::CmpChannelId channelId, const std::string &desc)
	{
		ESS_ASSERT(GetCmpChannelId() == channelId);

		m_cmpChannel.reset();

		if(m_log->LogActive(m_infoTag))
		{
			*m_log << m_infoTag << "Channel error.";
			if(!desc.empty()) *m_log << " " << desc;
			*m_log << iLogW::EndRecord;
		}

		boost::shared_ptr<const ISDN::DssCause> 
			cause(Cause(ISDN::IeConstants::TemporaryFailure));

		ClearUserCallRef(cause);

		ReleaseDss1(cause);
	}
Beispiel #9
0
int main(int argc, char *argv[]){
  static int N, /* Numero de nodos */
    token,
    event,
    teste,
    r, i;

  static char fa_name[5]; /* Facility Name */
  char *fail_code[2] = {"Sem falha", "Falho"};

  if(argc != 2){
    printf("USO: %s num_nodos\n", argv[0]);
    exit(1);
  }

  N = atoi(argv[1]);
  smpl(0, "Um Exemplo");
  reset();
  stream(1);

  /* Inicializacao */

  nodo = (Tnodo*) malloc(sizeof(Tnodo)*N);
  for(i = 0; i < N; i++){
    memset(fa_name, "\0", 5);
    sprintf(fa_name, "%d", i);
    nodo[i].id = facility(fa_name, 1);
    nodo[i].stats = -1;
    /* Aqui inicializa as variaveis locais */
  }

  /* Escalonamento de eventos */

  for(i=0; i<N; i++){
    schedule(test, 30.0, i);
  }

  schedule(fault, 50.0, 2); /* O nodo 2 vai falhar em 50.0 */
  schedule(fault, 50.0, 3);
  schedule(fault, 50.0, 4);
  schedule(repair, 100.0, 2);


  while(time() < 200){
    cause(&event, &token);
    switch(event){
    case test:

      if(status(nodo[token].id) != 0)
        break;

      teste = status(nodo[(token+1)%N].id);
      i = 1;
      while(teste){
        teste = status(nodo[(token+i)%N].id);
        if(!teste == 0){
          nodo[token].stats = (token+i)%N;
          i++;
        }
      }

      printf("%5.1f - O nodo %d testou o nodo %d. Resultado: %s\n",
             time(), token, (token+i)%N,
             fail_code[teste], nodo[token].stats);
      schedule(test, 30.0, token);

      break;

    case fault:
      r = request(nodo[token].id, token, 0);
      if(r != 0){
        puts("Nao foi possivel falhar o nodo\n");
        exit(1);
      }
      printf("%5.1f - O nodo %d falhou\n", time(), token);
      break;

    case repair:
      printf("%5.1f - O nodo %d recuperou\n", time(), token);
      release(nodo[token].id, token);
      schedule(test, 30.0, token);
      break;

    }
  }
  return 0;
}
Beispiel #10
0
/* Program body */
int main(int argc, char *argv[]) {
    static int N; 
    static int token;
    static int event;
    static int sender;
    static int timestamp;
    static int r;
    static int i;
    static int delay;
    static char fa_name[5];

    int scheduled_events = 0;

    if (argc < 2) {
        show_usage();
        exit(1);
    }

    // Number of nodes    
    N = argc-1;

    // Sets up SMPL simulation
    smpl(0, "mutual exclusion");
    reset();
    stream(1); // 1 execution thread

    // Node intialization
    nodes = (Node*) malloc(N*sizeof(Node));
    int times[N];
    for (i=0; i<N; i++) {
        memset (fa_name, '\0', 5);
        sprintf(fa_name, "%d", i);
        nodes[i].id = facility(fa_name, 1);
        nodes[i].running = false;
        nodes[i].clock = 0;
        nodes[i].pending = (bool *) malloc(N*sizeof(bool));
        memset (nodes[i].pending, false, N*sizeof(bool));

        nodes[i].waiting_reply = 0;

        times[i] = atoi(argv[i+1]);

        // Timestamp -1 means that the node has no active request
        nodes[i].timestamp = -1;
    }

    // Schedules the critical region requests
    for (i=0; i<N; i++) {
        schedule (REQUEST, times[i], i, i, 0);
        scheduled_events++;
    }

    printf("=============================================================================\n");
    printf("               Ricart-Agrawala mutual exclusion algorithm                    \n");
    printf("               Renan Greca - Distributed Systems, May 2016                   \n");
    printf("=============================================================================\n");

    // The program keeps running while there are still events scheduled
    while (scheduled_events > 0) {
        printf("-----\n");
        cause(&event, &token, &sender, &timestamp);
        switch(event) {
            case REQUEST:
                // REQUEST critical region access to other nodes
                scheduled_events--;

                nodes[token].clock++;
                printf("(%d, %d) Requested C.R. \n", token, nodes[token].clock);
                // Stores timestamp of request for priority reference
                nodes[token].timestamp = nodes[token].clock;

                // Sends requests to all other nodes
                for (i=0; i<N; i++) {
                    if (i==token) {
                        continue;
                    }
                    delay = rand_int(0, MAX_MESSAGE_DELAY);
                    // Sends REQUEST message to node i with a random delay
                    schedule (RECEIVE_REQUEST, delay, i, token, nodes[token].clock);
                    scheduled_events++;
                    nodes[token].waiting_reply++;

                }

                break;

            case RECEIVE_REQUEST:
                // Receive and handle a REQUEST
                scheduled_events--;

                // Updates logical clock
                nodes[token].clock = (nodes[token].clock > timestamp ? nodes[token].clock : timestamp)+1;
                printf("(%d, %d) Received request from %d\n", token, nodes[token].clock, sender);

                // Checks whether the sender node has priority over the receiver
                if (priority(sender, token, timestamp, nodes[token].timestamp) && !nodes[token].running) {
                    // If the sender has priority, send a REPLY
                    delay = rand_int(0, MAX_MESSAGE_DELAY);
                    printf("(%d, %d) Sending reply to %d\n", token, nodes[token].clock, sender);
                    schedule(RECEIVE_REPLY, delay, sender, token, nodes[token].clock);
                    scheduled_events++;
                } else {
                    // Else, store it in the pending array
                    printf("(%d, %d) Adding %d to pending array\n", token, nodes[token].clock, sender);
                    nodes[token].pending[sender] = true;
                }

                break;

            case RECEIVE_REPLY:
                // Receive and handle a REPLY
                scheduled_events--;

                // Updates logical clock
                nodes[token].clock = (nodes[token].clock > timestamp ? nodes[token].clock : timestamp)+1;
                printf("(%d, %d) Received reply from %d\n", token, nodes[token].clock, sender);
                
                nodes[token].waiting_reply--;
                // If node received all replies, it enters the critical region
                if (nodes[token].waiting_reply == 0) {
                    printf("(%d, %d) Entered the critical region.\n", token, nodes[token].clock);
                    schedule (RELEASE, RUNNING_INTERVAL, token, token, nodes[token].clock);
                    scheduled_events++;
                    nodes[token].running = true;
                }
                
                break;

            case RELEASE:
                // Release the critical region and alert other nodes
                scheduled_events--;
                
                nodes[token].clock++;
                printf("(%d, %d) Left the critical region.\n", token, nodes[token].clock);
                
                // Clear the information of the previous request
                nodes[token].running = false;
                nodes[token].timestamp = -1;

                // Send all pending REPLIES
                for (i=0; i<N; i++) {
                    if (nodes[token].pending[i]) {
                        delay = rand_int(0, MAX_MESSAGE_DELAY);
                        printf("(%d, %d) Sending reply to %d\n", token, nodes[token].clock, i);
                        schedule(RECEIVE_REPLY, delay, i, token, nodes[token].clock);
                        scheduled_events++;
                        nodes[token].pending[i] = false;
                    }
                }
                
                break;
        }
    }

}
Beispiel #11
0
/* Program body */
int main(int argc, char *argv[]) {
	static int N; // Number of nodes
	static int token;
	static int event;
	static int r;
	static int i;
	static char fa_name[5];
	
	if (argc != 2) {
		puts("Uso correto: tempo [num-nodos]");
		exit(1);
	}
	
	N = atoi(argv[1]);
	smpl(0, "programa tempo");
	reset();
	stream(1); // 1 execution thread
	
	// Node intialization
	nodes = (Node*) malloc(N*sizeof(Node));
	for (i=0; i<N; i++) {
		memset (fa_name, '\0', 5);
		sprintf(fa_name, "%d", i);
		nodes[i].id = facility(fa_name, 1);
	}
	
	for (i=0; i<N; i++) {
		schedule (TEST, 30.0, i);
	}
	schedule (FAULT, 31.0, 2);
	schedule (REPAIR, 61.0, 2);
	
	while (time() < 100.0) {
		cause(&event, &token);
		switch(event) {
			case TEST:
				if(status(nodes[token].id != 0)) {
					break;
				}
				printf("Sou o nodo %d, vou testar no tempo %5.1f\n", token, time());
				printf("\n");
				schedule(TEST, 30.0, token);
				break;
			case FAULT:
				r = request(nodes[token].id, token, 0);
				if (r != 0) {
					puts("Não consegui falhar o nodo!");
					exit(1);
				}
				printf("Sou o nodo %d, falhei no tempo %5.1f\n", token, time());


				break;
			case REPAIR:
				release(nodes[token].id, token);
				printf("Sou o nodo %d, recuperei no tempo %5.1f\n", token, time());

				schedule(TEST, 30.0, token);
				break;
		}
	}
}
Beispiel #12
0
int main(int argc, char **argv)
{
    const double sim_time = 200; ///< Total simulation time
    static int show_usage = 0;   ///< Flag to indicate if it is necessary to show usage options
    static int pnum = 0;         ///< Number of processes in the system

    int event,             ///< Current event
        pid,               ///< ID of the process executing the event
        num_requests = 0,  ///< Total number of requests in the simulation (used as stop criterion)
        p0_time = 0,       ///< Time at which process 0 will request the critical region
        p1_time = 0,       ///< Time at which process 1 will request the critical region
        p2_time = 0;       ///< Time at which process 2 will request the critical region

    struct timeval tp;
    queue_item recvd_msg;

    print_header();

    if (argc < 3) {
        print_usage(argv[0]);
        exit(1);
    }

    // parse parameters
    int c;
    while (1) {
        static struct option long_options[] = {
            {"help",  no_argument, &show_usage, 1},
            {"nproc", required_argument, 0, 'n'},
            {"rc0",   required_argument, 0, 'p'},
            {"rc1",   required_argument, 0, 'q'},
            {"rc2",   required_argument, 0, 'r'},
            {0, 0, 0, 0}
        };
        /* getopt_long stores the option index here. */
        int option_index = 0;

        c = getopt_long(argc, argv, "n:p:q:r:", long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1) break;

        switch (c) {
            case 0:
                /* If this option set a flag, do nothing else now. */
                if (long_options[option_index].flag != 0)
                    break;
                printf ("option %s", long_options[option_index].name);
                if (optarg)
                    printf (" with arg %s", optarg);
                printf ("\n");
                break;
            case 'n':
                pnum = (int) strtol(optarg, NULL, 10);
                break;
            case 'p':
                p0_time = (int) strtol(optarg, NULL, 10);
                ++num_requests;
                break;
            case 'q':
                p1_time = (int) strtol(optarg, NULL, 10);
                ++num_requests;
                break;
            case 'r':
                p2_time = (int) strtol(optarg, NULL, 10);
                ++num_requests;
                break;
            case '?':
                /* getopt_long already printed an error message. */
                break;
            default:
                abort();
        }
    }

    if (show_usage) {
        print_usage(argv[0]);
        exit(0);
    }

    if (pnum < 2) {
        printf("Error: Invalid number of processes! Please, specify at least 2 processes using the --nproc option.\n\n");
        print_usage(argv[0]);
        exit(1);
    } else if (pnum < 2 && p2_time != 0) {
        printf("Error: You have specified a time for process 2 (starting from 0) on a simulation with only 2 processes!\n\n");
        print_usage(argv[0]);
        exit(1);
    } else if (p0_time == 0 && p1_time == 0 && p2_time == 0) {
        printf("You have not specified any critical region requests in your simulation!\n\n");
        print_usage(argv[0]);
        exit(1);
    }

    // initialize PRNG
    gettimeofday(&tp, NULL);
    srand(tp.tv_sec + tp.tv_usec / 1000);
    seed(tp.tv_sec + tp.tv_usec / 1000, 1);

    smpl(0, "Ricart-Agrawala");
    stream(1);

    process plist = init_processes(pnum);

    printf("-- BEGIN PARAMETERS --\n");
    printf("Number of processes: %d\n", pnum);
    printf("Number of critical region requests: %d\n", num_requests);
    printf("Starting events:\n");
    if (p0_time != 0) {
        printf("  - Process 0 will request the critical region at time %d\n", p0_time);
        schedule(EV_REQUEST, p0_time, 0);
    }
    if (p1_time != 0) {
        printf("  - Process 1 will request the critical region at time %d\n", p1_time);
        schedule(EV_REQUEST, p1_time, 1);
    }
    if (p2_time != 0) {
        printf("  - Process 2 will request the critical region at time %d\n", p2_time);
        schedule(EV_REQUEST, p2_time, 2);
    }
    printf("-- END PARAMETERS --\n\n");

    printf("-- SIMULATION BEGIN --\n");
    while(time() < sim_time) {
        cause(&event, &pid);
        switch(event) {
            case EV_REQUEST:
                printf("Process %d has executed a critical region REQUEST at time %g\n", pid, time());
                plist[pid].state = ST_WANTED;
                // update pid's logical clock
                plist[pid].timestamp++;
                plist[pid].request_timestamp = plist[pid].timestamp;
                // broadcast REQUEST to all processes in the system
                broadcast(plist, pnum, pid);
                break;

            case EV_RECV:
                // remove next message to be received by pid
                recvd_msg = remove_max_pqueue(plist[pid].recvd_from);
                // synchronize pid's logical clock on receive before processing the message
                plist[pid].timestamp = (plist[pid].timestamp > recvd_msg->timestamp) ?
                    plist[pid].timestamp : recvd_msg->timestamp;
                plist[pid].timestamp++;

                printf("Process %d received %s from %d at time %g\n", pid, (recvd_msg->type == MSG_REQUEST) ? "REQUEST" : "REPLY", recvd_msg->pid, time());

                recv(plist, pnum, pid, recvd_msg->pid, recvd_msg->timestamp, recvd_msg->type);

                free(recvd_msg);
                break;
            case EV_RELEASE:
                printf("Process %d released the critical region at time %g\n", pid, time());

                releasecr(plist, pnum, pid);
                num_requests--;
                break;
        }

        // no more requests to simulate, simulation ended
        if (num_requests == 0) break;
    }
    printf("-- SIMULATION END --\n");

    destroy_processes(plist, pnum);

    return 0;
}