NTSTATUS
kmdf1394_AsyncWrite (
                     IN WDFDEVICE             Device,
                     IN WDFREQUEST         Request,
                     IN PASYNC_WRITE       AsyncWrite)
/*++

Routine Description:

    Async Write routine.

Arguments:

    Device - the current WDFDEVICE Object.

    Request - the current request.

    AsyncWrite - the Data buffer from usermode to be worked on.

Return Value:

    VOID
--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_EXTENSION deviceExtension = GetDeviceContext(Device);
    PIRB pIrb = NULL;
    PMDL   pMdl = NULL;
    WDFIOTARGET ioTarget = NULL;
    WDFMEMORY Memory;

    ENTER("kmdf1394_AsyncWrite");

    ioTarget = deviceExtension->StackIoTarget;


    pIrb = ExAllocatePoolWithTag(NonPagedPool, sizeof(IRB), POOLTAG_KMDF_VDEV);
    if (!pIrb) 
    {
        TRACE(TL_ERROR, ("Failed to allocate pIrb!\n"));
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    RtlZeroMemory (pIrb, sizeof (IRB));
    pIrb->FunctionNumber = REQUEST_ASYNC_WRITE;
    pIrb->Flags = 0;
    pIrb->u.AsyncWrite.DestinationAddress = AsyncWrite->DestinationAddress;
    pIrb->u.AsyncWrite.nNumberOfBytesToWrite = AsyncWrite->nNumberOfBytesToWrite;
    pIrb->u.AsyncWrite.nBlockSize = AsyncWrite->nBlockSize;
    pIrb->u.AsyncWrite.fulFlags = AsyncWrite->fulFlags;

    if (AsyncWrite->bGetGeneration) 
    {
        TRACE(
            TL_TRACE, 
            ("Retrieved Generation Count = 0x%x\n", 
            pIrb->u.AsyncRead.ulGeneration));

        pIrb->u.AsyncRead.ulGeneration = deviceExtension->GenerationCount;
    }
    else 
    {
        pIrb->u.AsyncRead.ulGeneration = AsyncWrite->ulGeneration;
    }

    pMdl = IoAllocateMdl (
        AsyncWrite->Data,
        AsyncWrite->nNumberOfBytesToWrite,
        FALSE,
        FALSE,
        NULL);
    if(NULL == pMdl) 
    {
        TRACE(TL_ERROR, ("Failed to allocate mdl!\n"));

        ExFreePoolWithTag (pIrb, POOLTAG_KMDF_VDEV);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    MmBuildMdlForNonPagedPool (pMdl);

    pIrb->u.AsyncWrite.Mdl = pMdl;

    //
    // We need to create a WDF Memory object for the IRB to nestle in
    // for an async request.
    //
    ntStatus = WdfMemoryCreatePreallocated (
        WDF_NO_OBJECT_ATTRIBUTES,
        pIrb,
        sizeof (IRB),
        &Memory);

    if (!NT_SUCCESS (ntStatus))
    {
        TRACE (
            TL_ERROR,
            ("Failed WdfMemoryCreate %d\n", 
            ntStatus));

        IoFreeMdl (pIrb->u.AsyncWrite.Mdl);
        ExFreePoolWithTag (pIrb, POOLTAG_KMDF_VDEV);

        return ntStatus;
    }

    WdfRequestSetCompletionRoutine (
        Request, 
        kmdf1394_AsyncWriteCompletion, 
        Memory);

    ntStatus = kmdf1394_SubmitIrpAsync (ioTarget, Request, Memory);
    if (!NT_SUCCESS(ntStatus)) 
    {
        if (ntStatus != STATUS_INVALID_GENERATION) 
        {
            TRACE(TL_ERROR, ("SubmitIrpSync failed = 0x%x\n", ntStatus));
        }
        else
        {
            TRACE (TL_ERROR, ("Invalid Generation count\n"));
        }

        IoFreeMdl (pIrb->u.AsyncWrite.Mdl);
        ExFreePoolWithTag (pIrb, POOLTAG_KMDF_VDEV);
        WdfObjectDelete (Memory);
    }

    EXIT("kmdf1394_AsyncWrite", ntStatus);
    return ntStatus;
} // kmdf1394_AsyncWrite
/*!
 * Send message to queue or signal to thread
 */
int sys__msg_post ( int dest_type, void *dest, msg_t *msg, uint flags )
{
	thread_t *thr;
	kthread_t *kthr, *new_kthr;
	kthrmsg_qs *thrmsg;
	kgmsg_q *kgmsgq;
	kmsg_q *kmsgq;
	msg_q *msgq;
	kmsg_t *kmsg;
	msg_t *cmsg;

	ASSERT_ERRNO_AND_EXIT ( dest && msg, E_INVALID_HANDLE );

	if ( dest_type == MSG_THREAD || dest_type == MSG_SIGNAL )
	{
		thr = dest;
		kthr = k_get_kthread ( thr );
		ASSERT_ERRNO_AND_EXIT ( kthr, E_DONT_EXIST );
		thrmsg = k_get_thrmsg ( kthr );
		kmsgq = &thrmsg->msgq;
	}
	else if ( dest_type == MSG_QUEUE )
	{
		msgq = dest;
		kgmsgq = msgq->handle;
		ASSERT_ERRNO_AND_EXIT ( kgmsgq && kgmsgq->id == msgq->id,
					E_INVALID_HANDLE );
		kmsgq = &kgmsgq->mq;
	}
	else {
		EXIT ( E_INVALID_TYPE );
	}

	if ( dest_type == MSG_THREAD || dest_type == MSG_QUEUE )
	{
		/* send message to queue */
		if ( kmsgq->min_prio <= msg->type ) /* msg has required prio. */
		{
			kmsg = kmalloc ( sizeof (kmsg_t) + msg->size );
			ASSERT_ERRNO_AND_EXIT ( kmsg, E_NO_MEMORY );

			kmsg->msg.type = msg->type;
			kmsg->msg.size = msg->size;
			memcpy ( kmsg->msg.data, msg->data, msg->size );

			list_append ( &kmsgq->msgs, kmsg, &kmsg->list );

			/* is thread waiting for message? */
			if ( k_release_thread ( &kmsgq->thrq ) )
				k_schedule_threads ();

			EXIT ( SUCCESS );
		}
		else { /* ignore message */
			EXIT ( E_IGNORED );
		}
	}

	/* must be MSG_SIGNAL */
	if ( thrmsg->sig_prio <= msg->type )
	{
		/* create thread that will service this signal */

		cmsg = k_create_thread_private_storage ( kthr,
				sizeof (msg_t) + msg->size );
		cmsg->type = msg->type;
		cmsg->size = msg->size;
		memcpy ( cmsg->data, msg->data, msg->size );

		new_kthr = k_create_thread (
			thrmsg->signal_handler, cmsg, pi.exit,
			k_get_thread_prio ( kthr ) + 1, NULL, 0, 1
		);
		ASSERT_ERRNO_AND_EXIT ( new_kthr, k_get_errno() );

		k_set_thread_private_storage ( new_kthr, cmsg );

		SET_ERRNO ( SUCCESS );

		k_schedule_threads ();

		RETURN ( SUCCESS );
	}
	else { /* ignore signal */
		EXIT ( E_IGNORED );
	}
}
Beispiel #3
0
/*!
 * Start new process
 * \param prog_name Program name (as given with module)
 * \param thr_desc Pointer to thread descriptor (user) for starting thread
 * \param param Command line arguments for starting thread (if not NULL)
 * \param prio Priority for starting thread
 */
int sys__start_program ( void *p )
{
	char *prog_name;
	void *param;
	int prio;
	thread_t *thr_desc;
	kthread_t *kthr, *cur = active_thread;
	char *arg, *karg, **args, **kargs = NULL;
	int argnum, argsize;

	prog_name = *( (void **) p ); p += sizeof (void *);
	ASSERT_ERRNO_AND_EXIT ( prog_name, E_INVALID_HANDLE );

	prog_name = U2K_GET_ADR ( prog_name, cur->proc );

	thr_desc = *( (void **) p ); p += sizeof (void *);

	param = *( (void **) p ); p += sizeof (void *);

	prio = *( (int *) p );

	if ( param ) /* copy parameters from one process space to another */
	{
		/* copy parameters to new process address space */
		/* first copy them to kernel */
		argnum = 0;
		argsize = 0;
		args = U2K_GET_ADR ( param, cur->proc );
		while ( args[argnum] )
		{
			arg = U2K_GET_ADR ( args[argnum++], cur->proc );
			argsize += strlen ( arg ) + 1;
		}
		if ( argnum > 0 )
		{
			kargs = kmalloc ( (argnum + 1) * sizeof (void *) +
					      argsize );
			karg = (void *) kargs + (argnum + 1) * sizeof (void *);
			argnum = 0;
			while ( args[argnum] )
			{
				arg = U2K_GET_ADR ( args[argnum], cur->proc );
				strcpy ( karg, arg );
				kargs[argnum++] = karg;
				karg += strlen ( karg ) + 1;
			}
			kargs[argnum] = NULL;
		}
	}

	SET_ERRNO ( SUCCESS );

	kthr = k_proc_start ( prog_name, kargs, prio );

	if ( !kthr )
		EXIT ( E_NO_MEMORY );

	if ( thr_desc ) /* save thread descriptor */
	{
		thr_desc = U2K_GET_ADR ( thr_desc, cur->proc );
		thr_desc->thread = kthr;
		thr_desc->thr_id = kthr->id;
	}

	RETURN ( SUCCESS );
}
Beispiel #4
0
/*
 * Execute the shell command tree pointed to by t.
 */
static void
execute(struct tnode *t, int *pin, int *pout)
{
	struct tnode *t1;
	enum tnflags f;
	pid_t cpid;
	int i, pfd[2];
	const char **gav;
	const char *cmd, *p;

	if (t == NULL)
		return;
	switch (t->ntype) {
	case TLIST:
		f = t->nflags & (FFIN | FPIN | FINTR);
		if ((t1 = t->nleft) != NULL)
			t1->nflags |= f;
		execute(t1, NULL, NULL);
		if ((t1 = t->nright) != NULL)
			t1->nflags |= f;
		execute(t1, NULL, NULL);
		return;

	case TPIPE:
		if (pipe(pfd) == -1) {
			err(SH_ERR, FMT1S, ERR_PIPE);
			if (pin != NULL) {
				(void)close(pin[0]);
				(void)close(pin[1]);
			}
			return;
		}
		f = t->nflags;
		if ((t1 = t->nleft) != NULL)
			t1->nflags |= FPOUT | (f & (FFIN|FPIN|FINTR|FPRS));
		execute(t1, pin, pfd);
		if ((t1 = t->nright) != NULL)
			t1->nflags |= FPIN | (f & (FAND|FPOUT|FINTR|FPRS));
		execute(t1, pfd, pout);
		(void)close(pfd[0]);
		(void)close(pfd[1]);
		return;

	case TCOMMAND:
		if (t->nav == NULL || t->nav[0] == NULL) {
			/* should never (but can) be true */
			err(SH_ERR, FMT1S, "execute: Invalid command");
			return;
		}
		cmd = t->nav[0];
		if (EQUAL(cmd, ":")) {
			status = SH_TRUE;
			return;
		}
		if (EQUAL(cmd, "chdir")) {
			ascan(t->nav[1], &trim);
			if (t->nav[1] == NULL)
				err(SH_ERR, FMT2S, cmd, ERR_ARGCOUNT);
			else if (chdir(t->nav[1]) == -1)
				err(SH_ERR, FMT2S, cmd, ERR_BADDIR);
			else
				status = SH_TRUE;
			return;
		}
		if (EQUAL(cmd, "exit")) {
			if (prompt == NULL) {
				(void)lseek(FD0, (off_t)0, SEEK_END);
				EXIT(status);
			}
			return;
		}
		if (EQUAL(cmd, "login") || EQUAL(cmd, "newgrp")) {
			if (prompt != NULL) {
				p = (*cmd == 'l') ? PATH_LOGIN : PATH_NEWGRP;
				vscan(t->nav, &trim);
				(void)sasignal(SIGINT, SIG_DFL);
				(void)sasignal(SIGQUIT, SIG_DFL);
				(void)pexec(p, (char *const *)t->nav);
				(void)sasignal(SIGINT, SIG_IGN);
				(void)sasignal(SIGQUIT, SIG_IGN);
			}
			err(SH_ERR, FMT2S, cmd, ERR_EXEC);
			return;
		}
		if (EQUAL(cmd, "shift")) {
			if (dolc > 1) {
				dolv = &dolv[1];
				dolc--;
				status = SH_TRUE;
				return;
			}
			err(SH_ERR, FMT2S, cmd, ERR_NOARGS);
			return;
		}
		if (EQUAL(cmd, "wait")) {
			pwait(-1);
			return;
		}
		/*FALLTHROUGH*/

	case TSUBSHELL:
		f = t->nflags;
		if ((cpid = ((f & FNOFORK) != 0) ? 0 : fork()) == -1) {
			err(SH_ERR, FMT1S, ERR_FORK);
			return;
		}
		/**** Parent! ****/
		if (cpid != 0) {
			if (pin != NULL && (f & FPIN) != 0) {
				(void)close(pin[0]);
				(void)close(pin[1]);
			}
			if ((f & FPRS) != 0)
				fd_print(FD2, "%u\n", (unsigned)cpid);
			if ((f & FAND) != 0)
				return;
			if ((f & FPOUT) == 0)
				pwait(cpid);
			return;
		}
		/**** Child! ****/
		/*
		 * Redirect (read) input from pipe.
		 */
		if (pin != NULL && (f & FPIN) != 0) {
			if (dup2(pin[0], FD0) == -1)
				err(FC_ERR, FMT1S, strerror(errno));
			(void)close(pin[0]);
			(void)close(pin[1]);
		}
		/*
		 * Redirect (write) output to pipe.
		 */
		if (pout != NULL && (f & FPOUT) != 0) {
			if (dup2(pout[1], FD1) == -1)
				err(FC_ERR, FMT1S, strerror(errno));
			(void)close(pout[0]);
			(void)close(pout[1]);
		}
		/*
		 * Redirect (read) input from file.
		 */
		if (t->nfin != NULL && (f & FPIN) == 0) {
			f |= FFIN;
			ascan(t->nfin, &trim);
			if ((i = open(t->nfin, O_RDONLY)) == -1)
				err(FC_ERR, FMT2S, t->nfin, ERR_OPEN);
			if (dup2(i, FD0) == -1)
				err(FC_ERR, FMT1S, strerror(errno));
			(void)close(i);
		}
		/*
		 * Redirect (write) output to file.
		 */
		if (t->nfout != NULL && (f & FPOUT) == 0) {
			if ((f & FCAT) != 0)
				i = O_WRONLY | O_APPEND | O_CREAT;
			else
				i = O_WRONLY | O_TRUNC | O_CREAT;
			ascan(t->nfout, &trim);
			if ((i = open(t->nfout, i, 0666)) == -1)
				err(FC_ERR, FMT2S, t->nfout, ERR_CREATE);
			if (dup2(i, FD1) == -1)
				err(FC_ERR, FMT1S, strerror(errno));
			(void)close(i);
		}
		/*
		 * Set the action for the SIGINT and SIGQUIT signals, and
		 * redirect input for `&' commands from `/dev/null' if needed.
		 */
		if ((f & FINTR) != 0) {
			(void)sasignal(SIGINT, SIG_IGN);
			(void)sasignal(SIGQUIT, SIG_IGN);
			if (t->nfin == NULL && (f & (FFIN|FPIN|FPRS)) == FPRS) {
				(void)close(FD0);
				if (open("/dev/null", O_RDONLY) != FD0)
					err(FC_ERR,FMT2S,"/dev/null",ERR_OPEN);
			}
		} else {
			if ((sig_child & S_SIGINT) != 0)
				(void)sasignal(SIGINT, SIG_DFL);
			if ((sig_child & S_SIGQUIT) != 0)
				(void)sasignal(SIGQUIT, SIG_DFL);
		}
		/* Set the SIGTERM signal to its default action if needed. */
		if ((sig_child & S_SIGTERM) != 0)
			(void)sasignal(SIGTERM, SIG_DFL);
		if (t->ntype == TSUBSHELL) {
			if ((t1 = t->nsub) != NULL)
				t1->nflags |= (f & (FFIN | FPIN | FINTR));
			execute(t1, NULL, NULL);
			_exit(status);
		}
		glob_flag = false;
		vscan(t->nav, &tglob);
		if (glob_flag) {
			for (i = 0; t->nav[i] != NULL; i++)
				;	/* nothing */
#ifdef	DEBUG
#ifdef	DEBUG_GLOB
			fd_print(FD2, "execute:  i      == %2d;\n", i);
			fd_print(FD2, "       : (i + 2) == %2d;\n", (i + 2));
			fd_print(FD2, "       : (i + 1) == %2d;\n", (i + 1));
#endif
#endif
			gav = xmalloc((i + 2) * sizeof(char *));
			gav[0] = "glob6";
			cmd = gav[0];
			(void)memcpy(&gav[1], t->nav, (i + 1) * sizeof(char *));
#ifdef	DEBUG
#ifdef	DEBUG_GLOB
			for (i = 0; gav[i] != NULL; i++)
				fd_print(FD2, "       : gav[%2d] == %s;\n",
				    i, gav[i]);
			fd_print(FD2, "       : gav[%2d] == NULL;\n", i);
#endif
#endif
			(void)err_pexec(cmd, (char *const *)gav);
		} else {
			vscan(t->nav, &trim);
			cmd = t->nav[0];
			(void)err_pexec(cmd, (char *const *)t->nav);
		}
		/*NOTREACHED*/
	}
}
Beispiel #5
0
int main(int argc, char **argv)
{
    BN_GENCB *cb;
    DSA *dsa = NULL;
    int counter, ret = 0, i, j;
    unsigned char buf[256];
    unsigned long h;
    unsigned char sig[256];
    unsigned int siglen;

    if (bio_err == NULL)
        bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    CRYPTO_set_mem_debug(1);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    RAND_seed(rnd_seed, sizeof rnd_seed);

    BIO_printf(bio_err, "test generation of DSA parameters\n");

    cb = BN_GENCB_new();
    if (!cb)
        goto end;

    BN_GENCB_set(cb, dsa_cb, bio_err);
    if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512,
                                                                   seed, 20,
                                                                   &counter,
                                                                   &h, cb))
        goto end;

    BIO_printf(bio_err, "seed\n");
    for (i = 0; i < 20; i += 4) {
        BIO_printf(bio_err, "%02X%02X%02X%02X ",
                   seed[i], seed[i + 1], seed[i + 2], seed[i + 3]);
    }
    BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h);

    DSA_print(bio_err, dsa, 0);
    if (counter != 105) {
        BIO_printf(bio_err, "counter should be 105\n");
        goto end;
    }
    if (h != 2) {
        BIO_printf(bio_err, "h should be 2\n");
        goto end;
    }

    i = BN_bn2bin(dsa->q, buf);
    j = sizeof(out_q);
    if ((i != j) || (memcmp(buf, out_q, i) != 0)) {
        BIO_printf(bio_err, "q value is wrong\n");
        goto end;
    }

    i = BN_bn2bin(dsa->p, buf);
    j = sizeof(out_p);
    if ((i != j) || (memcmp(buf, out_p, i) != 0)) {
        BIO_printf(bio_err, "p value is wrong\n");
        goto end;
    }

    i = BN_bn2bin(dsa->g, buf);
    j = sizeof(out_g);
    if ((i != j) || (memcmp(buf, out_g, i) != 0)) {
        BIO_printf(bio_err, "g value is wrong\n");
        goto end;
    }

    dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME;
    DSA_generate_key(dsa);
    DSA_sign(0, str1, 20, sig, &siglen, dsa);
    if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
        ret = 1;

    dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME;
    DSA_generate_key(dsa);
    DSA_sign(0, str1, 20, sig, &siglen, dsa);
    if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
        ret = 1;

 end:
    if (!ret)
        ERR_print_errors(bio_err);
    DSA_free(dsa);
    BN_GENCB_free(cb);

#ifndef OPENSSL_NO_CRYPTO_MDEBUG
    if (CRYPTO_mem_leaks(bio_err) <= 0)
        ret = 0;
#endif
    BIO_free(bio_err);
    bio_err = NULL;
    EXIT(!ret);
}
Beispiel #6
0
int main(int argc,char **argv)
{
  size_t preload_read;
  const char *preload_buffer;
  int yyparse_result;

  tree_init();

#ifdef WITH_CGI
  cgi_check_request();
  if (cgi_status < 0) {
    cgi_write_error_bad_req();
    return 0;
  }
#endif

  params_set_defaults();

#ifdef WITH_CGI
  if (!cgi_status)
    process_parameters(argc, argv);

  preload_buffer = charset_init_preload(param_inputf, &preload_read);

  if (cgi_status > 0)
    cgi_process_parameters(&preload_buffer, &preload_read);

  charset_auto_detect(preload_read);
  charset_preload_to_input(param_charset_in, preload_read);
  if (cgi_status == CGI_ST_MULTIPART)
    charset_cgi_boundary(boundary, boundary_len);
#else
  /* process command line arguments */
  process_parameters(argc, argv); 
  charset_init_preload(param_inputf, &preload_read);
  charset_auto_detect(preload_read);
  charset_preload_to_input(param_charset_in, preload_read);
#endif

  /* intialize the converter */
  saxStartDocument();
  if (param_inputf != stdin)
    parser_set_input(param_inputf);

  /* parse the input file and convert it */
  yyparse_result = yyparse();

  if (yyparse_result) {
    EXIT("Unrecoverable parse error");
  }

  charset_close();
  saxEndDocument();

#ifdef WITH_CGI
  if (!cgi_status) {
    /* write the output */
    if (writeOutput()) 
      EXIT("Bad state in writeOutput()");

    /* close de output file */
    if (param_outputf != stdout)
      fclose(param_outputf);
  } else {
    cgi_write_output();
  }
#else
  /* write the output */
  if (writeOutput()) 
    EXIT("Bad state in writeOutput()");
  
  /* close de output file */
  if (param_outputf != stdout)
    fclose(param_outputf);
#endif

  /* show final messages */
  write_end_messages();
  freeMemory();

  return 0;
}
Beispiel #7
0
/*!
  \brief updates the ms2 user_outputs controls which are a bit special purpose
  \param widget is the pointer to the widget to update
  */
G_MODULE_EXPORT void update_ms2_user_outputs(GtkWidget *widget)
{
	GtkTreeModel *model = NULL;
	DataSize size = MTX_U08;
	GtkTreeIter iter;
	gint tmpi = 0;
	gint t_bitval = 0;
	gboolean valid = FALSE;
	gfloat * multiplier = NULL;
	gfloat * adder = NULL;
	gchar *lower = NULL;
	gchar *upper = NULL;
	gchar *range = NULL;
	gchar *tempc_range = NULL;
	gchar *tempf_range = NULL;
	gchar *tempk_range = NULL;
	gchar *tmpbuf = NULL;
	gchar *tmpstr = NULL;
	gint bitmask = 0;
	gint bitshift = 0;
	gfloat tmpf = 0.0;
	gfloat tmpf2 = 0.0;
	gfloat value = 0.0;
	gboolean temp_dep = FALSE;
	gint i = 0;
	gint precision = 0;
	void *eval = NULL;
	GtkWidget *tmpwidget = NULL;

	ENTER();
	/*printf("update_ms2_user_outputs widget %s %p\n",glade_get_widget_name(widget),(void *)widget);*/
	get_essential_bits_f(widget, NULL, NULL, NULL, NULL, &bitmask, &bitshift);

	value = convert_after_upload_f(widget);
	tmpi = ((GINT)value & bitmask) >> bitshift;
	model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget));
	valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(model),&iter);
	i = 0;
	while (valid)
	{
		gtk_tree_model_get(GTK_TREE_MODEL(model),&iter,UO_BITVAL_COL,&t_bitval,-1);
		if (tmpi == t_bitval)
		{
			/* Get the rest of the data from the combo */
			gtk_tree_model_get(GTK_TREE_MODEL(model),&iter,
					UO_TEMP_DEP_COL,&temp_dep,
					UO_SIZE_COL,&size,
					UO_RAW_LOWER_COL,&lower,
					UO_RAW_UPPER_COL,&upper,
					UO_RANGE_COL,&range,
					UO_RANGE_TEMPC_COL,&tempc_range,
					UO_RANGE_TEMPF_COL,&tempf_range,
					UO_RANGE_TEMPK_COL,&tempk_range,
					UO_PRECISION_COL,&precision,
					UO_FROMECU_MULT_COL,&multiplier,
					UO_FROMECU_ADD_COL,&adder,-1);
			/*
			if (temp_dep)
			{
				printf("THIS WIDGET IS TEMP DEPENDENT\n");
				printf("raw_lower %s, raw_upper %s in treemodel\n",lower,upper);
				if (multiplier)
					printf("multiplier %f\n",*multiplier);
				if (adder)
					printf("adder %f\n",*adder);
				printf("size %i, precision %i, temp_dep %i\n",(gint)size,precision,(gint)temp_dep);
			}
			*/
			tmpbuf = (gchar *)OBJ_GET(widget,"range_label");
			if (tmpbuf)
				tmpwidget = lookup_widget_f(tmpbuf);
			if (GTK_IS_LABEL(tmpwidget))
			{
				if (temp_dep)
				{
					OBJ_SET(tmpwidget,"widget_temp",DATA_GET(global_data,"mtx_temp_units"));
					OBJ_SET(tmpwidget,"c_label",tempc_range);
					OBJ_SET(tmpwidget,"f_label",tempf_range);
					OBJ_SET(tmpwidget,"k_label",tempk_range);
					bind_to_lists_f(tmpwidget,"temperature");
					gtk_label_set_text(GTK_LABEL(tmpwidget),tempf_range);
					convert_temps_f(tmpwidget,DATA_GET(global_data,"mtx_temp_units"));
				}
				else
				{
					remove_from_lists_f("temperature",tmpwidget);
					OBJ_SET(tmpwidget,"widget_temp",NULL);
					OBJ_SET(tmpwidget,"temp_dep",NULL);
					/*OBJ_SET(tmpwidget,"c_label",NULL);
					  OBJ_SET(tmpwidget,"f_label",NULL);
					  OBJ_SET(tmpwidget,"k_label",NULL);
					  */
					gtk_label_set_text(GTK_LABEL(tmpwidget),range);
				}
			}
			tmpbuf = (gchar *)OBJ_GET(widget,"thresh_widget");
			if (tmpbuf)
				tmpwidget = lookup_widget_f(tmpbuf);
			if (GTK_IS_WIDGET(tmpwidget))
			{
				if (temp_dep)
				{
					OBJ_SET(tmpwidget,"widget_temp",DATA_GET(global_data,"mtx_temp_units"));
					OBJ_SET(tmpwidget,"temp_dep",GINT_TO_POINTER(temp_dep));
					bind_to_lists_f(tmpwidget,"temperature");
				}
				else
				{
					OBJ_SET(tmpwidget,"widget_temp",NULL);
					OBJ_SET(tmpwidget,"temp_dep",NULL);
					remove_from_lists_f("temperature",tmpwidget);
				}
				OBJ_SET(tmpwidget,"size",GINT_TO_POINTER(size));
				OBJ_SET(tmpwidget,"precision",GINT_TO_POINTER(precision));
				OBJ_SET(tmpwidget,"raw_lower",lower);
				OBJ_SET(tmpwidget,"raw_upper",upper);
				if (multiplier)
					OBJ_SET(tmpwidget,"fromecu_mult",multiplier);
				else
					OBJ_SET(tmpwidget,"fromecu_mult",NULL);
				if (adder)
					OBJ_SET(tmpwidget,"fromecu_add",adder);
				else
					OBJ_SET(tmpwidget,"fromecu_add",NULL);
				//convert_temps_f(tmpwidget,DATA_GET(global_data,"mtx_temp_units"));
				update_widget_f(tmpwidget,NULL);
			}
			tmpbuf = (gchar *)OBJ_GET(widget,"hyst_widget");
			if (tmpbuf)
				tmpwidget = lookup_widget_f(tmpbuf);
			if (GTK_IS_WIDGET(tmpwidget))
			{
				OBJ_SET(tmpwidget,"size",GINT_TO_POINTER(size));
				OBJ_SET(tmpwidget,"precision",GINT_TO_POINTER(precision));
				OBJ_SET(tmpwidget,"raw_lower",lower);
				OBJ_SET(tmpwidget,"raw_upper",upper);
				if (multiplier)
					OBJ_SET(tmpwidget,"fromecu_mult",multiplier);
				else
					OBJ_SET(tmpwidget,"fromecu_mult",NULL);
				if (adder)
					OBJ_SET(tmpwidget,"fromecu_add",adder);
				else
					OBJ_SET(tmpwidget,"fromecu_add",NULL);
				update_widget_f(tmpwidget,NULL);
			}
			g_free(range);
		}
		valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(model), &iter);
		i++;
	}
	EXIT();
	return;
}
Beispiel #8
0
/*-------------------------------------------------------------------*/
static IFD
open_input_image (char *ifname, U16 *devt, U32 *vcyls,
                U32 *itrkl, BYTE **itrkb, BYTE *volser)
{
int             rc;                     /* Return code               */
H30CKD_TRKHDR   h30trkhdr;              /* Input track header        */
IFD             ifd;                    /* Input file descriptor     */
int             len;                    /* Length of input           */
U16             code;                   /* Device type code          */
U16             dt;                     /* Device type               */
U32             cyls;                   /* Device size (pri+alt cyls)*/
U32             alts;                   /* Number of alternate cyls  */
BYTE           *itrkbuf;                /* -> Input track buffer     */
U32             itrklen;                /* Input track length        */
BYTE           *pbuf;                   /* Current byte in input buf */
BYTE            klen;                   /* Key length                */
U16             dlen;                   /* Data length               */
BYTE           *kptr;                   /* -> Key in input buffer    */
BYTE           *dptr;                   /* -> Data in input buffer   */
U32             cyl;                    /* Cylinder number           */
U32             head;                   /* Head number               */
BYTE            rec;                    /* Record number             */
char            pathname[MAX_PATH];     /* file path in host format  */

    hostpath(pathname, (char *)ifname, sizeof(pathname));

    /* Open the HDR-30 CKD image file */
  #if defined(HAVE_LIBZ)
    if (strcmp(ifname, "-") == 0)
        ifd = gzdopen (STDIN_FILENO, "rb");
    else
        ifd = gzopen (pathname, "rb");

    if (ifd == NULL)
    {
        fprintf (stderr, MSG(HHC02412, "E", "gzopen()", strerror(errno)));
        EXIT(3);
    }
  #else /*!defined(HAVE_LIBZ)*/
    if (strcmp(ifname, "-") == 0)
        ifd = STDIN_FILENO;
    else
    {
        ifd = HOPEN (pathname, O_RDONLY | O_BINARY);

        if (ifd < 0)
        {
            fprintf (stderr, MSG(HHC02412, "E", "open()", strerror(errno)));
            EXIT(3);
        }
    }
  #endif /*!defined(HAVE_LIBZ)*/

    /* Read the first track header */
    read_input_data (ifd, ifname, (BYTE*)&h30trkhdr,
                    H30CKD_TRKHDR_SIZE, 0);

  #if !defined(HAVE_LIBZ)
    /* Reject input if compressed and we lack gzip support */
    if (memcmp(h30trkhdr.devcode, gz_magic_id, sizeof(gz_magic_id)) == 0)
    {
        fprintf (stderr, MSG(HHC02413, "E"));
        EXIT(3);
    }
  #endif /*!defined(HAVE_LIBZ)*/

    /* Reject input if it is already in CKD or CCKD format */
    if (memcmp((BYTE*)&h30trkhdr, ckd_ident, sizeof(ckd_ident)) == 0)
    {
        fprintf (stderr, MSG(HHC02414, "I"));
        EXIT(3);
    }

    /* Extract the device type code from the track header */
    FETCH_HW (code, h30trkhdr.devcode);

    /* Determine the input device type and size from the device code */
    switch (code) {
    case 0x01: dt=0x3330; cyls=411; alts=7; break;      /* 3330      */
    case 0x02: dt=0x3330; cyls=815; alts=7; break;      /* 3330-11   */
    case 0x03: dt=0x3340; cyls=351; alts=1; break;      /* 3340-35   */
    case 0x04: dt=0x3340; cyls=701; alts=1; break;      /* 3340-70   */
    case 0x05: dt=0x3350; cyls=562; alts=7; break;      /* 3350      */
    case 0x06: dt=0x3375; cyls=962; alts=3; break;      /* 3375      */
    case 0x08: dt=0x3380; cyls=888; alts=3; break;      /* 3380-A,D,J*/
    case 0x09: dt=0x3380; cyls=1774; alts=4; break;     /* 3380-E    */
    case 0x0A: dt=0x3380; cyls=2660; alts=5; break;     /* 3380-K    */
    case 0x0B: dt=0x3390; cyls=1117; alts=4; break;     /* 3390-1    */
    case 0x0C: dt=0x3390; cyls=2230; alts=4; break;     /* 3390-2    */
    case 0x0D: dt=0x3390; cyls=3343; alts=4; break;     /* 3390-3    */
    case 0x12: dt=0x2314; cyls=203; alts=3; break;      /* 2314      */
    case 0x13: dt=0x3390; cyls=10038; alts=21; break;   /* 3390-9    */
    case 0x14: dt=0x9345; cyls=1454; alts=14; break;    /* 9345-1    */
    case 0x15: dt=0x9345; cyls=2170; alts=14; break;    /* 9345-2    */
    default:
        fprintf (stderr, MSG(HHC02415, "E", code));
        EXIT(3);
    } /* end switch(code) */

    /* Use the device type to determine the input image track size */
    switch (dt) {
    case 0x2314: itrklen = 0x2000; break;
    case 0x3330: itrklen = 0x3400; break;
    case 0x3340: itrklen = 0x2400; break;
    case 0x3350: itrklen = 0x4C00; break;
    case 0x3375: itrklen = 0x9000; break;
    case 0x3380: itrklen = 0xBC00; break;
    case 0x3390: itrklen = 0xE400; break;
    case 0x9345: itrklen = 0xBC00; break;
    default:
        fprintf (stderr, MSG(HHC02416, "E", dt));
        EXIT(3);
    } /* end switch(dt) */

    /* Obtain the input track buffer */
    itrkbuf = malloc (itrklen);
    if (itrkbuf == NULL)
    {
        char buf[40];
        MSGBUF( buf, "malloc(%u)", itrklen);
        fprintf (stderr, MSG(HHC02412, "E", buf, strerror(errno)));
        EXIT(3);
    }

    /* Copy the first track header to the input track buffer */
    memcpy (itrkbuf, &h30trkhdr, H30CKD_TRKHDR_SIZE);

    /* Read the remainder of the first track into the buffer */
    read_input_data (ifd, ifname,
                     itrkbuf + H30CKD_TRKHDR_SIZE,
                     itrklen - H30CKD_TRKHDR_SIZE,
                     H30CKD_TRKHDR_SIZE);

    /* Initialize the volume serial number */
    strcpy ((char *)volser, "(NONE)");

    /* Search for volume label in record 3 of first track */
    pbuf = itrkbuf + H30CKD_TRKHDR_SIZE;
    len = itrklen - H30CKD_TRKHDR_SIZE;
    while (1)
    {
        /* Find next input record */
        rc = find_input_record (itrkbuf, &pbuf, &len,
                &klen, &kptr, &dlen, &dptr,
                &cyl, &head, &rec);

        /* Give up if error or end of track */
        if (rc != 0) break;

        /* Process when record 3 is found */
        if (cyl == 0 && head == 0 && rec == 3)
        {
            /* Extract volser if it is a volume label */
            if (klen == 4 && memcmp(kptr, ebcdicvol1, 4) == 0
            && dlen == 80 && memcmp(dptr, ebcdicvol1, 4) == 0)
                make_asciiz ((char *)volser, 7, dptr+4, 6);
            break;
        }
    } /* end while */

    /* Set output variables and return the input file descriptor */
    *devt = dt;
    *vcyls = cyls - alts;
    *itrkl = itrklen;
    *itrkb = itrkbuf;
    return ifd;

} /* end function open_input_image */
Beispiel #9
0
/*-------------------------------------------------------------------*/
static void
convert_ckd_file (IFD ifd, char *ifname, int itrklen, BYTE *itrkbuf,
                int repl, int quiet,
                char *ofname, int fseqn, U16 devtype, U32 heads,
                U32 trksize, BYTE *obuf, U32 start, U32 end,
                U32 volcyls, BYTE *volser)
{
int             rc;                     /* Return code               */
int             ofd;                    /* Output file descriptor    */
CKDDASD_DEVHDR  devhdr;                 /* Output device header      */
CKDDASD_TRKHDR *trkhdr;                 /* -> Output track header    */
CKDDASD_RECHDR *rechdr;                 /* -> Output record header   */
U32             cyl;                    /* Cylinder number           */
U32             head;                   /* Head number               */
int             fileseq;                /* CKD header sequence number*/
int             highcyl;                /* CKD header high cyl number*/
BYTE           *opos;                   /* -> Byte in output buffer  */
BYTE            klen;                   /* Key length                */
U16             dlen;                   /* Data length               */
BYTE            rec;                    /* Record number             */
BYTE           *iptr;                   /* -> Byte in input buffer   */
BYTE           *kptr;                   /* -> Key in input buffer    */
BYTE           *dptr;                   /* -> Data in input buffer   */
int             ilen;                   /* Bytes left in input buffer*/
H30CKD_TRKHDR  *ith;                    /* -> Input track header     */
U32             ihc, ihh;               /* Input trk header cyl,head */
U32             offset;                 /* Current input file offset */
char            pathname[MAX_PATH];     /* file path in host format  */

    UNREFERENCED(volser);

    /* Set file sequence number to zero if this is the only file */
    if (fseqn == 1 && end + 1 == volcyls)
        fileseq = 0;
    else
        fileseq = fseqn;

    /* Set high cylinder number to zero if this is the last file */
    if (end + 1 == volcyls)
        highcyl = 0;
    else
        highcyl = end;

    /* Create the AWSCKD image file */
    hostpath(pathname, (char *)ofname, sizeof(pathname));
    ofd = HOPEN (pathname,
                O_WRONLY | O_CREAT | O_BINARY | (repl ? 0 : O_EXCL),
                S_IRUSR | S_IWUSR | S_IRGRP);

    if (ofd < 0)
    {
        fprintf (stderr, MSG(HHC02412, "E", "open()", strerror(errno)));
        EXIT(8);
    }

    /* Create the device header */
    memset(&devhdr, 0, CKDDASD_DEVHDR_SIZE);
    memcpy(devhdr.devid, "CKD_P370", 8);
    devhdr.heads[3] = (heads >> 24) & 0xFF;
    devhdr.heads[2] = (heads >> 16) & 0xFF;
    devhdr.heads[1] = (heads >> 8) & 0xFF;
    devhdr.heads[0] = heads & 0xFF;
    devhdr.trksize[3] = (trksize >> 24) & 0xFF;
    devhdr.trksize[2] = (trksize >> 16) & 0xFF;
    devhdr.trksize[1] = (trksize >> 8) & 0xFF;
    devhdr.trksize[0] = trksize & 0xFF;
    devhdr.devtype = devtype & 0xFF;
    devhdr.fileseq = fileseq;
    devhdr.highcyl[1] = (highcyl >> 8) & 0xFF;
    devhdr.highcyl[0] = highcyl & 0xFF;

    /* Write the device header */
    rc = write (ofd, &devhdr, CKDDASD_DEVHDR_SIZE);
    if (rc < CKDDASD_DEVHDR_SIZE)
    {
        fprintf (stderr, MSG(HHC02412, "E", "write()", errno ? strerror(errno) : "incomplete"));
        EXIT(1);
    }

    /* Write each cylinder */
    for (cyl = start; cyl <= end; cyl++)
    {
        /* Display progress message every 10 cylinders */
        if ((cyl % 10) == 0)
        {
#ifdef EXTERNALGUI
            if (extgui)
                fprintf (stderr, "CYL=%u\n", cyl);
            else
#endif /*EXTERNALGUI*/
            if (quiet == 0)
                fprintf (stderr, "Writing cylinder %u\r", cyl);
        }

        for (head = 0; head < heads; head++)
        {
            /* Calculate the current offset in the file */
            offset = ((cyl*heads)+head)*itrklen;

            /* Read the input track image (except cyl 0 head 0
               already read by the open_input_image procedure) */
            if (cyl > 0 || head > 0)
            {
                read_input_data (ifd, ifname,
                                 itrkbuf, itrklen,
                                 offset);
            } /* end if(cyl>0||head>0) */

            /* Validate the track header */
            ith = (H30CKD_TRKHDR*)itrkbuf;
            FETCH_HW (ihc, ith->cyl);
            FETCH_HW (ihh, ith->head);
            if (ihc != cyl || ihh != head)
            {
                fprintf (stderr, MSG(HHC02417, "E", offset));
                fprintf (stderr, MSG(HHC02418, "E",
                        cyl, head, ihc, ihh));
                EXIT(8);
            }

            /* Clear the output track image to zeroes */
            memset (obuf, 0, trksize);

            /* Build the output track header */
            trkhdr = (CKDDASD_TRKHDR*)obuf;
            trkhdr->bin = 0;
            STORE_HW (trkhdr->cyl, cyl);
            STORE_HW (trkhdr->head, head);
            opos = obuf + CKDDASD_TRKHDR_SIZE;

            /* Copy each record from the input buffer */
            iptr = itrkbuf + H30CKD_TRKHDR_SIZE;
            ilen = itrklen - H30CKD_TRKHDR_SIZE;
            while (1)
            {
                /* Locate the next input record */
                rc = find_input_record (itrkbuf, &iptr, &ilen,
                        &klen, &kptr, &dlen, &dptr,
                        &ihc, &ihh, &rec);

                /* Exit at end of track */
                if (rc == 1) break;

                /* Error if invalid record header detected */
                if (rc > 1)
                {
                    fprintf (stderr, MSG(HHC02419, "E",
                            rc, (unsigned int)(iptr-itrkbuf), cyl, head,
                            offset, ifname));
                    EXIT(9);
                }

                /* Build AWSCKD record header in output buffer */
                rechdr = (CKDDASD_RECHDR*)opos;
                opos += CKDDASD_RECHDR_SIZE;
                STORE_HW (rechdr->cyl, ihc);
                STORE_HW (rechdr->head, ihh);
                rechdr->rec = rec;
                rechdr->klen = klen;
                STORE_HW (rechdr->dlen, dlen);

                /* Copy key and data to output buffer */
                if (klen != 0)
                {
                    memcpy (opos, kptr, klen);
                    opos += klen;
                }
                if (dlen != 0)
                {
                    memcpy (opos, dptr, dlen);
                    opos += dlen;
                }

            } /* end while */

            /* Build the end of track marker */
            memcpy (opos, eighthexFF, 8);

            /* Write the track to the file */
            rc = write (ofd, obuf, trksize);
            if (rc < 0 || (U32)rc < trksize)
            {
                fprintf (stderr, MSG(HHC02412, "E", "write()",
                        errno ? strerror(errno) : "incomplete"));
                EXIT(1);
            }

        } /* end for(head) */

    } /* end for(cyl) */

    /* Close the AWSCKD image file */
    rc = close (ofd);
    if (rc < 0)
    {
        fprintf (stderr, MSG(HHC02412, "E", "close()", strerror(errno)));
        EXIT(10);
    }

    /* Display completion message */
    fprintf (stderr, MSG(HHC02420, "I",
            cyl - start, ofname));

} /* end function convert_ckd_file */
Beispiel #10
0
/*! Receive message from queue (global or from own thread message queue) */
int sys__msg_recv ( void *p )
{
	/* parameters on thread stack */
	int src_type;	/* MSG_QUEUE or MSG_THREAD 		*/
	void *src;	/* (msg_q *) or (thread_t *)		*/
	msg_t *msg;	/* { type, size, data[0..size-1] }	*/
	int type;	/* message type (identifier) */
	size_t size;	/* size of 'data' member */
	uint flags;
	/* local variables */
	kthread_t *kthr;
	kthrmsg_qs *thrmsg;
	kgmsg_q *kgmsgq;
	kmsg_q *kmsgq;
	msg_q *msgq;
	kmsg_t *kmsg;

	src_type = *( (int *) p );	p += sizeof (int);
	src = *( (void **) p );		p += sizeof (void *);
	msg = *( (msg_t **) p );	p += sizeof (msg_t *);
	type = *( (int *) p );		p += sizeof (int);
	size = *( (size_t *) p );	p += sizeof (size_t);
	flags = *( (uint *) p );

	ASSERT_ERRNO_AND_EXIT ( src && msg, E_INVALID_HANDLE );

	ASSERT_ERRNO_AND_EXIT ( src_type == MSG_THREAD || src_type == MSG_QUEUE,
				E_INVALID_TYPE );

	if ( src_type == MSG_THREAD )
	{
		kthr = k_get_active_thread ();
		thrmsg = k_get_thrmsg ( kthr );
		kmsgq = &thrmsg->msgq;
	}
	else { /* src_type == MSG_QUEUE */
		msgq = src;
		kgmsgq = msgq->handle;
		ASSERT_ERRNO_AND_EXIT ( kgmsgq && kgmsgq->id == msgq->id,
					E_INVALID_HANDLE );
		kmsgq = &kgmsgq->mq;
	}

	/* get first message from queue */
	kmsg = list_get ( &kmsgq->msgs, FIRST );

	if ( type != 0 ) /* type != 0 => search for first message 'type' */
		while ( kmsg && kmsg->msg.type != type )
			kmsg = list_get_next ( &kmsg->list );

	if ( kmsg ) /* have message */
	{
		if ( size < kmsg->msg.size )
		{
			msg->size = 0;
			EXIT ( E_TOO_BIG );
		}

		msg->type = kmsg->msg.type;
		msg->size = kmsg->msg.size;
		memcpy ( msg->data, kmsg->msg.data, msg->size );

		kmsg = list_remove ( &kmsgq->msgs, FIRST, &kmsg->list );
		ASSERT ( kmsg );
		kfree ( kmsg );

		EXIT ( SUCCESS );
	}
	else { /* queue empty! */
		if ( !( flags & IPC_WAIT ) )
			EXIT ( E_EMPTY );

		SET_ERRNO ( E_RETRY );
		/* block thread */
		k_enqueue_thread ( NULL, &kmsgq->thrq );

		k_schedule_threads ();

		RETURN ( E_RETRY );
	}
}
Beispiel #11
0
/*-------------------------------------------------------------------*/
int main ( int argc, char *argv[] )
{
char           *pgmname;                /* prog name in host format  */
char           *pgm;                    /* less any extension (.ext) */
char            msgbuf[512];            /* message build work area   */
IFD             ifd;                    /* Input file descriptor     */
int             repl = 0;               /* 1=replace existing file   */
int             quiet = 0;              /* 1=suppress progress msgs  */
BYTE           *itrkbuf;                /* -> Input track buffer     */
U32             itrklen;                /* Input track length        */
U32             volcyls;                /* Total cylinders on volume */
U32             heads = 0;              /* Number of tracks/cylinder */
U32             maxdlen = 0;            /* Maximum R1 data length    */
U16             devtype;                /* Device type               */
char            ifname[256];            /* Input file name           */
char            ofname[256];            /* Output file name          */
BYTE            volser[7];              /* Volume serial (ASCIIZ)    */
int             lfs = 0;                /* 1 = Build large file      */
char           *strtok_str = NULL;

    /* Set program name */
    if ( argc > 0 )
    {
        if ( strlen(argv[0]) == 0 )
        {
            pgmname = strdup( UTILITY_NAME );
        }
        else
        {
            char path[MAX_PATH];
#if defined( _MSVC_ )
            GetModuleFileName( NULL, path, MAX_PATH );
#else
            strncpy( path, argv[0], sizeof( path ) );
#endif
            pgmname = strdup(basename(path));
#if !defined( _MSVC_ )
            strncpy( path, argv[0], sizeof(path) );
#endif
        }
    }
    else
    {
        pgmname = strdup( UTILITY_NAME );
    }

    pgm = strtok_r( strdup(pgmname), ".", &strtok_str);
    INITIALIZE_UTILITY( pgm );

    /* Display the program identification message */
    MSGBUF( msgbuf, MSG_C( HHC02499, "I", pgm, "DASD CKD image conversion" ) );
    display_version (stderr, msgbuf+10, FALSE);

    /* Process the options in the argument list */
    for (; argc > 1; argc--, argv++)
    {
        if (strcmp(argv[1], "-") == 0) break;
        if (argv[1][0] != '-') break;
        if (strcmp(argv[1], "-r") == 0)
            repl = 1;
        else if (strcmp(argv[1], "-q") == 0)
            quiet = 1;
        else
        if (sizeof(off_t) > 4 && strcmp(argv[1], "-lfs") == 0)
            lfs = 1;
        else
            argexit(5, pgm);
    }
    if (argc != 3)
        argexit(5, pgm);

    /* The first argument is the input file name */
    if (argv[1] == NULL || strlen(argv[1]) == 0
        || strlen(argv[1]) > sizeof(ifname)-1)
        argexit(1, pgm);
    strcpy (ifname, argv[1]);

    /* The second argument is the output file name */
    if (argv[2] == NULL || strlen(argv[2]) == 0
        || strlen(argv[2]) > sizeof(ofname)-1)
        argexit(2, pgm);
    strcpy (ofname, argv[2]);

    /* Read the first track of the input file, and determine
       the device type and size from the track header */
    ifd = open_input_image (ifname, &devtype, &volcyls,
                &itrklen, &itrkbuf, volser);

    /* Use the device type to determine track characteristics */
    switch (devtype) {
    case 0x2314: heads = 20; maxdlen = 7294; break;
    case 0x3330: heads = 19; maxdlen = 13030; break;
    case 0x3340: heads = 12; maxdlen = 8368; break;
    case 0x3350: heads = 30; maxdlen = 19069; break;
    case 0x3375: heads = 12; maxdlen = 35616; break;
    case 0x3380: heads = 15; maxdlen = 47476; break;
    case 0x3390: heads = 15; maxdlen = 56664; break;
    case 0x9345: heads = 15; maxdlen = 46456; break;
    default:
        fprintf (stderr, MSG(HHC02416, "E", devtype));
        EXIT(3);
    } /* end switch(devtype) */

    /* Create the device */
    convert_ckd (lfs, ifd, ifname, itrklen, itrkbuf, repl, quiet,
                ofname, devtype, heads, maxdlen, volcyls, volser);

    /* Release the input buffer and close the input file */
    free (itrkbuf);
    IFCLOS (ifd);

    /* Display completion message */
    fprintf (stderr, MSG(HHC02423, "I"));

    return 0;

} /* end function main */
Beispiel #12
0
void OnCmdStart(CCommandParser* pParser)
{
	if(!s_vtClients.empty())
	{
		::LogClientStartFail(SE_ILLEGAL_STATE, ::HP_GetSocketErrorDesc(SE_ILLEGAL_STATE));
		return;
	}

	s_stat.Reset();

	for(DWORD i = 0; i < g_app_arg.conn_count; i++)
	{
		CSSLClientPtr pSocket(&s_listener);

		if(!pSocket->SetupSSLContext(g_c_iVerifyMode, g_c_lpszPemCertFile, g_c_lpszPemKeyFile, g_c_lpszKeyPasswod, g_c_lpszCAPemCertFileOrPath))
		{
			int iErrCode = ::SYS_GetLastError();
			::LogClientStartFail(iErrCode, _T("initialize SSL env fail"));

			ClearHPSocketPtrSet(s_vtClients);

			EXIT(EX_CONFIG, iErrCode);
		}

		pSocket->SetKeepAliveTime(g_app_arg.keep_alive ? TCP_KEEPALIVE_TIME : 0);

		if(pSocket->Start(g_app_arg.remote_addr, g_app_arg.port, g_app_arg.async))
			s_vtClients.push_back(pSocket.Detach());
		else
		{
			::LogClientStartFail(pSocket->GetLastError(), pSocket->GetLastErrorDesc());
			ClearHPSocketPtrSet(s_vtClients);

			return;
		}
	}

	::LogClientStart(g_app_arg.remote_addr, g_app_arg.port);

	DWORD dwSendDelay = 3;
	CString strMsg;

	strMsg.Format(_T("*** willing to send data after %d seconds ***"), dwSendDelay);
	::LogMsg(strMsg);

	::WaitFor(dwSendDelay * 500);

	while(true)
	{
		int iConnected = s_stat.GetConnected();

		if(iConnected < 0)
		{
			ClearHPSocketPtrSet(s_vtClients);

			::LogClientStartFail(ERROR_CONNREFUSED, ::HP_GetSocketErrorDesc(SE_CONNECT_SERVER));

			return;
		}
		else if(iConnected == (int)g_app_arg.conn_count)
			break;
		
		::WaitFor(3);
	}

	::WaitFor(dwSendDelay * 500);
	s_sendBuffer.Malloc(g_app_arg.data_length, true);

	::LogMsg(_T("*** Go Now ! ***"));

	s_stat.StartTest();

	BOOL bTerminated = FALSE;
	for(DWORD i = 0; i < g_app_arg.test_times; i++)
	{
		for(DWORD j = 0; j < g_app_arg.conn_count; j++)
		{
			ITcpClient* pSocket = s_vtClients[j];
			if(!pSocket->Send(s_sendBuffer, (int)s_sendBuffer.Size()))
			{
				::LogClientSendFail(i + 1, j + 1, ::SYS_GetLastError(), ::HP_GetSocketErrorDesc(SE_DATA_SEND));
				bTerminated = TRUE;
				break;
			}
		}

		if(bTerminated)
			break;

		if(g_app_arg.test_interval > 0 && i + 1 < g_app_arg.test_times)
			::WaitFor(g_app_arg.test_interval);
	}

	if(bTerminated)
		ClearHPSocketPtrSet(s_vtClients);

	s_sendBuffer.Free();
}
Beispiel #13
0
int main(int argc,char **argv)
    {
    const char *szTestFile;
    FILE *f;

    if(argc != 2)
	{
	fprintf(stderr,"%s <test file>\n",argv[0]);
	EXIT(1);
	}
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    szTestFile=argv[1];

    f=fopen(szTestFile,"r");
    if(!f)
	{
	perror(szTestFile);
	EXIT(2);
	}

    /* Load up the software EVP_CIPHER and EVP_MD definitions */
    OpenSSL_add_all_ciphers();
    OpenSSL_add_all_digests();
#ifndef OPENSSL_NO_ENGINE
    /* Load all compiled-in ENGINEs */
    ENGINE_load_builtin_engines();
#endif
#if 0
    OPENSSL_config();
#endif
#ifndef OPENSSL_NO_ENGINE
    /* Register all available ENGINE implementations of ciphers and digests.
     * This could perhaps be changed to "ENGINE_register_all_complete()"? */
    ENGINE_register_all_ciphers();
    ENGINE_register_all_digests();
    /* If we add command-line options, this statement should be switchable.
     * It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use if
     * they weren't already initialised. */
    /* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */
#endif

    for( ; ; )
	{
	char line[4096];
	char *p;
	char *cipher;
	unsigned char *iv,*key,*plaintext,*ciphertext;
	int encdec;
	int kn,in,pn,cn;

	if(!fgets((char *)line,sizeof line,f))
	    break;
	if(line[0] == '#' || line[0] == '\n')
	    continue;
	p=line;
	cipher=sstrsep(&p,":");	
	key=ustrsep(&p,":");
	iv=ustrsep(&p,":");
	plaintext=ustrsep(&p,":");
	ciphertext=ustrsep(&p,":");
	if (p[-1] == '\n') {
	    p[-1] = '\0';
	    encdec = -1;
	} else {
	    encdec = atoi(sstrsep(&p,"\n"));
	}
	      

	kn=convert(key);
	in=convert(iv);
	pn=convert(plaintext);
	cn=convert(ciphertext);

	if(!test_cipher(cipher,key,kn,iv,in,plaintext,pn,ciphertext,cn,encdec)
	   && !test_digest(cipher,plaintext,pn,ciphertext,cn))
	    {
#ifdef OPENSSL_NO_AES
	    if (strstr(cipher, "AES") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_DES
	    if (strstr(cipher, "DES") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_RC4
	    if (strstr(cipher, "RC4") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_CAMELLIA
	    if (strstr(cipher, "CAMELLIA") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_SEED
	    if (strstr(cipher, "SEED") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
	    fprintf(stderr,"Can't find %s\n",cipher);
	    EXIT(3);
	    }
	}
	fclose(f);

#ifndef OPENSSL_NO_ENGINE
    ENGINE_cleanup();
#endif
    EVP_cleanup();
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_thread_state(NULL);
    ERR_free_strings();
    CRYPTO_mem_leaks_fp(stderr);

    return 0;
    }
Beispiel #14
0
static int test1_exit(int ec)
	{
	EXIT(ec);
	return(0);		/* To keep some compilers quiet */
	}
Beispiel #15
0
// Upon return no more I/O is possible. The stream is closed.
//
// If ne_close indicates a recoverable error, then the object is
// logged to the "degraded object log".
int mc_sync(DAL_Context* ctx) {
   ENTRY();

   ObjectStream* os         = MC_OS(ctx);
   ne_handle     handle     = MC_HANDLE(ctx);
   MC_Config*    config     = MC_CONFIG(ctx);
   MC_Context*   mc_context = MC_CONTEXT(ctx);
   
   if(! (os->flags & OSF_OPEN)) {
      LOG(LOG_ERR, "%s isn't open\n", os->url);
      errno = EINVAL;
      return -1;
   }

   // the result of close for a handle opened for reading is an
   // indicator of whether the data is degraded and, if so, which
   // block is corrupt or missing.
   int error_pattern = ne_close(handle);
   if(error_pattern > 0) {
      // Keeping the log message as well as writing to the degraded
      // object file for debugging purposes.
      LOG(LOG_INFO, "WARNING: Object %s degraded. Error pattern: 0x%x."
          " (N: %d, E: %d, Start: %d).\n",
          mc_context->path_template, error_pattern,
          config->n, config->e, mc_context->start_block);
      // we shouldn't need more then 512 bytes to hold the extra data
      // needed for rebuild
      char buf[MC_MAX_LOG_LEN];
      snprintf(buf, MC_MAX_LOG_LEN,
               MC_DEGRADED_LOG_FORMAT, mc_context->path_template,
               config->n, config->e,
               mc_context->start_block, error_pattern,
               MC_FH(ctx)->info.pre.repo->name,
               mc_context->pod, mc_context->cap);
      WAIT(&config->lock);
      // If the degraded log file has not already been opened, open it now.
      if(config->degraded_log_fd == -1) {
         config->degraded_log_fd =
            open_degraded_object_log(config->degraded_log_path);
         if(config->degraded_log_fd < 0) {
            LOG(LOG_ERR, "failed to open degraded log file\n");
         }
         else {
            // If we successfully opened it, then free the resources
            // used to store the path.
            free(config->degraded_log_path);
            config->degraded_log_path = NULL;
         }
      }

      if(write(config->degraded_log_fd, buf, strlen(buf))
         != strlen(buf)) {
         LOG(LOG_ERR, "Failed to write to degraded object log\n");
         // theoretically the data is still safe, so we can just log
         // and ignore the failure.
      }
      POST(&config->lock);
   }
   else if(error_pattern < 0) {
      // close the stream, a failed sync renders the ne_handle
      // invalid calling mc_close should prevent marfs from ever
      // trying to use it again.
      mc_close(ctx);
      os->flags |= OSF_ERRORS;
      LOG(LOG_ERR, "ne_close failed on %s", mc_context->path_template);
      return -1;
   }

   EXIT();
   return 0;
}
Beispiel #16
0
/*-------------------------------------------------------------------*/
static void
convert_ckd (int lfs, IFD ifd, char *ifname, int itrklen,
            BYTE *itrkbuf, int repl, int quiet,
            char *ofname, U16 devtype, U32 heads,
            U32 maxdlen, U32 volcyls, BYTE *volser)
{
int             i;                      /* Array subscript           */
char            *s;                     /* String pointer            */
int             fileseq;                /* File sequence number      */
char            sfname[260];            /* Suffixed name of this file*/
char            *suffix;                /* -> Suffix character       */
U32             endcyl;                 /* Last cylinder of this file*/
U32             cyl;                    /* Cylinder number           */
U32             cylsize;                /* Cylinder size in bytes    */
BYTE           *obuf;                   /* -> Output track buffer    */
U32             mincyls;                /* Minimum cylinder count    */
U32             maxcyls;                /* Maximum cylinder count    */
U32             maxcpif;                /* Maximum number of cylinders
                                           in each CKD image file    */
int             rec0len = 8;            /* Length of R0 data         */
U32             trksize;                /* AWSCKD image track length */

    /* Compute the AWSCKD image track length */
    trksize = sizeof(CKDDASD_TRKHDR)
                + sizeof(CKDDASD_RECHDR) + rec0len
                + sizeof(CKDDASD_RECHDR) + maxdlen
                + sizeof(eighthexFF);
    trksize = ROUND_UP(trksize,512);

    /* Compute minimum and maximum number of cylinders */
    cylsize = trksize * heads;
    mincyls = 1;

    if (!lfs)
    {
        maxcpif = 0x80000000 / cylsize;
        maxcyls = maxcpif * CKD_MAXFILES;
    }
    else
        maxcpif = maxcyls = volcyls;

    if (maxcyls > 65536) maxcyls = 65536;

    /* Check for valid number of cylinders */
    if (volcyls < mincyls || volcyls > maxcyls)
    {
        fprintf (stderr, MSG(HHC02421, "E",
                volcyls, mincyls, maxcyls));
        EXIT(4);
    }

    /* Obtain track data buffer */
    obuf = malloc(trksize);
    if (obuf == NULL)
    {
        char buf[40];
        MSGBUF( buf, "malloc(%u)", trksize);
        fprintf (stderr, MSG(HHC02412, "E", buf, strerror(errno)));
        EXIT(6);
    }

    /* Display progress message */
    fprintf (stderr, MSG(HHC02422, "I",
            devtype, volser, volcyls, heads, trksize));
#ifdef EXTERNALGUI
    if (extgui)
        fprintf (stderr, "CYLS=%u\n", volcyls);
#endif /*EXTERNALGUI*/

    /* Copy the unsuffixed AWSCKD image file name */
    strcpy (sfname, ofname);
    suffix = NULL;

    /* Create the suffixed file name if volume will exceed 2GB */
    if (volcyls > maxcpif)
    {
        /* Look for last slash marking end of directory name */
        s = strrchr (ofname, '/');
        if (s == NULL) s = ofname;

        /* Insert suffix before first dot in file name, or
           append suffix to file name if there is no dot */
        s = strchr (s, '.');
        if (s != NULL)
        {
            i = s - ofname;
            strcpy (sfname + i, "_1");
            strcat (sfname, ofname + i);
            suffix = sfname + i + 1;
        }
        else
        {
            strcat (sfname, "_1");
            suffix = sfname + strlen(sfname) - 1;
        }
    }

    /* Create the AWSCKD image files */
    for (cyl = 0, fileseq = 1; cyl < volcyls;
            cyl += maxcpif, fileseq++)
    {
        /* Insert the file sequence number in the file name */
        if (suffix) *suffix = '0' + fileseq;

        /* Calculate the ending cylinder for this file */
        if (cyl + maxcpif < volcyls)
            endcyl = cyl + maxcpif - 1;
        else
            endcyl = volcyls - 1;

        /* Create an AWSCKD image file */
        convert_ckd_file (ifd, ifname, itrklen, itrkbuf, repl, quiet,
                        sfname, fileseq, devtype, heads, trksize,
                        obuf, cyl, endcyl, volcyls, volser);
    }

    /* Release the output track buffer */
    free (obuf);

} /* end function convert_ckd */
Beispiel #17
0
static void process_parameters(int argc, char **argv)
{
  int i, fich, tmpnum;

  /* process command line arguments */
  for (i=1, fich=0; i<argc; i++) {
    if (!strcmp(argv[i], "-e")) {
      param_strict = 0;
    } else if (!strcmp(argv[i], "-t") && ((i+1) < argc)) {
      param_doctype = dtd_get_dtd_index(argv[++i]);
    } else if (!strcmp(argv[i], "-o") && ((i+1) < argc)) {
      /* open the output file */
      param_outputf = fopen(argv[++i], "wb");
      if (!param_outputf) {
	perror("fopen");
	EXIT("Could not open the output file for writing");
      }
    } else if (!strcmp(argv[i], "-l") && ((i+1) < argc)) {
      tmpnum= atoi(argv[++i]);
      if (tmpnum >= 40)
	param_chars_per_line = tmpnum; 
    } else if (!strcmp(argv[i], "-b") && ((i+1) < argc)) {
      tmpnum= atoi(argv[++i]);
      if (tmpnum >= 0 && tmpnum <= 16)
	param_tab_len = tmpnum; 
    } else if (!strcmp(argv[i], "--preserve-space-comments")) {
      param_pre_comments = 1;
    } else if (!strcmp(argv[i], "--no-protect-cdata")) {
      param_protect_cdata = 0;
    } else if (!strcmp(argv[i], "--compact-block-elements")) {
      param_compact_block_elms = 1;
    } else if (!strcmp(argv[i], "--compact-empty-elem-tags")) {
      param_compact_empty_elm_tags = 1;
    } else if (!strcmp(argv[i], "--empty-elm-tags-always")) {
      param_empty_tags = 1;
    } else if (!strcmp(argv[i], "--dos-eol")) {
      param_crlf_eol = 1;
    } else if (!fich && argv[i][0]!='-') {
      fich = 1;
      param_inputf = fopen(argv[i], "r");
      if (!param_inputf) {
	perror("fopen");
	EXIT("Could not open the input file for reading");
      }
    } else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
      help();
      exit(0);
    } else if (!strcmp(argv[i], "--version") || !strcmp(argv[i], "-v")) {
      print_version();
      exit(0);
    } else if (!strcmp(argv[i], "-L")) {
      print_doctype_keys();
      exit(0);
    } else if (!strcmp(argv[i], "--ics") && ((i+1) < argc)) {
      param_charset_in = charset_lookup_alias(argv[++i]);
      if (!param_charset_in) {
	EPRINTF1("Trying to set input character set: %s\n", argv[i]);
	EXIT("Unsupported character set");
      }
    } else if (!strcmp(argv[i], "--ocs") && ((i+1) < argc)) {
      param_charset_out = charset_lookup_alias(argv[++i]);
      if (!param_charset_out) {
	EPRINTF1("Trying to set output character set: %s\n", argv[i]);
	EXIT("Unsupported character set");
      }
    } else if (!strcmp(argv[i], "--lcs")) {
      charset_dump_aliases(stdout);
      exit(0);
    } else if (!strcmp(argv[i], "--generate-snippet")) {
      param_generate_snippet = 1;
    } else {
      help();
      exit(1);
    }
  } 
}
Beispiel #18
0
NTSTATUS
t1394Cmdr_SystemSetPowerIrpCompletion(
    IN PDEVICE_OBJECT   DeviceObject,
    IN PIRP             Irp,
    IN PVOID            NotUsed
    )
{

    PDEVICE_EXTENSION           deviceExtension     = DeviceObject->DeviceExtension;
    NTSTATUS                    ntStatus            = Irp->IoStatus.Status;
    PIO_STACK_LOCATION          stack               = IoGetCurrentIrpStackLocation(Irp);
    POWER_STATE                 state               = stack->Parameters.Power.State;
    POWER_COMPLETION_CONTEXT    *powerContext       = NULL;
    PIRP                        pDIrp               = NULL;

    ENTER("t1394Cmdr_SystemPowerIrpCompletion");

    if (!NT_SUCCESS(ntStatus)) {

        TRACE(TL_TRACE, ("Set System Power Irp failed, status = 0x%x\n", ntStatus));
        PoStartNextPowerIrp(Irp);
        ntStatus = STATUS_SUCCESS;
        goto Exit_SystemSetPowerIrpCompletion;
    }

    // allocate powerContext
    powerContext = (POWER_COMPLETION_CONTEXT*)
                ExAllocatePool(NonPagedPool, sizeof(POWER_COMPLETION_CONTEXT));

    if (!powerContext) {

        TRACE(TL_TRACE, ("Failed to allocate powerContext, status = 0x%x\n", ntStatus));
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;
        goto Exit_SystemSetPowerIrpCompletion;

    } else {

        if (state.SystemState == PowerSystemWorking) {

            state.DeviceState = PowerDeviceD0;
        }
        else {
                    
            state.DeviceState = PowerDeviceD3;
        }
        
        powerContext->DeviceObject = DeviceObject;
        powerContext->SIrp = Irp;
        
        ntStatus = PoRequestPowerIrp(deviceExtension->StackDeviceObject,
                                    IRP_MN_SET_POWER,
                                    state,
                                    t1394Cmdr_DeviceSetPowerIrpCompletion,
                                    powerContext,
                                    &pDIrp);
        
        TRACE(TL_TRACE, ("New Device Set Power Irp = 0x%x\n", pDIrp));
    }

Exit_SystemSetPowerIrpCompletion:

    if (!NT_SUCCESS(ntStatus)) {


        TRACE(TL_TRACE, ("System SetPowerIrp Completion routine failed = 0x%x\n", ntStatus));

        if (powerContext) {
            ExFreePool(powerContext);
        }

        PoStartNextPowerIrp(Irp);
        Irp->IoStatus.Status = ntStatus;
    }
    else
    {
        ntStatus = STATUS_MORE_PROCESSING_REQUIRED;
    }

    EXIT("t1394Cmdr_SystemPowerIrpCompletion", ntStatus);    
    return ntStatus;
}
Beispiel #19
0
Window::Window(int width, int height, bool enableVsync)
    :m_window(nullptr), m_context(nullptr), m_width(width), m_height(height)
{
    if(!init(enableVsync))
        EXIT("Window initialization failed.");    
}
Beispiel #20
0
VOID
t1394Cmdr_DeviceSetPowerIrpCompletion(
    PDEVICE_OBJECT DeviceObject,
    UCHAR MinorFunction,
    POWER_STATE state,
    POWER_COMPLETION_CONTEXT* PowerContext,
    PIO_STATUS_BLOCK IoStatus
    )
{
    PDEVICE_EXTENSION   deviceExtension = (PDEVICE_EXTENSION) PowerContext->DeviceObject->DeviceExtension;
    PIRP                sIrp = PowerContext->SIrp;
    NTSTATUS            ntStatus = IoStatus->Status;

    ENTER("t1394Cmdr_DevicePowerIrpCompletion");

    if(!NT_SUCCESS(ntStatus))
    {
        TRACE(TL_WARNING, ("Device Power Irp failed by driver below us = 0x%x\n", ntStatus));
        goto Exit_t1394Cmdr_DeviceSetPowerIrpCompletion;
    }

    // set the new power state
    PoSetPowerState(DeviceObject, DevicePowerState, state);

    // figure out how to respond to this power state change
    if (state.DeviceState < deviceExtension->CurrentDevicePowerState)
    {
        // adding power
        // check to see if we are working again
        if (PowerDeviceD0 == state.DeviceState)
        {
            TRACE (TL_TRACE, ("Restarting our device\n"));
            deviceExtension->bShutdown = FALSE;
            
            // update the generation count                    
            t1394_GetGenerationCount(DeviceObject, NULL, &deviceExtension->GenerationCount);
        }
    }
    else
    {
        // removing power
        deviceExtension->bShutdown = TRUE;
    }
        
    // save the current device power state
    deviceExtension->CurrentDevicePowerState = state.DeviceState;

Exit_t1394Cmdr_DeviceSetPowerIrpCompletion:

    // Here we copy the D-IRP status into the S-IRP
    sIrp->IoStatus.Status = IoStatus->Status;

    // Release the IRP
    PoStartNextPowerIrp(sIrp);    
    sIrp->IoStatus.Information = 0;
    IoCompleteRequest(sIrp, IO_NO_INCREMENT);

    // Cleanup
    ExFreePool(PowerContext);
    
    EXIT("t1394Cmdr_DevicePowerIrpCompletion", ntStatus);
}
Beispiel #21
0
/*!
  \brief sets up and populates the MS2-Extra combo for output choice
  \param widget is the pointer to the combo to initialize
  */
G_MODULE_EXPORT void ms2_output_combo_setup(GtkWidget *widget)
{
	guint i = 0;
	GtkWidget *parent = NULL;
	gchar * lower = NULL;
	gchar * upper = NULL;
	gfloat * multiplier = NULL;
	gfloat * adder = NULL;
	gfloat * testmult = NULL;
	gchar * range = NULL;
	gint bitval = 0;
	gint width = 0;
	DataSize size = MTX_U08;
	gint precision = 0;
	gconstpointer * object = NULL;
	gint raw_lower = 0;
	gint raw_upper = 0;
	gboolean temp_dep = FALSE;
	gchar *raw_lower_str = NULL;
	gchar *raw_upper_str = NULL;
	gchar *tempc_range = NULL;
	gchar *tempf_range = NULL;
	gchar *tempk_range = NULL;
	gfloat real_lower = 0.0;
	gfloat real_upper = 0.0;
	gfloat tmpf = 0.0;
	gchar * name = NULL;
	gchar *internal_names = NULL;
	GtkWidget *entry = NULL;
	GtkEntryCompletion *completion = NULL;
	GtkListStore *store = NULL;
	GtkTreeIter iter;

	ENTER();
	Rtv_Map *rtv_map = NULL;

	rtv_map = (Rtv_Map *)DATA_GET(global_data,"rtv_map");

	if (!rtv_map)
	{
		EXIT();
		return;
	}
	/* Create the store for the combo, with severla hidden values
	*/
	store = gtk_list_store_new(UO_COMBO_COLS,
			G_TYPE_STRING,	/* Choice */
			G_TYPE_UCHAR,	/* BITval */
			G_TYPE_POINTER,	/* FromECU Multiplier (gfloat *) */
			G_TYPE_POINTER,	/* FromECU Adder (gfloat *) */
			G_TYPE_STRING,	/* Raw Lower clamp limit */
			G_TYPE_STRING,	/* Raw Upper clamp limit */
			G_TYPE_STRING,	/* Range widget string (non temp ctrls) */
			G_TYPE_STRING,	/* Range widget string (Celsius) */
			G_TYPE_STRING,	/* Range widget string (Fahrenheit) */
			G_TYPE_STRING,	/* Range widget string (Kelvin) */
			G_TYPE_INT,		/* Size enumeration (_U08_, _U16_, etc.) */
			G_TYPE_UCHAR,	/* Precision (floating point precision) */
			G_TYPE_BOOLEAN);/* Temp dependent flag */

	/* Iterate across valid variables */
	for (i=0;i<rtv_map->rtv_list->len;i++)
	{
		object = NULL;
		name = NULL;
		object = (gconstpointer *)g_ptr_array_index(rtv_map->rtv_list,i);
		if (!object)
			continue;
		name = (gchar *) DATA_GET(object,"dlog_gui_name");
		if (!name)
			continue;
		if (DATA_GET(object,"fromecu_complex"))
			continue;
		if (DATA_GET(object,"special"))
			continue;
		internal_names = (gchar *) DATA_GET(object,"internal_names");
		if (!find_in_list(rtv_map->raw_list,internal_names))
			continue;

		temp_dep = (GBOOLEAN)DATA_GET(object,"temp_dep");
		size = (DataSize)(GINT)DATA_GET(object,"size");
		multiplier = (gfloat *)DATA_GET(object,"fromecu_mult");
		adder = (gfloat *)DATA_GET(object,"fromecu_add");
		precision = (GINT) DATA_GET(object,"precision");
		bitval = (GINT) DATA_GET(object,"offset");
		if (DATA_GET(object,"real_lower"))
		{
			lower = (gchar *)DATA_GET(object,"real_lower");
			real_lower = g_strtod(lower,NULL);
			raw_lower = calc_value_f(real_lower,multiplier,adder,TOECU);
		}
		else
			raw_lower = get_extreme_from_size_f(size,LOWER);
		if (DATA_GET(object,"real_upper"))
		{
			upper = (gchar *)DATA_GET(object,"real_upper");
			real_upper = g_strtod(upper,NULL);
			raw_upper = calc_value_f(real_upper,multiplier,adder,TOECU);
		}
		else
			raw_upper = get_extreme_from_size_f(size,UPPER);

		range = g_strdup_printf("Valid Range: %.1f <-> %.1f",real_lower,real_upper);
		if (temp_dep)
		{
			tempc_range = g_strdup_printf("Valid Range: %.1f\302\260C <-> %.1f\302\260C",f_to_c_f(real_lower),f_to_c_f(real_upper));
			tempf_range = g_strdup_printf("Valid Range: %.1f\302\260F <-> %.1f\302\260F",real_lower,real_upper);
			tempk_range = g_strdup_printf("Valid Range: %.1f\302\260K <-> %.1f\302\260K",f_to_k_f(real_lower),f_to_k_f(real_upper));
		}
		else
		{
			tempc_range = g_strdup(range);
			tempf_range = g_strdup(range);
			tempk_range = g_strdup(range);
		}
		raw_lower_str = g_strdup_printf("%i",raw_lower);
		raw_upper_str = g_strdup_printf("%i",raw_upper);

		gtk_list_store_append(store,&iter);
		gtk_list_store_set(store,&iter,
				UO_CHOICE_COL,name,
				UO_BITVAL_COL,bitval,
				UO_FROMECU_MULT_COL,multiplier,
				UO_FROMECU_ADD_COL,adder,
				UO_RAW_LOWER_COL,raw_lower_str,
				UO_RAW_UPPER_COL,raw_upper_str,
				UO_RANGE_COL,range,
				UO_RANGE_TEMPC_COL,tempc_range,
				UO_RANGE_TEMPF_COL,tempf_range,
				UO_RANGE_TEMPK_COL,tempk_range,
				UO_SIZE_COL,size,
				UO_PRECISION_COL,precision,
				UO_TEMP_DEP_COL,temp_dep,
				-1);
		g_free(raw_lower_str);
		g_free(raw_upper_str);
		g_free(range);
		g_free(tempc_range);
		g_free(tempf_range);
		g_free(tempk_range);
	}
	if (GTK_IS_COMBO_BOX_ENTRY(widget))
	{
		gtk_combo_box_entry_set_text_column(GTK_COMBO_BOX_ENTRY(widget),UO_CHOICE_COL);
		gtk_combo_box_set_model(GTK_COMBO_BOX(widget),GTK_TREE_MODEL(store));
		g_object_unref(store);
		entry = gtk_bin_get_child(GTK_BIN(widget));
		/* Nasty hack, but otherwise the entry is an obnoxious size.. */
		if ((width = (GINT)OBJ_GET((GtkWidget *)widget,"max_chars")) > 0)
			gtk_entry_set_width_chars(GTK_ENTRY(entry),width);
		else
			gtk_entry_set_width_chars(GTK_ENTRY(entry),12);

		gtk_widget_set_size_request(GTK_WIDGET(widget),-1,(3*(GINT)DATA_GET(global_data,"font_size")));

		//		gtk_container_remove (GTK_CONTAINER (widget), gtk_bin_get_child(GTK_BIN(widget)));
		//		gtk_container_add (GTK_CONTAINER (widget), entry);

		completion = gtk_entry_completion_new();
		gtk_entry_set_completion(GTK_ENTRY(entry),completion);
		g_object_unref(completion);
		gtk_entry_completion_set_model(completion,GTK_TREE_MODEL(store));
		gtk_entry_completion_set_text_column(completion,UO_CHOICE_COL);
		gtk_entry_completion_set_inline_completion(completion,TRUE);
		gtk_entry_completion_set_inline_selection(completion,TRUE);
		gtk_entry_completion_set_popup_single_match(completion,FALSE);
		OBJ_SET(widget,"arrow-size",GINT_TO_POINTER(1));
	}
	EXIT();
	return;
}
Beispiel #22
0
NTSTATUS
t1394Cmdr_Power(
    IN PDEVICE_OBJECT   DeviceObject,
    IN PIRP             Irp
    )
{
    NTSTATUS                ntStatus = STATUS_SUCCESS;
    PIO_STACK_LOCATION      IrpSp;
    PDEVICE_EXTENSION       deviceExtension;
    POWER_STATE             State;
    KIRQL                   Irql;

    ENTER("t1394Cmdr_Power");

    deviceExtension = DeviceObject->DeviceExtension;

    IrpSp = IoGetCurrentIrpStackLocation(Irp);

    State = IrpSp->Parameters.Power.State;

    TRACE(TL_TRACE, ("Power.Type = 0x%x\n", IrpSp->Parameters.Power.Type));
    TRACE(TL_TRACE, ("Power.State.SystemState = 0x%x\n", State.SystemState));
    TRACE(TL_TRACE, ("Power.State.DeviceState = 0x%x\n", State.DeviceState));

    switch (IrpSp->MinorFunction) {

        case IRP_MN_SET_POWER:
            
            TRACE(TL_TRACE, ("IRP_MN_SET_POWER\n"));                        

            switch (IrpSp->Parameters.Power.Type) {

                case SystemPowerState:
                    TRACE(TL_TRACE, ("SystemPowerState\n"));
                    
                    // Send the IRP down
                    PoStartNextPowerIrp(Irp);
                    IoCopyCurrentIrpStackLocationToNext(Irp);
                    IoSetCompletionRoutine(Irp,
                        (PIO_COMPLETION_ROUTINE) t1394Cmdr_SystemSetPowerIrpCompletion,
                        NULL, TRUE, TRUE, TRUE);

                    ntStatus = PoCallDriver(deviceExtension->StackDeviceObject, Irp);
                    break;
                
                case DevicePowerState:
                    TRACE(TL_TRACE, ("DevicePowerState\n"));
                    TRACE(TL_TRACE, ("Current device state = 0x%x, new device state = 0x%x\n", 
                                     deviceExtension->CurrentDevicePowerState, State.DeviceState));

                    PoStartNextPowerIrp(Irp);
                    IoCopyCurrentIrpStackLocationToNext(Irp);
                    ntStatus = PoCallDriver(deviceExtension->StackDeviceObject, Irp);
                    break; // DevicePowerState

                default:
                    break;

            }
            break; // IRP_MN_SET_POWER

        case IRP_MN_QUERY_POWER:
            TRACE(TL_TRACE, ("IRP_MN_QUERY_POWER\n"));

            PoStartNextPowerIrp(Irp);
            IoSkipCurrentIrpStackLocation(Irp);
            ntStatus = PoCallDriver(deviceExtension->StackDeviceObject, Irp);

            break; // IRP_MN_QUERY_POWER

        default:
            TRACE(TL_TRACE, ("Default = 0x%x\n", IrpSp->MinorFunction));

            PoStartNextPowerIrp(Irp);
            IoSkipCurrentIrpStackLocation(Irp);
            ntStatus = PoCallDriver(deviceExtension->StackDeviceObject, Irp);

            break; // default
            
    } // switch

    EXIT("t1394Cmdr_Power", ntStatus);
    return(ntStatus);
} // t1394Cmdr_Power
Beispiel #23
0
int main(int argc, char *argv[])
{
    BN_GENCB _cb;
    DH *a;
    DH *b = NULL;
    char buf[12];
    unsigned char *abuf = NULL, *bbuf = NULL;
    int i, alen, blen, aout, bout, ret = 1;
    BIO *out;

    CRYPTO_malloc_debug_init();
    CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

# ifdef OPENSSL_SYS_WIN32
    CRYPTO_malloc_init();
# endif

    RAND_seed(rnd_seed, sizeof rnd_seed);

    out = BIO_new(BIO_s_file());
    if (out == NULL)
        EXIT(1);
    BIO_set_fp(out, stdout, BIO_NOCLOSE);

    BN_GENCB_set(&_cb, &cb, out);
    if (((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64,
                                                               DH_GENERATOR_5,
                                                               &_cb))
        goto err;

    if (!DH_check(a, &i))
        goto err;
    if (i & DH_CHECK_P_NOT_PRIME)
        BIO_puts(out, "p value is not prime\n");
    if (i & DH_CHECK_P_NOT_SAFE_PRIME)
        BIO_puts(out, "p value is not a safe prime\n");
    if (i & DH_UNABLE_TO_CHECK_GENERATOR)
        BIO_puts(out, "unable to check the generator value\n");
    if (i & DH_NOT_SUITABLE_GENERATOR)
        BIO_puts(out, "the g value is not a generator\n");

    BIO_puts(out, "\np    =");
    BN_print(out, a->p);
    BIO_puts(out, "\ng    =");
    BN_print(out, a->g);
    BIO_puts(out, "\n");

    b = DH_new();
    if (b == NULL)
        goto err;

    b->p = BN_dup(a->p);
    b->g = BN_dup(a->g);
    if ((b->p == NULL) || (b->g == NULL))
        goto err;

    /* Set a to run with normal modexp and b to use constant time */
    a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME;
    b->flags |= DH_FLAG_NO_EXP_CONSTTIME;

    if (!DH_generate_key(a))
        goto err;
    BIO_puts(out, "pri 1=");
    BN_print(out, a->priv_key);
    BIO_puts(out, "\npub 1=");
    BN_print(out, a->pub_key);
    BIO_puts(out, "\n");

    if (!DH_generate_key(b))
        goto err;
    BIO_puts(out, "pri 2=");
    BN_print(out, b->priv_key);
    BIO_puts(out, "\npub 2=");
    BN_print(out, b->pub_key);
    BIO_puts(out, "\n");

    alen = DH_size(a);
    abuf = (unsigned char *)OPENSSL_malloc(alen);
    aout = DH_compute_key(abuf, b->pub_key, a);

    BIO_puts(out, "key1 =");
    for (i = 0; i < aout; i++) {
        sprintf(buf, "%02X", abuf[i]);
        BIO_puts(out, buf);
    }
    BIO_puts(out, "\n");

    blen = DH_size(b);
    bbuf = (unsigned char *)OPENSSL_malloc(blen);
    bout = DH_compute_key(bbuf, a->pub_key, b);

    BIO_puts(out, "key2 =");
    for (i = 0; i < bout; i++) {
        sprintf(buf, "%02X", bbuf[i]);
        BIO_puts(out, buf);
    }
    BIO_puts(out, "\n");
    if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) {
        fprintf(stderr, "Error in DH routines\n");
        ret = 1;
    } else
        ret = 0;
    if (!run_rfc5114_tests())
        ret = 1;
 err:
    ERR_print_errors_fp(stderr);

    if (abuf != NULL)
        OPENSSL_free(abuf);
    if (bbuf != NULL)
        OPENSSL_free(bbuf);
    if (b != NULL)
        DH_free(b);
    if (a != NULL)
        DH_free(a);
    BIO_free(out);
# ifdef OPENSSL_SYS_NETWARE
    if (ret)
        printf("ERROR: %d\n", ret);
# endif
    EXIT(ret);
    return (ret);
}
Beispiel #24
0
int main(int Argc, char *ARGV[])
{
    ARGS arg;
#define PROG_NAME_SIZE	39
    char pname[PROG_NAME_SIZE+1];
    FUNCTION f,*fp;
    MS_STATIC const char *prompt;
    MS_STATIC char buf[1024];
    char *to_free=NULL;
    int n,i,ret=0;
    int argc;
    char **argv,*p;
    LHASH_OF(FUNCTION) *prog=NULL;
    long errline;

#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* 2011-03-22 SMS.
     * If we have 32-bit pointers everywhere, then we're safe, and
     * we bypass this mess, as on non-VMS systems.  (See ARGV,
     * above.)
     * Problem 1: Compaq/HP C before V7.3 always used 32-bit
     * pointers for argv[].
     * Fix 1: For a 32-bit argv[], when we're using 64-bit pointers
     * everywhere else, we always allocate and use a 64-bit
     * duplicate of argv[].
     * Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed
     * to NULL-terminate a 64-bit argv[].  (As this was written, the
     * compiler ECO was available only on IA64.)
     * Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a
     * 64-bit argv[argc] for NULL, and, if necessary, use a
     * (properly) NULL-terminated (64-bit) duplicate of argv[].
     * The same code is used in either case to duplicate argv[].
     * Some of these decisions could be handled in preprocessing,
     * but the code tends to get even uglier, and the penalty for
     * deciding at compile- or run-time is tiny.
     */
    char **Argv = NULL;
    int free_Argv = 0;

    if ((sizeof( _Argv) < 8)        /* 32-bit argv[]. */
# if !defined( VMS_TRUST_ARGV)
            || (_Argv[ Argc] != NULL)      /* Untrusted argv[argc] not NULL. */
# endif
       )
    {
        int i;
        Argv = OPENSSL_malloc( (Argc+ 1)* sizeof( char *));
        if (Argv == NULL)
        {
            ret = -1;
            goto end;
        }
        for(i = 0; i < Argc; i++)
            Argv[i] = _Argv[i];
        Argv[ Argc] = NULL;     /* Certain NULL termination. */
        free_Argv = 1;
    }
    else
    {
        /* Use the known-good 32-bit argv[] (which needs the
         * type cast to satisfy the compiler), or the trusted or
         * tested-good 64-bit argv[] as-is. */
        Argv = (char **)_Argv;
    }
#endif /* defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) */

    arg.data=NULL;
    arg.count=0;

    if (bio_err == NULL)
        if ((bio_err=BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

    if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
    {
        if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))
        {
            CRYPTO_malloc_debug_init();
            CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
        }
        else
        {
            /* OPENSSL_DEBUG_MEMORY=off */
            CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
        }
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
    if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
    {
        CRYPTO_set_locking_callback(lock_dbg_cb);
    }

    if(getenv("OPENSSL_FIPS")) {
#ifdef OPENSSL_FIPS
        if (!FIPS_mode_set(1)) {
            ERR_load_crypto_strings();
            ERR_print_errors(BIO_new_fp(stderr,BIO_NOCLOSE));
            EXIT(1);
        }
#else
        fprintf(stderr, "FIPS mode not supported.\n");
        EXIT(1);
#endif
    }

    apps_startup();

    /* Lets load up our environment a little */
    p=getenv("OPENSSL_CONF");
    if (p == NULL)
        p=getenv("SSLEAY_CONF");
    if (p == NULL)
        p=to_free=make_config_name();

    default_config_file=p;

    config=NCONF_new(NULL);
    i=NCONF_load(config,p,&errline);
    if (i == 0)
    {
        if (ERR_GET_REASON(ERR_peek_last_error())
                == CONF_R_NO_SUCH_FILE)
        {
#if 0 /* ANDROID */
            BIO_printf(bio_err,
                       "WARNING: can't open config file: %s\n",p);
#endif
            ERR_clear_error();
            NCONF_free(config);
            config = NULL;
        }
        else
        {
            ERR_print_errors(bio_err);
            NCONF_free(config);
            exit(1);
        }
    }

    prog=prog_init();

    /* first check the program name */
    program_name(Argv[0],pname,sizeof pname);

    f.name=pname;
    fp=lh_FUNCTION_retrieve(prog,&f);
    if (fp != NULL)
    {
        Argv[0]=pname;
        ret=fp->func(Argc,Argv);
        goto end;
    }

    /* ok, now check that there are not arguments, if there are,
     * run with them, shifting the ssleay off the front */
    if (Argc != 1)
    {
        Argc--;
        Argv++;
        ret=do_cmd(prog,Argc,Argv);
        if (ret < 0) ret=0;
        goto end;
    }

    /* ok, lets enter the old 'OpenSSL>' mode */

    for (;;)
    {
        ret=0;
        p=buf;
        n=sizeof buf;
        i=0;
        for (;;)
        {
            p[0]='\0';
            if (i++)
                prompt=">";
            else	prompt="OpenSSL> ";
            fputs(prompt,stdout);
            fflush(stdout);
            if (!fgets(p,n,stdin))
                goto end;
            if (p[0] == '\0') goto end;
            i=strlen(p);
            if (i <= 1) break;
            if (p[i-2] != '\\') break;
            i-=2;
            p+=i;
            n-=i;
        }
        if (!chopup_args(&arg,buf,&argc,&argv)) break;

        ret=do_cmd(prog,argc,argv);
        if (ret < 0)
        {
            ret=0;
            goto end;
        }
        if (ret != 0)
            BIO_printf(bio_err,"error in %s\n",argv[0]);
        (void)BIO_flush(bio_err);
    }
    BIO_printf(bio_err,"bad exit\n");
    ret=1;
end:
    if (to_free)
        OPENSSL_free(to_free);
    if (config != NULL)
    {
        NCONF_free(config);
        config=NULL;
    }
    if (prog != NULL) lh_FUNCTION_free(prog);
    if (arg.data != NULL) OPENSSL_free(arg.data);

    apps_shutdown();

    CRYPTO_mem_leaks(bio_err);
    if (bio_err != NULL)
    {
        BIO_free(bio_err);
        bio_err=NULL;
    }
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* Free any duplicate Argv[] storage. */
    if (free_Argv)
    {
        OPENSSL_free(Argv);
    }
#endif
    OPENSSL_EXIT(ret);
}
Beispiel #25
0
int main(int argc, char *argv[])
{
# ifndef OPENSSL_NO_MD5
    int i;
    char *p;
# endif
    int err = 0;
    HMAC_CTX ctx, ctx2;
    unsigned char buf[EVP_MAX_MD_SIZE];
    unsigned int len;

# ifdef OPENSSL_NO_MD5
    printf("test skipped: MD5 disabled\n");
# else

#  ifdef CHARSET_EBCDIC
    ebcdic2ascii(test[0].data, test[0].data, test[0].data_len);
    ebcdic2ascii(test[1].data, test[1].data, test[1].data_len);
    ebcdic2ascii(test[2].key, test[2].key, test[2].key_len);
    ebcdic2ascii(test[2].data, test[2].data, test[2].data_len);
#  endif

    for (i = 0; i < 4; i++) {
        p = pt(HMAC(EVP_md5(),
                    test[i].key, test[i].key_len,
                    test[i].data, test[i].data_len, NULL, NULL),
                    MD5_DIGEST_LENGTH);

        if (strcmp(p, (const char *)test[i].digest) != 0) {
            printf("Error calculating HMAC on %d entry'\n", i);
            printf("got %s instead of %s\n", p, test[i].digest);
            err++;
        } else
            printf("test %d ok\n", i);
    }
# endif                         /* OPENSSL_NO_MD5 */

/* test4 */
    HMAC_CTX_init(&ctx);
    if (HMAC_Init_ex(&ctx, NULL, 0, NULL, NULL)) {
        printf("Should fail to initialise HMAC with empty MD and key (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Update(&ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Init_ex(&ctx, NULL, 0, EVP_sha1(), NULL)) {
        printf("Should fail to initialise HMAC with empty key (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Update(&ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 4)\n");
        err++;
        goto test5;
    }
    printf("test 4 ok\n");
test5:
    HMAC_CTX_cleanup(&ctx);
    HMAC_CTX_init(&ctx);
    if (HMAC_Init_ex(&ctx, test[4].key, test[4].key_len, NULL, NULL)) {
        printf("Should fail to initialise HMAC with empty MD (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_Update(&ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_Init_ex(&ctx, test[4].key, -1, EVP_sha1(), NULL)) {
        printf("Should fail to initialise HMAC with invalid key len(test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(&ctx, test[4].key, test[4].key_len, EVP_sha1(), NULL)) {
        printf("Failed to initialise HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(&ctx, test[4].data, test[4].data_len)) {
        printf("Error updating HMAC with data (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(&ctx, buf, &len)) {
        printf("Error finalising data (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (const char *)test[4].digest) != 0) {
        printf("Error calculating interim HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[4].digest);
        err++;
        goto test6;
    }
    if (HMAC_Init_ex(&ctx, NULL, 0, EVP_sha256(), NULL)) {
        printf("Should disallow changing MD without a new key (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(&ctx, test[4].key, test[4].key_len, EVP_sha256(), NULL)) {
        printf("Failed to reinitialise HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(&ctx, test[5].data, test[5].data_len)) {
        printf("Error updating HMAC with data (sha256) (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(&ctx, buf, &len)) {
        printf("Error finalising data (sha256) (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (const char *)test[5].digest) != 0) {
        printf("Error calculating 2nd interim HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[5].digest);
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(&ctx, test[6].key, test[6].key_len, NULL, NULL)) {
        printf("Failed to reinitialise HMAC with key (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(&ctx, test[6].data, test[6].data_len)) {
        printf("Error updating HMAC with data (new key) (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(&ctx, buf, &len)) {
        printf("Error finalising data (new key) (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (const char *)test[6].digest) != 0) {
        printf("error calculating HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[6].digest);
        err++;
    } else {
        printf("test 5 ok\n");
    }
test6:
    HMAC_CTX_cleanup(&ctx);
    HMAC_CTX_init(&ctx);
    if (!HMAC_Init_ex(&ctx, test[7].key, test[7].key_len, EVP_sha1(), NULL)) {
        printf("Failed to initialise HMAC (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_Update(&ctx, test[7].data, test[7].data_len)) {
        printf("Error updating HMAC with data (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_CTX_copy(&ctx2, &ctx)) {
        printf("Failed to copy HMAC_CTX (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_Final(&ctx2, buf, &len)) {
        printf("Error finalising data (test 6)\n");
        err++;
        goto end;
    }
    p = pt(buf, len);
    if (strcmp(p, (const char *)test[7].digest) != 0) {
        printf("Error calculating HMAC on test 6\n");
        printf("got %s instead of %s\n", p, test[7].digest);
        err++;
    } else {
        printf("test 6 ok\n");
    }
end:
    HMAC_CTX_cleanup(&ctx);
    EXIT(err);
    return (0);
}
CallbackPipeline::~CallbackPipeline() {
	ENTER();

	EXIT();
}
/*!
 * Receive message from queue (global or from own thread message queue)
 */
int sys__msg_recv ( int src_type, void *src, msg_t *msg, int type, size_t size,
		    uint flags )
{
	kthread_t *kthr;
	kthrmsg_qs *thrmsg;
	kgmsg_q *kgmsgq;
	kmsg_q *kmsgq;
	msg_q *msgq;
	kmsg_t *kmsg;

	ASSERT_ERRNO_AND_EXIT ( src && msg, E_INVALID_HANDLE );
	ASSERT_ERRNO_AND_EXIT ( src_type == MSG_THREAD || src_type == MSG_QUEUE,
				E_INVALID_TYPE );

	if ( src_type == MSG_THREAD )
	{
		kthr = k_get_active_thread ();
		thrmsg = k_get_thrmsg ( kthr );
		kmsgq = &thrmsg->msgq;
	}
	else { /* src_type == MSG_QUEUE */
		msgq = src;
		kgmsgq = msgq->handle;
		ASSERT_ERRNO_AND_EXIT ( kgmsgq && kgmsgq->id == msgq->id,
					E_INVALID_HANDLE );
		kmsgq = &kgmsgq->mq;
	}

	/* get first message from queue */
	kmsg = list_get ( &kmsgq->msgs, FIRST );

	if ( type != 0 ) /* type != 0 => search for first message 'type' */
		while ( kmsg && kmsg->msg.type != type )
			kmsg = list_get_next ( &kmsg->list );

	if ( kmsg ) /* have message */
	{
		if ( size < kmsg->msg.size )
		{
			msg->size = 0;
			EXIT ( E_TOO_BIG );
		}

		msg->type = kmsg->msg.type;
		msg->size = kmsg->msg.size;
		memcpy ( msg->data, kmsg->msg.data, msg->size );

		kmsg = list_remove ( &kmsgq->msgs, FIRST, &kmsg->list );
		ASSERT ( kmsg );
		kfree ( kmsg );

		EXIT ( SUCCESS );
	}
	else { /* queue empty! */
		if ( !( flags & IPC_WAIT ) )
			EXIT ( E_EMPTY );

		SET_ERRNO ( E_RETRY );
		/* block thread */
		k_enqueue_thread ( NULL, &kmsgq->thrq );

		k_schedule_threads ();

		RETURN ( E_RETRY );
	}
}
int main(int argc, char ** argv)
{
    SETLOGMASK();

    {
    	TEST();

        ASSERT(diminuto_shaper_bursttolerance(2, 3, 7, 5) == 23);
        ASSERT(diminuto_shaper_bursttolerance(2, 0, 7, 5) == 20);
        ASSERT(diminuto_shaper_bursttolerance(0, 0, 2, 5) == 8);
        ASSERT(diminuto_shaper_bursttolerance(7, 3, 7, 5) == 3);
        ASSERT(diminuto_shaper_bursttolerance(2, 3, 7, 1) == 3);
        ASSERT(diminuto_shaper_bursttolerance(2, 3, 7, 0) == 3);

    	STATUS();
    }

    {
        static const size_t PEAK = 2048;
        static const diminuto_ticks_t TOLERANCE = 0;
        static const size_t SUSTAINED = 1024;
        static const size_t BURST = 512;
        static const size_t OPERATIONS = 1000000;
        diminuto_shaper_t shaper;
        diminuto_shaper_t * sp;
        size_t size = 0;
        diminuto_ticks_t now = 0;
        diminuto_ticks_t delay;
        size_t iops;
        int admissable;
        uint64_t total = 0;
        diminuto_ticks_t duration = 0;
        double peak = 0.0;
        double sustained;
        double rate;
        diminuto_ticks_t frequency;
    	diminuto_ticks_t peakincrement;
    	diminuto_ticks_t jittertolerance;
    	diminuto_ticks_t sustainedincrement;
    	diminuto_ticks_t bursttolerance;
    	/**/
        frequency = diminuto_frequency();
        /**/
		peakincrement = diminuto_throttle_interarrivaltime(PEAK, 1, frequency);
		jittertolerance = diminuto_throttle_jittertolerance(peakincrement, BURST) + TOLERANCE;
		sustainedincrement = diminuto_throttle_interarrivaltime(SUSTAINED, 1, frequency);
		bursttolerance = diminuto_shaper_bursttolerance(peakincrement, jittertolerance, sustainedincrement, BURST);
		/**/
		sp = diminuto_shaper_init(&shaper, peakincrement, 0 /* jittertolerance */, sustainedincrement, bursttolerance, now);
        ASSERT(sp == &shaper);
        diminuto_shaper_log(sp);
        srand(diminuto_time_clock());
        /**/
        for (iops = 0; iops < OPERATIONS; ++iops) {
            delay = diminuto_shaper_request(sp, now);
            ASSERT(delay >= 0);
            now += delay;
            duration += delay;
            if (iops <= 0) {
            	/* Do nothing. */
            } else if (delay <= 0) {
            	/* Do nothing. */
            } else {
				rate = size;
				rate *= frequency;
				rate /= delay;
				if (rate > peak) { peak = rate; }
            }
            delay = diminuto_shaper_request(sp, now);
            ASSERT(delay == 0);
            size = blocksize(BURST);
            ASSERT(size > 0);
            ASSERT(size <= BURST);
            total += size;
            admissable = !diminuto_shaper_commitn(sp, size);
            ASSERT(admissable);
        }
        /**/
        delay = diminuto_shaper_getexpected(sp);
        ASSERT(delay >= 0);
        now += delay;
        duration += delay;
        if (delay > 0) {
			rate = size;
			rate *= frequency;
			rate /= delay;
			if (rate > peak) { peak = rate; }
        }
        diminuto_shaper_update(sp, now);
        /**/
        ASSERT(total > 0);
        ASSERT(duration > frequency);
        diminuto_shaper_log(sp);
        sustained = total;
        sustained *= frequency;
        sustained /= duration;
        DIMINUTO_LOG_DEBUG("operations=%zu total=%llubytes average=%llubytes duration=%lldseconds peak=%zubytes/second measured=%lfbytes/second sustained=%zubytes/second measured=%lfdbytes/second\n", iops, total, total / iops, duration / diminuto_frequency(), PEAK, peak, SUSTAINED, sustained);
        ASSERT(fabs(sustained - SUSTAINED) < (SUSTAINED / 200) /* 0.5% */);
        ADVISE(fabs(peak - PEAK) < (PEAK / 200) /* 0.5% */);
     }

    EXIT();
}
Beispiel #29
0
static isc_result_t
process_request(isc_httpd_t *httpd, int length)
{
	char *s;
	char *p;
	int delim;

	ENTER("request");

	httpd->recvlen += length;

	httpd->recvbuf[httpd->recvlen] = 0;

	/*
	 * If we don't find a blank line in our buffer, return that we need
	 * more data.
	 */
	s = strstr(httpd->recvbuf, "\r\n\r\n");
	delim = 1;
	if (s == NULL) {
		s = strstr(httpd->recvbuf, "\n\n");
		delim = 2;
	}
	if (s == NULL)
		return (ISC_R_NOTFOUND);

	/*
	 * Determine if this is a POST or GET method.  Any other values will
	 * cause an error to be returned.
	 */
	if (strncmp(httpd->recvbuf, "GET ", 4) == 0) {
		httpd->method = ISC_HTTPD_METHODGET;
		p = httpd->recvbuf + 4;
	} else if (strncmp(httpd->recvbuf, "POST ", 5) == 0) {
		httpd->method = ISC_HTTPD_METHODPOST;
		p = httpd->recvbuf + 5;
	} else {
		return (ISC_R_RANGE);
	}

	/*
	 * From now on, p is the start of our buffer.
	 */

	/*
	 * Extract the URL.
	 */
	s = p;
	while (LENGTHOK(s) && BUFLENOK(s) &&
	       (*s != '\n' && *s != '\r' && *s != '\0' && *s != ' '))
		s++;
	if (!LENGTHOK(s))
		return (ISC_R_NOTFOUND);
	if (!BUFLENOK(s))
		return (ISC_R_NOMEMORY);
	*s = 0;

	/*
	 * Make the URL relative.
	 */
	if ((strncmp(p, "http:/", 6) == 0)
	    || (strncmp(p, "https:/", 7) == 0)) {
		/* Skip first / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0)
			return (ISC_R_RANGE);
		p++;
		/* Skip second / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0)
			return (ISC_R_RANGE);
		p++;
		/* Find third / */
		while (*p != '/' && *p != 0)
			p++;
		if (*p == 0) {
			p--;
			*p = '/';
		}
	}

	httpd->url = p;
	p = s + delim;
	s = p;

	/*
	 * Now, see if there is a ? mark in the URL.  If so, this is
	 * part of the query string, and we will split it from the URL.
	 */
	httpd->querystring = strchr(httpd->url, '?');
	if (httpd->querystring != NULL) {
		*(httpd->querystring) = 0;
		httpd->querystring++;
	}

	/*
	 * Extract the HTTP/1.X protocol.  We will bounce on anything but
	 * HTTP/1.1 for now.
	 */
	while (LENGTHOK(s) && BUFLENOK(s) &&
	       (*s != '\n' && *s != '\r' && *s != '\0'))
		s++;
	if (!LENGTHOK(s))
		return (ISC_R_NOTFOUND);
	if (!BUFLENOK(s))
		return (ISC_R_NOMEMORY);
	*s = 0;
	if ((strncmp(p, "HTTP/1.0", 8) != 0)
	    && (strncmp(p, "HTTP/1.1", 8) != 0))
		return (ISC_R_RANGE);
	httpd->protocol = p;
	p = s + 1;
	s = p;

	if (strstr(s, "Connection: close") != NULL)
		httpd->flags |= HTTPD_CLOSE;

	if (strstr(s, "Host: ") != NULL)
		httpd->flags |= HTTPD_FOUNDHOST;

	/*
	 * Standards compliance hooks here.
	 */
	if (strcmp(httpd->protocol, "HTTP/1.1") == 0
	    && ((httpd->flags & HTTPD_FOUNDHOST) == 0))
		return (ISC_R_RANGE);

	EXIT("request");

	return (ISC_R_SUCCESS);
}
NTSTATUS
kmdf1394_SetAddressData (
                         IN WDFDEVICE Device,
                         IN WDFREQUEST Request,
                         IN PSET_ADDRESS_DATA SetAddrData)
/*++

Routine Description:

    Set Address Range routine.

Arguments:

    Device - the current WDFDEVICE Object.

    Request - the current request.

    SetAddrData - the Data buffer from usermode to be worked on.

Return Value:

    VOID
--*/
{
    NTSTATUS ntStatus = STATUS_SUCCESS;
    PDEVICE_EXTENSION  deviceExtension = GetDeviceContext(Device);
    PASYNC_ADDRESS_DATA AsyncAddressData = NULL;
    PLIST_ENTRY listHead, thisEntry;

    UNREFERENCED_PARAMETER(Request);

    ENTER("kmdf1394_SetAddressData");

    //
    // have to find our struct...
    //
    WdfSpinLockAcquire(deviceExtension->AsyncSpinLock);

    listHead = &deviceExtension->AsyncAddressData;

    for(thisEntry = listHead->Flink; thisEntry != listHead;
        AsyncAddressData = NULL, thisEntry = thisEntry->Flink)
    {
        AsyncAddressData = CONTAINING_RECORD(
            thisEntry, 
            ASYNC_ADDRESS_DATA,
            AsyncAddressList);
        if (AsyncAddressData->hAddressRange == SetAddrData->hAddressRange) 
        {
            PULONG  pBuffer;

            // 
            // found it, let's copy over the contents from data...
            //
            pBuffer = \
                (PULONG)((ULONG_PTR)AsyncAddressData->Buffer + \
                SetAddrData->ulOffset);

            TRACE(TL_TRACE, ("pBuffer = 0x%x\n", pBuffer));
            TRACE(TL_TRACE, ("Data = 0x%x\n", SetAddrData->Data));

            if(pBuffer && SetAddrData->Data) 
            {
                RtlCopyMemory(pBuffer, SetAddrData->Data, SetAddrData->nLength);
            }
            break;
        }
    }

    WdfSpinLockRelease(deviceExtension->AsyncSpinLock);

    // 
    // never found an entry...
    //
    if (!AsyncAddressData) 
    {
        ntStatus = STATUS_INVALID_PARAMETER;
    }

    EXIT("kmdf1394_SetAddressData", ntStatus);
    return ntStatus;
} // kmdf1394_SetAddressData