Exemple #1
0
const std::string& ArgumentVector::Argument::get(std::string& dst) const {
	if (type != Argument::STRING)
		printd(WARNING, "Argument::get(): WARNING: conversion from non-string to string type!\n");
	dst = *((std::string*)value);
	return dst;
} // get
Exemple #2
0
// NOTE: we do not cleanup in reverse initialization order
// the threading subsystem is deleted before the modules are
// unloaded in case there are any module-specific thread
// cleanup functions to be run...
void qore_cleanup() {
   // first delete all user modules
   QMM.delUser();

#ifdef _Q_WINDOWS 
   // do windows socket cleanup
   WSACleanup();
#endif

#ifdef HAVE_SIGNAL_HANDLING
   // stop signal manager
   QSM.del();
#endif

   // purge thread resources before deleting modules
   {
      ExceptionSink xsink;
      purge_thread_resources(&xsink);
   }

   // delete all loadable modules
   QMM.cleanup();

   // delete thread-local data
   delete_thread_local_data();

   // now free memory (like ARGV, QORE_ARGV, ENV, etc)
   delete_global_variables();

   // delete pseudo-methods
   pseudo_classes_del();

   // delete static system namespace after modules
   delete staticSystemNamespace;
#ifdef DEBUG
   staticSystemNamespace = 0;
#endif

   // delete default type values
   delete_qore_types();

   // delete threading infrastructure
   delete_qore_threads();

   // only perform openssl cleanup if not performed externally
   if (!qore_check_option(QLO_DISABLE_OPENSSL_CLEANUP)) {
      // cleanup openssl library
      ERR_free_strings();

      ENGINE_cleanup();
      EVP_cleanup();

      CONF_modules_finish();
      CONF_modules_free();
      CONF_modules_unload(1);

      CRYPTO_cleanup_all_ex_data();

      CRYPTO_set_id_callback(0);
      CRYPTO_set_locking_callback(0);

      // delete openssl locks
      for (mutex_vec_t::iterator i = q_openssl_mutex_list.begin(), e = q_openssl_mutex_list.end(); i != e; ++i)
	 delete *i;
   }
   printd(5, "qore_cleanup() exiting cleanly\n");
}
Exemple #3
0
int qore_number_private::formatNumberString(QoreString& num, const QoreString& fmt, ExceptionSink* xsink) {
   assert(!num.empty());
   assert(num.getEncoding() == fmt.getEncoding());
   // get the length of the format string in characters (not bytes)
   qore_size_t fl = fmt.length();
   if (fmt.empty() || fl == 2) {
      printd(5, "qore_number_private::formatNumberString() invalid format string: '%s' for number: '%s'\n", fmt.getBuffer(), num.getBuffer());
      return 0;
   }

   // get thousands separator character
   QoreString tsep;
   if (tsep.concat(fmt, 0, 1, xsink))
      return -1;

   // decimal separator
   QoreString dsep;
   // number of digits after the decimal separator
   unsigned prec = 0;
   if (fl > 1) {
      if (dsep.concat(fmt, 1, 1, xsink))
         return -1;
      // get byte offset of start of decimal precision number
      qore_offset_t i = fmt.getByteOffset(2, xsink);
      if (*xsink)
         return -1;
      assert(i >= 2);
      prec = atoi(fmt.getBuffer() + i);
      if (!prec)
         dsep.clear();
   }

   //printd(5, "qore_number_private::formatNumberString() tsep: '%s' dsep: '%s' prec: %d '%s'\n", tsep.getBuffer(), dsep.getBuffer(), prec, num.getBuffer());

   // find decimal point
   qore_offset_t dp = num.find('.');
   if (dp != -1) {
      // how many digits do we have now after the decimal point
      qore_size_t d = num.strlen() - dp - 1;
      assert(d);
      if (d < prec)
         num.addch('0', prec - d);
      else if (d > prec) {
         if ((num[dp + prec + 1] > '4') && (roundUp(num, dp + prec)))
            ++dp;
         num.terminate(dp + prec + 1);
      }
      // now substitute decimal point if necessary
      if (dsep.strlen() != 1 || dsep[0] != '.')
         num.replace(dp, 1, dsep.getBuffer());
   }
   else {
      dp = num.size();
      if (prec) {
         // add decimal point
         num.concat(&dsep, xsink);
         assert(!*xsink);
         // add zeros for significant digits
         num.addch('0', prec);
      }
   }

   // now insert thousands separator
   // start of digits before the decimal point
   qore_offset_t ds = num[0] == '-' ? 1 : 0;

   // work backwards from the decimal point
   qore_offset_t i = dp - 3;
   while (i > ds) {
      num.replace(i, 0, tsep.getBuffer());
      i -= 3;
   }

   //printd(0, "qore_number_private::formatNumberString() ok '%s'\n", num.getBuffer());

   //assert(false); xxx
   return 0;
}
Exemple #4
0
void *rcvr_thread(void* arg)
{	
	rcvr(fd, msglen, interval, nmsg);
	printd(lostmsgs ? "lost messages" : "");
	return 0;
}
Exemple #5
0
int main()

{
  printd(-123);
  return 0;
}
Exemple #6
0
void process_line(struct ast_node_line* line)
{
    struct instruction_mapping* insttype;
    struct process_parameters_results ppresults;
    struct process_parameter_results dparam;
    struct ast_node_parameter* dcurrent;
    uint32_t dchrproc;
    uint16_t i, flimit, fchar, opos;
    struct aout_byte* result = NULL;
    struct dbg_sym* newsym;

    // Change depending on the type of line.
    switch (line->type)
    {
        case type_keyword:
            switch (line->keyword)
            {
                case SYMBOL:
                    printd(LEVEL_VERBOSE, ".SYMBOL %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit debugging symbol.
                    list_append(&newsyms, dbgfmt_create_symbol(DBGFMT_SYMBOL_STRING, dbgfmt_create_symbol_string(line->keyword_data_string, DBGFMT_UNDETERMINED)));

                    break;

                case SECTION:
                    printd(LEVEL_VERBOSE, ".SECTION %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit section metadata.
                    aout_emit(aout_create_metadata_section(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case OUTPUT:
                    printd(LEVEL_VERBOSE, ".OUTPUT %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit output metadata.
                    aout_emit(aout_create_metadata_output(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case BOUNDARY:
                    printd(LEVEL_VERBOSE, ".BOUNDARY");

                    // Emit safety boundary of 16 NULL words.
                    for (i = 0; i < 16; i += 1)
                        aout_emit(aout_create_raw(0));

                    break;

                case FILL:
                    printd(LEVEL_VERBOSE, ".FILL");

                    if (line->keyword_data_expr_1 == NULL || line->keyword_data_expr_2 == NULL)
                    {
                        if (line->keyword_data_string != NULL)
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, line->keyword_data_string->data);
                        else
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, "");
                    }

                    // Emit N words with value X
                    flimit = expr_evaluate(line->keyword_data_expr_1, &dhalt_label_resolution_not_permitted, &dhalt_expression_exit_handler);
                    fchar = expr_evaluate(line->keyword_data_expr_2, &dhalt_label_resolution_not_permitted, &dhalt_expression_exit_handler);
                    for (i = 0; i < flimit; i++)
                        aout_emit(aout_create_raw(fchar));

                    break;

                case EXTENSION:
                    printd(LEVEL_VERBOSE, ".EXTENSION %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit extension metadata.
                    aout_emit(aout_create_metadata_extension(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case INCBIN:
                    printd(LEVEL_VERBOSE, ".INCBIN %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit binary include metadata.
                    aout_emit(aout_create_metadata_incbin(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case ORIGIN:
                    if (line->keyword_data_expr_1 == NULL)
                    {
                        if (line->keyword_data_string != NULL)
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, line->keyword_data_string->data);
                        else
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, "");
                    }

                    opos = expr_evaluate(line->keyword_data_expr_1, &dhalt_label_resolution_not_permitted, &dhalt_expression_exit_handler);
                    printd(LEVEL_VERBOSE, ".ORIGIN 0x%04X", opos);

                    // Emit origin set metadata.
                    aout_emit(aout_create_metadata_origin(opos));

                    break;

                case SEEK:
                    if (line->keyword_data_expr_1 == NULL)
                    {
                        if (line->keyword_data_string != NULL)
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, line->keyword_data_string->data);
                        else
                            dhalt(ERR_LABEL_RESOLUTION_NOT_PERMITTED, "");
                    }

                    opos = expr_evaluate(line->keyword_data_expr_1, &dhalt_label_resolution_not_permitted, &dhalt_expression_exit_handler);
                    printd(LEVEL_VERBOSE, ".SEEK 0x%04X", opos);

                    // Emit seek metadata.
                    aout_emit(aout_create_metadata_seek(opos));

                    break;

                case EXPORT:
                    printd(LEVEL_VERBOSE, ".EXPORT %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit export metadata.
                    aout_emit(aout_create_metadata_export(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case IMPORT:
                    printd(LEVEL_VERBOSE, ".IMPORT %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit import metadata.
                    aout_emit(aout_create_metadata_import(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case IMPORT_OPTIONAL:
                    printd(LEVEL_VERBOSE, ".IMPORT OPTIONAL %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit import metadata.
                    aout_emit(aout_create_metadata_import_optional(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                case JUMP:
                    if (line->keyword_data_string == NULL)
                        printd(LEVEL_VERBOSE, ".JUMP <table>");
                    else
                        printd(LEVEL_VERBOSE, ".JUMP %s", bstr2cstr(line->keyword_data_string, '0'));

                    // Emit jump metadata.
                    if (line->keyword_data_string == NULL)
                        aout_emit(aout_create_metadata_jump(NULL));
                    else
                        aout_emit(aout_create_metadata_jump(bstr2cstr(line->keyword_data_string, '0')));

                    break;

                default:
                    printd(LEVEL_VERBOSE, "?? UNKNOWN KEYWORD\n");
                    dhalt(ERR_UNSUPPORTED_KEYWORD, NULL);
            }

            printd(LEVEL_VERBOSE, "\n");
            break;

        case type_instruction:

            // Check to see if this is DAT.
            if (strcmp(line->instruction->instruction, "DAT") == 0)
            {
                // Handle data.
                printd(LEVEL_VERBOSE, "EMIT DAT");

                // Process parameters as data.
                reverse_parameters(line->instruction->parameters);
                dcurrent = line->instruction->parameters->last;

                while (dcurrent != NULL)
                {
                    // Process parameter normally.
                    dparam = process_parameter(dcurrent);

                    // Output depending on what kind of parameter it was.
                    if (dparam.v_label != NULL) // If this is a label, output something that we need to replace.
                        aout_emit(aout_create_expr(expr_new_label(bautofree(bfromcstr(dparam.v_label)))));
                    else if (dparam.v_raw != NULL) // If the raw field is not null, get each character and output it.
                    {
                        printd(LEVEL_VERBOSE, " \"%s\"", dparam.v_raw->data);

                        for (dchrproc = 0; dchrproc < (uint32_t)blength(dparam.v_raw); dchrproc++)
                            aout_emit(aout_create_raw(dparam.v_raw->data[dchrproc]));
                    }
                    else if (dparam.v_extra_used == true) // Just a single address.
                        aout_emit(aout_create_expr(dparam.v_extra));
                    else // Something that isn't handled by DAT.
                    {
                        printd(LEVEL_VERBOSE, "\n");
                        dhalt(ERR_DAT_UNSUPPORTED_PARAMETER, NULL);
                    }

                    dcurrent = dcurrent->prev;
                }
            }
            else
            {
                // Handle instruction.
                insttype = get_instruction_by_name(line->instruction->instruction);

                if (insttype == NULL)
                    dhalt(ERR_UNKNOWN_OPCODE, line->instruction->instruction);

                printd(LEVEL_VERBOSE, "EMIT %s", insttype->name);

                // Check parameter count.
                if (line->instruction->parameters == NULL && strcmp(line->instruction->instruction, "RFI") == 0)
                {
                    // Handle RFI (which can accept no parameters).
                    result = aout_emit(aout_create_opcode(insttype->opcode, insttype->nbopcode, 0x21 /* 0 literal */));
                    printd(LEVEL_VERBOSE, "\n");
                    break;
                }
                else if (line->instruction->parameters == NULL)
                {
                    // Halt and error.
                    dhalt(ERR_INVALID_PARAMETER_COUNT, NULL);
                }

                // Process parameters normally.
                ppresults = process_parameters(line->instruction->parameters);

                // Force the parameter value to be NXT if it's a label.
                if (ppresults.a_label != NULL) ppresults.a = NXT_LIT;
                if (ppresults.b_label != NULL) ppresults.b = NXT_LIT;
                if (ppresults.a_label != NULL && ppresults.a_label_bracketed) ppresults.a = NXT;
                if (ppresults.b_label != NULL && ppresults.b_label_bracketed) ppresults.b = NXT;

                // Check for relative addressing.
                if ((insttype->opcode == OP_ADD || insttype->opcode == OP_SUB ||
                        insttype->opcode == OP_MUL || insttype->opcode == OP_DIV) && ppresults.a == PC)
                {
                    // Warn about relative addressing portability.
                    dwarn(WARN_RELATIVE_PC_ADDRESSING, NULL);
                }

                // Output the initial opcode.
                if (insttype->opcode != OP_NONBASIC)
                    result = aout_emit(aout_create_opcode(insttype->opcode, ppresults.a, ppresults.b));
                else
                    result = aout_emit(aout_create_opcode(insttype->opcode, insttype->nbopcode, ppresults.a));

                // If the parameter is a label or requires an extra word, output them.
                if (ppresults.b_label != NULL)
                    aout_emit(aout_create_expr(expr_new_label(bautofree(bfromcstr(ppresults.b_label)))));
                else if (ppresults.b_extra_used)
                    aout_emit(aout_create_expr(ppresults.b_extra));

                if (ppresults.a_label != NULL)
                    aout_emit(aout_create_expr(expr_new_label(bautofree(bfromcstr(ppresults.a_label)))));
                else if (ppresults.a_extra_used)
                    aout_emit(aout_create_expr(ppresults.a_extra));

            }

            printd(LEVEL_VERBOSE, "\n");
            break;

        case type_label:
            // Handle label definition.
            list_append(&newsyms, dbgfmt_create_symbol(DBGFMT_SYMBOL_LABEL, dbgfmt_create_symbol_label(bfromcstr(line->label->name), DBGFMT_UNDETERMINED)));
            printd(LEVEL_VERBOSE, ":%s\n", line->label->name);
            aout_emit(aout_create_label(line->label->name));
            break;

        default:
            assert(false);
    }

    // If we can associate debugging symbols with this instruction...
    if (result != NULL)
    {
        // While the new symbols list is not empty, copy those symbols
        // into the output and associate.
        while (list_size(&newsyms) > 0)
        {
            newsym = list_extract_at(&newsyms, 0);
            printd(LEVEL_DEBUG, "Debugging custom symbol: %i\n", newsym->length);
            list_append(&result->symbols, newsym);
            list_append(assem_dbg_symbols, newsym);
        }

        // If the line information is provided, output
        // debugging symbols.
        if (line != NULL && line->file != NULL)
        {
            // Output a file / line number debugging symbol here.
            newsym = dbgfmt_create_symbol(DBGFMT_SYMBOL_LINE, dbgfmt_create_symbol_line(line->file, line->line, DBGFMT_UNDETERMINED));
            list_append(&result->symbols, newsym);
            list_append(assem_dbg_symbols, newsym);

            printd(LEVEL_DEBUG, "Debugging symbol: %i %s\n", line->line, line->file->data);
        }

        // If the higher-language line information is
        // provided, output debugging symbols.
        if (line != NULL && line->ufile != NULL)
        {
            // Output a file / line number debugging symbol here.
            newsym = dbgfmt_create_symbol(DBGFMT_SYMBOL_LINE, dbgfmt_create_symbol_line(line->ufile, line->uline, DBGFMT_UNDETERMINED));
            list_append(&result->symbols, newsym);
            list_append(assem_dbg_symbols, newsym);

            printd(LEVEL_DEBUG, "High-level debugging symbol: %i %s\n", line->uline, line->ufile->data);
        }
    }
}
Exemple #7
0
bool Navigation::ConverterToV1_0a4::convert(XmlDocument* document, const Version& version,
		std::string configFile) {
	bool success = true;

	updateDocument(document, XmlConfigurationLoader::XmlDtdUrl + "navigation_v1.0a4.dtd",
			destinationVersion, "navigation");

	// remove unnecessary <models> element
	XmlElement* rootElement = document->getRootElement();
	XmlElement* models = document->getElement("navigation.models");
	if (!models) {
		printd(ERROR,
				"Navigation::ConverterToV1_0a4::convert(): missing element <models>! Please fix your Navigation module configuration!\n");
		return false;
	} // if
	// detach models element from root
	rootElement->removeSubElement(models);
	std::vector<XmlElement*> subElements = models->getAllSubElements();
	std::vector<XmlElement*>::iterator it;
	XmlElement* subElement;
	// move all subelements of models to root
	for (it = subElements.begin(); it != subElements.end(); ++it) {
		subElement = *it;
		models->removeSubElement(subElement);
		rootElement->addSubElement(subElement);
		// update argument vector (if available)
		if (subElement->hasSubElement("arguments")) {
			XmlElement* argumentElement = subElement->getSubElement("arguments");
			XmlArgumentVectorLoader::get().updateXmlElement(argumentElement, version,
					destinationVersion, configFile);
		} // if
	} // for
	delete models;

	// rename element names
	document->renameElements("navigation.translationmodel", "translationModel");
	document->renameElements("navigation.orientationmodel", "orientationModel");
	document->renameElements("navigation.speedmodel", "speedModel");

	// rename attribute names
	document->renameAttributes("navigation.translationModel.name", "type");
	document->renameAttributes("navigation.orientationModel.name", "type");
	document->renameAttributes("navigation.speedModel.name", "type");

	// update deprecated model names
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationRelativeSensorFlyModel", "OrientationSensorFlyModel");
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationAbsoluteButtonModel", "OrientationButtonModel");
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationAbsoluteAxisModel", "OrientationSingleAxisModel");
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationAbsoluteSingleAxisModel", "OrientationSingleAxisModel");
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationAbsoluteDualAxisModel", "OrientationDualAxisModel");
	document->replaceAttributeValues("navigation.orientationModel.type",
			"OrientationAbsoluteSensorModel", "OrientationSensorModel");
	document->replaceAttributeValues("navigation.speedModel.type",
			"SpeedAbsoluteAxisModel", "SpeedAxisModel");
	document->replaceAttributeValues("navigation.speedModel.type",
			"SpeedAbsoluteButtonModel", "SpeedButtonModel");
	document->replaceAttributeValues("navigation.speedModel.type",
			"SpeedAbsoluteMultiButtonModel", "SpeedMultiButtonModel");
	document->replaceAttributeValues("navigation.speedModel.type",
			"SpeedAbsolute2AxisModel", "SpeedDualAxisModel");

	// rename Idx entries to Index
	document->replaceAttributeValues("navigation.speedModel.arguments.arg.key",
			"axisIdx", "axisIndex");
	document->replaceAttributeValues("navigation.speedModel.arguments.arg.key",
			"accelButtonIdx", "accelButtonIndex");
	document->replaceAttributeValues("navigation.speedModel.arguments.arg.key",
			"decelButtonIdx", "decelButtonIndex");
	document->replaceAttributeValues("navigation.speedModel.arguments.arg.key",
			"axis1Idx", "axis1Index");
	document->replaceAttributeValues("navigation.speedModel.arguments.arg.key",
			"axis2Idx", "axis2Index");

	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"sensorIdx", "sensorIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"frontIdx", "frontIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"backIdx", "backIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"leftIdx", "leftIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"rightIdx", "rightIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"leftRightIdx", "leftRightIndex");
	document->replaceAttributeValues("navigation.translationModel.arguments.arg.key",
			"frontBackIdx", "frontBackIndex");

	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"sensorIdx", "sensorIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"buttonIdx", "buttonIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"leftIdx", "leftIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"rightIdx", "rightIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"upIdx", "upIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"downIdx", "downIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"cwIdx", "clockwiseIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"ccwIdx", "counterclockwiseIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"axisIdx", "axisIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"xAxisIdx", "xAxisIndex");
	document->replaceAttributeValues("navigation.orientationModel.arguments.arg.key",
			"yAxisIdx", "yAxisIndex");


	return success;
} // convert
Exemple #8
0
int epos_Modes_of_Operation_Display(uint16_t node_id, enum Epos_mode mode) {
        int result;
        SDO_data d;
        d.nodeid = node_id;
        d.index = 0x6061;
        d.subindex = 0x00;
        d.data.size = 1; 
        d.data.data = mode;
        result = SDO_write(motor_cfg_fd, &d);
        switch (d.data.data) {
           case 7:
              printd(LOG_ERROR, "Interpolated_Position_Mode\n");
              break; 
           case 6:
              printd(LOG_ERROR, "Homing_Mode\n");
              break;
           case 3:
              printd(LOG_ERROR, "Profile_Velocity_Mode\n");
              break;   
           case 1:
 	      printd(LOG_ERROR, "Profile_Position_Mode\n");
              break;
 	   case -1:
              printd(LOG_ERROR, "Position_Mode\n");
              break;
	   case -2:
              printd(LOG_ERROR, "Velocity_Mode\n");
              break;
	   case -3:
              printd(LOG_ERROR, "Current_Mode\n");
              break;
           case -4:
              printd(LOG_ERROR, "Diagnostic_Mode\n");
              break;
           case -5:
              printd(LOG_ERROR, "Master_Encoder_Mode\n");
              break;
           case -6:
              printd(LOG_ERROR, "Step_Direction_Mode\n");
              break;
           default:
              printd(LOG_ERROR, "Unknown Mode\n");
              return 1;
       }
       return 0;
}
Exemple #9
0
//---------------------------------------------------------------------------------
int main(int argc, char **argv)
{
    IOS_ReloadIOS(56);

    InitVideo ();

    printd ("---------------------------------------------------------------------------");
    printd ("                        neekbooter "VER" by stfour");
    printd ("                       (part of postLoader project)");
    printd ("---------------------------------------------------------------------------");

    u32 idx = -1;
    u32 status = 0;
    u32 hi, lo;
    u32 back2real;

    if (neek_PLNandInfo	(0, &idx, &status, &lo, &hi, &back2real) == false)
    {
        printd ("no boot information...");
        Reload ();
    }

    printd ("idx = %d", idx);
    printd ("status = %d", status);

    if (status == PLNANDSTATUS_NONE)
    {
        status = PLNANDSTATUS_BOOTING;
        neek_PLNandInfo	(1, &idx, &status, &lo, &hi, &back2real);

        if (!hi && !lo)
        {
            printd ("booting disk");

            // Copy the di image
            memcpy(EXECUTE_ADDR, di_dol, di_dol_size);
            DCFlushRange((void *) EXECUTE_ADDR, di_dol_size);

            // Load the booter
            memcpy(BOOTER_ADDR, booter_dol, booter_dol_size);
            DCFlushRange(BOOTER_ADDR, booter_dol_size);

            memset(ARGS_ADDR, 0, sizeof(struct __argv));
            DCFlushRange(ARGS_ADDR, sizeof(struct __argv));

            printd ("stating di");

            entrypoint hbboot_ep = (entrypoint) BOOTER_ADDR;

            // bootit !
            u32 level;
            SYS_ResetSystem(SYS_SHUTDOWN, 0, 0);
            _CPU_ISR_Disable(level);
            __exception_closeall();
            hbboot_ep();
            _CPU_ISR_Restore(level);
        }
        else
        {
            printd ("booting channel");

            WII_Initialize();
            WII_LaunchTitle((u64)(TITLE_ID (hi, lo)));

            exit(0);  // Use exit() to exit a program, do not use 'return' from main()

            /*

            s_nandbooter nb ATTRIBUTE_ALIGN(32);

            u8 *tfb = ((u8 *) 0x93200000);

            memset (&nb, 0, sizeof (s_nandbooter));

            nb.channel.language = -1;
            nb.channel.titleId = TITLE_ID (hi, lo);
            nb.channel.bootMode = 1;

            // Copy the triiforce image
            memcpy(EXECUTE_ADDR, nandbooter_dol, nandbooter_dol_size);
            DCFlushRange((void *) EXECUTE_ADDR, nandbooter_dol_size);

            // Load the booter
            memcpy(BOOTER_ADDR, booter_dol, booter_dol_size);
            DCFlushRange(BOOTER_ADDR, booter_dol_size);

            memset(ARGS_ADDR, 0, sizeof(struct __argv));
            DCFlushRange(ARGS_ADDR, sizeof(struct __argv));

            memcpy (tfb, &nb, sizeof(s_nandbooter));

            printd ("stating nandbooter");

            entrypoint hbboot_ep = (entrypoint) BOOTER_ADDR;

            u32 level;
            SYS_ResetSystem(SYS_SHUTDOWN, 0, 0);
            _CPU_ISR_Disable(level);
            __exception_closeall();
            hbboot_ep();
            _CPU_ISR_Restore(level);
            */
        }
    }
    else if (status == PLNANDSTATUS_BOOTING)
    {
        status = PLNANDSTATUS_BOOTED;
        neek_PLNandInfo	(1, &idx, &status, &lo, &hi, &back2real);

        if (!hi && !lo)
        {
            if (back2real)
            {
                printd ("returning to realnand");

                RestoreSneekFolder ();
                SYS_ResetSystem(SYS_RESTART,0,0);
            }
            else
            {
                printd ("restoring old nanndindex");

                neek_GetNandConfig ();

                // Go back to previous nand
                nandConfig->NandSel = idx;
                neek_WriteNandConfig ();

                neek_PLNandInfoRemove ();
                SYS_ResetSystem(SYS_RETURNTOMENU, 0, 0);
            }
        }
        else
        {
            // restore sneek files
            RestoreSneekFolder ();
            SYS_ResetSystem(SYS_RESTART,0,0);
        }
    }

    exit (0);
}
Exemple #10
0
//------------------------------------------------------------------------------
// The main method
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
	osgInit(argc, argv);                 // initialize OpenSG
	int winid = setupGLUT(&argc, argv);  // initialize GLUT

	// the connection between GLUT and OpenSG is established
	GLUTWindowPtr gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->init();

//----------------------------------------------------------------------------//
// Snippet-1-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// very first step: load the configuration of the file structures, basically
	// paths are set. The Configuration always has to be loaded first since each
	// module uses the paths set in the configuration-file
	if (!Configuration::loadConfig("config/general.xml")) {
		printf("Error: could not load config-file!\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-1-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-4 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// register callbacks
	InputInterface::registerModuleInitCallback(initInputInterface);
	SystemCore::registerModuleInitCallback(initModules);
//----------------------------------------------------------------------------//
// Snippet-2-4 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	SystemCore::registerCoreComponentInitCallback(initCoreComponents);
//----------------------------------------------------------------------------//
// Snippet-3-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-1-2 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	std::string systemCoreConfigFile = Configuration::getString(
			"SystemCore.systemCoreConfiguration");
	std::string outputInterfaceConfigFile = Configuration::getString(
			"Interfaces.outputInterfaceConfiguration");

//	// !!!!!! Remove in tutorial part 2, Snippet-2-1 - BEGIN
//	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile)) {
//		printf("Error: failed to setup SystemCore!\n");
//		return -1;
//	}
//	// !!!!!! Remove - END
//----------------------------------------------------------------------------//
// Snippet-1-2 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// !!!!!! Remove part of Snippet-1-2 (right above)
	// in addition to the SystemCore config file, modules and interfaces config
	// files have to be loaded.
	std::string modulesConfigFile = Configuration::getString(
				"Modules.modulesConfiguration");
	std::string inputInterfaceConfigFile = Configuration::getString(
			"Interfaces.inputInterfaceConfiguration");

	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile, inputInterfaceConfigFile,
			modulesConfigFile)) {
		printf("Error: failed to setup SystemCore!\n");
		printf("Please check if the Plugins-path is correctly set to the inVRs-lib directory in the ");
		printf("'final/config/general.xml' config file, e.g.:\n");
		printf("<path name=\"Plugins\" path=\"/home/guest/inVRs/lib\"/>\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-2-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// generate or load and configure height maps of the used tiles
	HeightMapManager::generateTileHeightMaps();
//----------------------------------------------------------------------------//
// Snippet-3-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-15 - BEGIN                                                       //
//----------------------------------------------------------------------------//
	// generate and configure the SkyBox
	std::string skyPath = Configuration::getPath("Skybox");
	skybox.init(5,5,5, 1000, (skyPath+"lostatseaday/lostatseaday_dn.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_up.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_ft.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_bk.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_rt.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_lf.jpg").c_str());
//----------------------------------------------------------------------------//
// Snippet-2-15 - END                                                         //
//----------------------------------------------------------------------------//

	NodePtr root = Node::create();
	beginEditCP(root);
		root->setCore(Group::create());

//----------------------------------------------------------------------------//
// Snippet-1-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
		OpenSGSceneGraphInterface* sgIF =
			dynamic_cast<OpenSGSceneGraphInterface*>(OutputInterface::getSceneGraphInterface());
		if (!sgIF) {
			printf("Error: Failed to get OpenSGSceneGraphInterface!\n");
			printf("Please check if the OutputInterface configuration is correct!\n");
			return -1;
		}
		// retrieve root node of the SceneGraphInterface (method is OpenSG specific)
		NodePtr scene = sgIF->getNodePtr();

		root->addChild(scene);
//----------------------------------------------------------------------------//
// Snippet-1-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-16 - BEGIN                                                       //
//----------------------------------------------------------------------------//
		// add the SkyBox to the scene
		root->addChild(skybox.getNodePtr());
//----------------------------------------------------------------------------//
// Snippet-2-16 - END                                                         //
//----------------------------------------------------------------------------//

	endEditCP(root);

//----------------------------------------------------------------------------//
// Snippet-2-5 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// fetch users camera, it is used to tell the Navigator where we are
	localUser = UserDatabase::getLocalUser();
	if (!localUser) {
		printd(ERROR, "Error: Could not find localUser!\n");
		return -1;
	}

	camera = localUser->getCamera();
	if (!camera) {
		printd(ERROR, "Error: Could not find camera!\n");
		return -1;
	}

	avatar = localUser->getAvatar();
	if (!avatar) {
		printd(ERROR, "Error: Could not find avatar!\n");
		return -1;
	}
	avatar->showAvatar(false);

  // set our transformation to the start transformation
	TransformationData startTrans =
		WorldDatabase::getEnvironmentWithId(1)->getStartTransformation(0);
	localUser->setNavigatedTransformation(startTrans);
//----------------------------------------------------------------------------//
// Snippet-2-5 - END                                                          //
//----------------------------------------------------------------------------//

	mgr = new SimpleSceneManager;  // create the SimpleSceneManager
	mgr->setWindow(gwin);          // tell the manager what to manage
	mgr->setRoot(root);            // attach the scenegraph to the  root node
	mgr->showAll();                // show the whole scene
	mgr->getCamera()->setNear(0.1);

//----------------------------------------------------------------------------//
// Snippet-2-6 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// Navigator is part of SimpleSceneManager and not of the inVRs framework
	Navigator *nav = mgr->getNavigator();
	nav->setMode(Navigator::NONE);     // turn off the navigator
	lastTimeStamp = timer.getTime();   // initialize timestamp;
	camMatrix = gmtl::MAT_IDENTITY44F; // initial setting of the camera matrix
//----------------------------------------------------------------------------//
// Snippet-2-6 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-5-2                                                                //
//----------------------------------------------------------------------------//

	glutMainLoop(); // GLUT main loop
	return 0;
}
Exemple #11
0
/*
 * For a certain principal, collect any unreferenced and not_in 
 * free list cbufs so that they can be reused.  This is the 
 * garbage-collection mechanism.
 *
 * Collect cbufs and add them onto the shared component's ring buffer.
 *
 * This function is semantically complicated. It can return no cbufs 
 * even if they are available to force the pool of cbufs to be
 * expanded (the client will call cbuf_create in this case). 
 * Or, the common case: it can return a number of available cbufs.
 */
int
cbuf_collect(spdid_t spdid, unsigned long size)
{
	struct cbuf_info *cbi;
	struct cbuf_comp_info *cci;
	struct cbuf_shared_page *csp;
	struct cbuf_bin *bin;
	int ret = 0;

	printl("cbuf_collect\n");

	CBUF_TAKE();
	cci  = cbuf_comp_info_get(spdid);
	tracking_start(&cci->track, CBUF_COLLECT);
	if (unlikely(!cci)) ERR_THROW(-ENOMEM, done);
	if (size + cci->allocated_size <= cci->target_size) goto done;

	csp  = cci->csp;
	if (unlikely(!csp)) ERR_THROW(-EINVAL, done);

	assert(csp->ring.size == CSP_BUFFER_SIZE);
	ret = CK_RING_SIZE(cbuf_ring, &csp->ring);
	if (ret != 0) goto done;
	/* 
	 * Go through all cbufs we own, and report all of them that
	 * have no current references to them.  Unfortunately, this is
	 * O(N*M), N = min(num cbufs, PAGE_SIZE/sizeof(int)), and M =
	 * num components.
	 */
	size = round_up_to_page(size);
	bin  = cbuf_comp_info_bin_get(cci, size);
	if (!bin) ERR_THROW(0, done);
	cbi  = bin->c;
	do {
		if (!cbi) break;
		/*
		 * skip cbufs which are in freelist. Coordinates with cbuf_free to 
		 * detect such cbufs correctly. 
		 * We must check refcnt first and then next pointer.
		 *
		 * If do not check refcnt: the manager may check "next" before cbuf_free 
		 * (when it is NULL), then switch to client who calls cbuf_free to set 
		 * "next", decrease refcnt and add cbuf to freelist. Then switch back to 
		 * manager, but now it will collect this in-freelist cbuf.
		 * 
		 * Furthermore we must check refcnt before the "next" pointer: 
		 * If not, similar to above case, the manager maybe preempted by client 
		 * between the manager checks "next" and refcnt. Therefore the manager 
		 * finds the "next" is null and refcnt is 0, and collect this cbuf.
		 * Short-circuit can prevent reordering. 
		 */
		assert(cbi->owner.m);
		if (!CBUF_REFCNT(cbi->owner.m) && !CBUF_IS_IN_FREELIST(cbi->owner.m)
                 		    && !cbuf_referenced(cbi)) {
			struct cbuf_ring_element el = { .cbid = cbi->cbid };
			cbuf_references_clear(cbi);
			if (!CK_RING_ENQUEUE_SPSC(cbuf_ring, &csp->ring, &el)) break;
			/*
			 * Prevent other collection collecting those cbufs.
			 * The manager checks if the shared ring buffer is empty upon 
			 * the entry, if not, it just returns. This is not enough to 
			 * prevent double-collection. The corner case is: 
			 * after the last one in ring buffer is dequeued and 
			 * before it is added to the free-list, the manager  
			 * appears. It may collect the last one again.
			 */
			cbi->owner.m->next = (struct cbuf_meta *)1;
			if (++ret == CSP_BUFFER_SIZE) break;
		}
		cbi = FIRST_LIST(cbi, next, prev);
	} while (cbi != bin->c);
	if (ret) cbuf_thd_wake_up(cci, ret*size);

done:
	tracking_end(&cci->track, CBUF_COLLECT);
	CBUF_RELEASE();
	return ret;
}

/* 
 * Called by cbuf_deref.
 */
int
cbuf_delete(spdid_t spdid, unsigned int cbid)
{
	struct cbuf_comp_info *cci;
	struct cbuf_info *cbi;
	struct cbuf_meta *meta;
	int ret = -EINVAL, sz;

	printl("cbuf_delete\n");
	CBUF_TAKE();
	tracking_start(NULL, CBUF_DEL);

	cci  = cbuf_comp_info_get(spdid);
	if (unlikely(!cci)) goto done;
	cbi  = cmap_lookup(&cbufs, cbid);
	if (unlikely(!cbi)) goto done;
	meta = cbuf_meta_lookup(cci, cbid);

	/*
	 * Other threads can access the meta data simultaneously. For
	 * example, others call cbuf2buf which increase the refcnt.
	 */
	CBUF_REFCNT_ATOMIC_DEC(meta);
	/* Find the owner of this cbuf */
	if (cbi->owner.spdid != spdid) {
		cci = cbuf_comp_info_get(cbi->owner.spdid);
		if (unlikely(!cci)) goto done;
	}
	if (cbuf_free_unmap(cci, cbi)) 	goto done;
	if (cci->allocated_size < cci->target_size) {
		cbuf_thd_wake_up(cci, cci->target_size - cci->allocated_size);
	}
	ret = 0;
done:
	tracking_end(NULL, CBUF_DEL);
	CBUF_RELEASE();
	return ret;
}

/* 
 * Called by cbuf2buf to retrieve a given cbid.
 */
int
cbuf_retrieve(spdid_t spdid, unsigned int cbid, unsigned long size)
{
	struct cbuf_comp_info *cci, *own;
	struct cbuf_info *cbi;
	struct cbuf_meta *meta, *own_meta;
	struct cbuf_maps *map;
	vaddr_t dest;
	void *page;
	int ret = -EINVAL, off;

	printl("cbuf_retrieve\n");

	CBUF_TAKE();
	tracking_start(NULL, CBUF_RETRV);

	cci        = cbuf_comp_info_get(spdid);
	if (!cci) {printd("no cci\n"); goto done; }
	cbi        = cmap_lookup(&cbufs, cbid);
	if (!cbi) {printd("no cbi\n"); goto done; }
	/* shouldn't cbuf2buf your own buffer! */
	if (cbi->owner.spdid == spdid) {
		printd("owner\n"); 
		goto done;
	}
	meta       = cbuf_meta_lookup(cci, cbid);
	if (!meta) {printd("no meta\n"); goto done; }
	assert(!(meta->nfo & ~CBUF_INCONSISENT));

	map        = malloc(sizeof(struct cbuf_maps));
	if (!map) {printd("no map\n"); ERR_THROW(-ENOMEM, done); }
	if (size > cbi->size) {printd("too big\n"); goto done; }
	assert(round_to_page(cbi->size) == cbi->size);
	size       = cbi->size;
	/* TODO: change to MAPPING_READ */
	if (cbuf_alloc_map(spdid, &map->addr, NULL, cbi->mem, size, MAPPING_RW)) {
		printc("cbuf mgr map fail spd %d mem %p sz %lu cbid %u\n", spdid, cbi->mem, size, cbid);
		goto free;
	}

	INIT_LIST(map, next, prev);
	ADD_LIST(&cbi->owner, map, next, prev);
	CBUF_PTR_SET(meta, map->addr);
	map->spdid          = spdid;
	map->m              = meta;
	meta->sz            = cbi->size >> PAGE_ORDER;
	meta->cbid_tag.cbid = cbid;
	own                 = cbuf_comp_info_get(cbi->owner.spdid);
	if (unlikely(!own)) goto done;
	/*
	 * We need to inherit the relinquish bit from the sender. 
	 * Otherwise, this cbuf cannot be returned to the manager. 
	 */
	own_meta            = cbuf_meta_lookup(own, cbid);
	if (CBUF_RELINQ(own_meta)) CBUF_FLAG_ADD(meta, CBUF_RELINQ);
	ret                 = 0;
done:
	tracking_end(NULL, CBUF_RETRV);

	CBUF_RELEASE();
	return ret;
free:
	free(map);
	goto done;
}

vaddr_t
cbuf_register(spdid_t spdid, unsigned int cbid)
{
	struct cbuf_comp_info  *cci;
	struct cbuf_meta_range *cmr;
	void *p;
	vaddr_t dest, ret = 0;

	printl("cbuf_register\n");
	CBUF_TAKE();
	tracking_start(NULL, CBUF_REG);

	cci = cbuf_comp_info_get(spdid);
	if (unlikely(!cci)) goto done;
	cmr = cbuf_meta_lookup_cmr(cci, cbid);
	if (cmr) ERR_THROW(cmr->dest, done);

	/* Create the mapping into the client */
	if (cbuf_alloc_map(spdid, &dest, &p, NULL, PAGE_SIZE, MAPPING_RW)) goto done;
	assert((unsigned int)p == round_to_page(p));
	cmr = cbuf_meta_add(cci, cbid, p, dest);
	assert(cmr);
	ret = cmr->dest;
done:
	tracking_end(NULL, CBUF_REG);

	CBUF_RELEASE();
	return ret;
}

static void
cbuf_shrink(struct cbuf_comp_info *cci, int diff)
{
	int i, sz;
	struct cbuf_bin *bin;
	struct cbuf_info *cbi, *next, *head;

	for (i = cci->nbin-1 ; i >= 0 ; i--) {
		bin = &cci->cbufs[i];
		sz = (int)bin->size;
		if (!bin->c) continue;
		cbi = FIRST_LIST(bin->c, next, prev);
		while (cbi != bin->c) {
			next = FIRST_LIST(cbi, next, prev);
			if (!cbuf_free_unmap(cci, cbi)) {
				diff -= sz;
				if (diff <= 0) return;
			}
			cbi = next;
		}
		if (!cbuf_free_unmap(cci, cbi)) {
			diff -= sz;
			if (diff <= 0) return;
		}
	}
	if (diff > 0) cbuf_mark_relinquish_all(cci);
}
Exemple #12
0
void
kerberos4_is(Authenticator *ap, unsigned char *data, int cnt)
{
    struct sockaddr_in addr;
    char realm[REALM_SZ];
    char instance[INST_SZ];
    int r;
    int addr_len;

    if (cnt-- < 1)
	return;
    switch (*data++) {
    case KRB_AUTH:
	if (krb_get_lrealm(realm, 1) != KSUCCESS) {
	    Data(ap, KRB_REJECT, (void *)"No local V4 Realm.", -1);
	    auth_finished(ap, AUTH_REJECT);
	    if (auth_debug_mode)
		printf("No local realm\r\n");
	    return;
	}
	memmove(auth.dat, data, auth.length = cnt);
	if (auth_debug_mode) {
	    printf("Got %d bytes of authentication data\r\n", cnt);
	    printf("CK: %d:", kerberos4_cksum(auth.dat, auth.length));
	    printd(auth.dat, auth.length);
	    printf("\r\n");
	}
	k_getsockinst(0, instance, sizeof(instance));
	addr_len = sizeof(addr);
	if(getpeername(0, (struct sockaddr *)&addr, &addr_len) < 0) {
	    if(auth_debug_mode)
		printf("getpeername failed\r\n");
	    Data(ap, KRB_REJECT, "getpeername failed", -1);
	    auth_finished(ap, AUTH_REJECT);
	    return;
	}
	r = krb_rd_req(&auth, KRB_SERVICE_NAME,
		       instance, addr.sin_addr.s_addr, &adat, "");
	if (r) {
	    if (auth_debug_mode)
		printf("Kerberos failed him as %s\r\n", name);
	    Data(ap, KRB_REJECT, (void *)krb_get_err_text(r), -1);
	    auth_finished(ap, AUTH_REJECT);
	    return;
	}
	/* save the session key */
	memmove(session_key, adat.session, sizeof(adat.session));
	krb_kntoln(&adat, name);

	if (UserNameRequested && !kuserok(&adat, UserNameRequested)){
	    char ts[MAXPATHLEN];
	    struct passwd *pw = getpwnam(UserNameRequested);

	    if(pw){
		snprintf(ts, sizeof(ts),
			 "%s%u",
			 TKT_ROOT,
			 (unsigned)pw->pw_uid);
		setenv("KRBTKFILE", ts, 1);
	    }
	    Data(ap, KRB_ACCEPT, NULL, 0);
	} else {
	    char *msg;

	    asprintf (&msg, "user `%s' is not authorized to "
		      "login as `%s'", 
		      krb_unparse_name_long(adat.pname, 
					    adat.pinst, 
					    adat.prealm), 
		      UserNameRequested ? UserNameRequested : "<nobody>");
	    if (msg == NULL)
		Data(ap, KRB_REJECT, NULL, 0);
	    else {
		Data(ap, KRB_REJECT, (void *)msg, -1);
		free(msg);
	    }
	}
	auth_finished(ap, AUTH_USER);
	break;
	
    case KRB_CHALLENGE:
#ifndef ENCRYPTION
	Data(ap, KRB_RESPONSE, NULL, 0);
#else
	if(!VALIDKEY(session_key)){
	    Data(ap, KRB_RESPONSE, NULL, 0);
	    break;
	}
	des_key_sched(&session_key, sched);
	{
	    des_cblock d_block;
	    int i;
	    Session_Key skey;

	    memmove(d_block, data, sizeof(d_block));

	    /* make a session key for encryption */
	    des_ecb_encrypt(&d_block, &session_key, sched, 1);
	    skey.type=SK_DES;
	    skey.length=8;
	    skey.data=session_key;
	    encrypt_session_key(&skey, 1);

	    /* decrypt challenge, add one and encrypt it */
	    des_ecb_encrypt(&d_block, &challenge, sched, 0);
	    for (i = 7; i >= 0; i--)
		if(++challenge[i] != 0)
		    break;
	    des_ecb_encrypt(&challenge, &challenge, sched, 1);
	    Data(ap, KRB_RESPONSE, (void *)challenge, sizeof(challenge));
	}
#endif
	break;

    case KRB_FORWARD:
	{
	    des_key_schedule ks;
	    unsigned char netcred[sizeof(CREDENTIALS)];
	    CREDENTIALS cred;
	    int ret;
	    if(cnt > sizeof(cred))
		abort();

	    des_set_key(&session_key, ks);
	    des_pcbc_encrypt((void*)data, (void*)netcred, cnt, 
			     ks, &session_key, DES_DECRYPT);
	    unpack_cred(netcred, cnt, &cred);
	    {
		if(strcmp(cred.service, KRB_TICKET_GRANTING_TICKET) ||
		   strncmp(cred.instance, cred.realm, sizeof(cred.instance)) ||
		   cred.lifetime < 0 || cred.lifetime > 255 ||
		   cred.kvno < 0 || cred.kvno > 255 ||
		   cred.issue_date < 0 || 
		   cred.issue_date > time(0) + CLOCK_SKEW ||
		   strncmp(cred.pname, adat.pname, sizeof(cred.pname)) ||
		   strncmp(cred.pinst, adat.pinst, sizeof(cred.pname))){
		    Data(ap, KRB_FORWARD_REJECT, "Bad credentials", -1);
		}else{
		    if((ret = tf_setup(&cred,
				       cred.pname,
				       cred.pinst)) == KSUCCESS){
		        struct passwd *pw = getpwnam(UserNameRequested);

			if (pw)
			  chown(tkt_string(), pw->pw_uid, pw->pw_gid);
			Data(ap, KRB_FORWARD_ACCEPT, 0, 0);
		    } else{
			Data(ap, KRB_FORWARD_REJECT, 
			     krb_get_err_text(ret), -1);
		    }
		}
	    }
	    memset(data, 0, cnt);
	    memset(ks, 0, sizeof(ks));
	    memset(&cred, 0, sizeof(cred));
	}
	
	break;

    default:
	if (auth_debug_mode)
	    printf("Unknown Kerberos option %d\r\n", data[-1]);
	Data(ap, KRB_REJECT, 0, 0);
	break;
    }
}
Exemple #13
0
static int
kerberos4_send(char *name, Authenticator *ap)
{
    KTEXT_ST auth;
    char instance[INST_SZ];
    char *realm;
    CREDENTIALS cred;
    int r;

    printf("[ Trying %s ... ]\r\n", name);
    if (!UserNameRequested) {
	if (auth_debug_mode) {
	    printf("Kerberos V4: no user name supplied\r\n");
	}
	return(0);
    }

    memset(instance, 0, sizeof(instance));

    if ((realm = krb_get_phost(RemoteHostName)))
	strncpy(instance, realm, sizeof(instance));

    instance[sizeof(instance)-1] = '\0';

    realm = dest_realm ? dest_realm : krb_realmofhost(RemoteHostName);

    if (!realm) {
	printf("Kerberos V4: no realm for %s\r\n", RemoteHostName);
	return(0);
    }
    r = krb_mk_req(&auth, KRB_SERVICE_NAME, instance, realm, 0L);
    if (r) {
	printf("mk_req failed: %s\r\n", krb_get_err_text(r));
	return(0);
    }
    r = krb_get_cred(KRB_SERVICE_NAME, instance, realm, &cred);
    if (r) {
	printf("get_cred failed: %s\r\n", krb_get_err_text(r));
	return(0);
    }
    if (!auth_sendname(UserNameRequested, strlen(UserNameRequested))) {
	if (auth_debug_mode)
	    printf("Not enough room for user name\r\n");
	return(0);
    }
    if (auth_debug_mode)
	printf("Sent %d bytes of authentication data\r\n", auth.length);
    if (!Data(ap, KRB_AUTH, (void *)auth.dat, auth.length)) {
	if (auth_debug_mode)
	    printf("Not enough room for authentication data\r\n");
	return(0);
    }
#ifdef ENCRYPTION
    /* create challenge */
    if ((ap->way & AUTH_HOW_MASK)==AUTH_HOW_MUTUAL) {
	int i;

	des_key_sched(&cred.session, sched);
	des_init_random_number_generator(&cred.session);
	des_new_random_key(&session_key);
	des_ecb_encrypt(&session_key, &session_key, sched, 0);
	des_ecb_encrypt(&session_key, &challenge, sched, 0);

	/*
	  old code
	  Some CERT Advisory thinks this is a bad thing...
	    
	  des_init_random_number_generator(&cred.session);
	  des_new_random_key(&challenge);
	  des_ecb_encrypt(&challenge, &session_key, sched, 1);
	  */
	  
	/*
	 * Increment the challenge by 1, and encrypt it for
	 * later comparison.
	 */
	for (i = 7; i >= 0; --i) 
	    if(++challenge[i] != 0) /* No carry! */
		break;
	des_ecb_encrypt(&challenge, &challenge, sched, 1);
    }

#endif

    if (auth_debug_mode) {
	printf("CK: %d:", kerberos4_cksum(auth.dat, auth.length));
	printd(auth.dat, auth.length);
	printf("\r\n");
	printf("Sent Kerberos V4 credentials to server\r\n");
    }
    return(1);
}
Exemple #14
0
/*
 * This is called when an AUTH SEND is received.
 * It should never arrive on the server side (as only the server can
 * send an AUTH SEND).
 * You should probably respond to it if you can...
 *
 * If you want to respond to the types out of order (i.e. even
 * if he sends  LOGIN KERBEROS and you support both, you respond
 * with KERBEROS instead of LOGIN (which is against what the
 * protocol says)) you will have to hack this code...
 */
void
auth_send(unsigned char *data, int cnt)
{
	Authenticator *ap;
	static unsigned char str_none[] = { IAC, SB, TELOPT_AUTHENTICATION,
					    TELQUAL_IS, AUTHTYPE_NULL, 0,
					    IAC, SE };
	if (Server) {
		if (auth_debug_mode) {
			printf(">>>%s: auth_send called!\r\n", Name);
		}
		return;
	}

	if (auth_debug_mode) {
		printf(">>>%s: auth_send got:", Name);
		printd(data, cnt); printf("\r\n");
	}

	/*
	 * Save the data, if it is new, so that we can continue looking
	 * at it if the authorization we try doesn't work
	 */
	if (data < _auth_send_data ||
	    data > _auth_send_data + sizeof(_auth_send_data)) {
		auth_send_cnt = (size_t)cnt > sizeof(_auth_send_data)
					? sizeof(_auth_send_data)
					: cnt;
		memmove((void *)_auth_send_data, (void *)data, auth_send_cnt);
		auth_send_data = _auth_send_data;
	} else {
		/*
		 * This is probably a no-op, but we just make sure
		 */
		auth_send_data = data;
		auth_send_cnt = cnt;
	}
	while ((auth_send_cnt -= 2) >= 0) {
		if (auth_debug_mode)
			printf(">>>%s: He supports %d\r\n",
				Name, *auth_send_data);
		if ((i_support & ~i_wont_support) & typemask(*auth_send_data)) {
			ap = findauthenticator(auth_send_data[0],
					       auth_send_data[1]);
			if (ap && ap->send) {
				if (auth_debug_mode)
					printf(">>>%s: Trying %d %d\r\n",
						Name, auth_send_data[0],
							auth_send_data[1]);
				if ((*ap->send)(ap)) {
					/*
					 * Okay, we found one we like
					 * and did it.
					 * we can go home now.
					 */
					if (auth_debug_mode)
						printf(">>>%s: Using type %d\r\n",
							Name, *auth_send_data);
					auth_send_data += 2;
					return;
				}
			}
			/* else
			 *	just continue on and look for the
			 *	next one if we didn't do anything.
			 */
		}
		auth_send_data += 2;
	}
	net_write(str_none, sizeof(str_none));
	printsub('>', &str_none[2], sizeof(str_none) - 2);
	if (auth_debug_mode)
		printf(">>>%s: Sent failure message\r\n", Name);
	auth_finished(0, AUTH_REJECT);
}
Exemple #15
0
struct process_parameter_results process_address(struct ast_node_address* param)
{
    struct process_parameter_results result;
    struct register_mapping* registr;
    bstring btmp = NULL;
    result.v_raw = NULL;

    if (param->value != NULL)
        btmp = expr_representation(param->value);

    if (param->bracketed && param->added)
    {
        // This is of the form [0x1000+I].
        registr = get_register_by_name_next(param->addcmpt);

        if (registr == NULL)
        {
            // Attempt to use a label in square brackets.  Convert this
            // to an expression and then reinvoke ourselves with the
            // evaluated value.
            param->value = expr_new(expr_new_label(bautofree(bfromcstr(param->addcmpt))), EXPR_OP_ADD, param->value);
            param->addcmpt = "";
            param->added = 0;
            param->bracketed = 0;

            bdestroy(btmp);
            return process_address(param);
        }
        else if (registr->value == VALUE_NEXT_UNSUPPORTED)
        {
            // Attempt to use a register in brackets that can't be.
            printd(LEVEL_VERBOSE, "\n");
            dhalt(ERR_NEXTED_REGISTER_UNSUPPORTED, param->addcmpt);
        }

        printd(LEVEL_VERBOSE, "[%s+%s]", btmp->data, registr->name);
        result.v = registr->value;
        result.v_extra = param->value;
        result.v_extra_used = true;
        result.v_label = NULL;
    }
    else
    {
        // This is either the form 0x1000 or [0x1000].
        if (param->bracketed)
        {
            printd(LEVEL_VERBOSE, "[%s]", btmp->data);
            result.v = NXT;
        }
        else
        {
            printd(LEVEL_VERBOSE, "%s", btmp->data);
            result.v = NXT_LIT;
        }

        result.v_extra = param->value;
        result.v_extra_used = true;
        result.v_label = NULL;
    }

    if (btmp != NULL)
        bdestroy(btmp);

    return result;
}
Exemple #16
0
void SystemCoreRequestSyncEvent::encode(NetMessage* message) {
	printd(INFO, "SystemCoreRequestSyncEvent::encode(): encoding userId %u\n",
			requestUserId);
	message->putUInt32(requestUserId);
} // encode
Exemple #17
0
struct process_parameters_results process_parameters(struct ast_node_parameters* params)
{
    struct process_parameters_results result;
    struct process_parameter_results t;
    reverse_parameters(params);
    result.raw = NULL;

    if (params->last != NULL)
    {
        t = process_parameter(params->last);

        if (t.v_raw)
        {
            printd(LEVEL_VERBOSE, "\n");
            dhalt(ERR_GEN_UNSUPPORTED_PARAMETER, NULL);
        }

        result.a = t.v;
        result.a_extra = t.v_extra;
        result.a_extra_used = t.v_extra_used;
        result.a_label = t.v_label;
        result.a_label_bracketed = t.v_label_bracketed;

        if (params->last->prev != NULL)
        {
            t = process_parameter(params->last->prev);

            if (t.v_raw)
            {
                printd(LEVEL_VERBOSE, "\n");
                dhalt(ERR_GEN_UNSUPPORTED_PARAMETER, NULL);
            }

            result.b = t.v;
            result.b_extra = t.v_extra;
            result.b_extra_used = t.v_extra_used;
            result.b_label = t.v_label;
            result.b_label_bracketed = t.v_label_bracketed;
        }
        else
        {
            result.b = 0x0;
            result.b_extra = 0x0;
            result.b_extra_used = false;
            result.b_label = NULL;
            result.b_label_bracketed = false;
        }
    }
    else
    {
        result.a = 0x0;
        result.a_extra = 0x0;
        result.a_extra_used = false;
        result.a_label = NULL;
        result.b_label_bracketed = false;
        result.b = 0x0;
        result.b_extra = 0x0;
        result.b_extra_used = false;
        result.b_label = NULL;
        result.b_label_bracketed = false;
    }

    return result;
}
Exemple #18
0
void SystemCoreRequestSyncEvent::decode(NetMessage* message) {
	message->getUInt32(requestUserId);
	printd(INFO, "SystemCoreRequestSyncEvent::decode(): decoded userId %u\n",
			requestUserId);
} // decode
Exemple #19
0
bool Navigation::loadConfig(std::string configFile) {

	std::string configFileConcatenatedPath = configFile;
	if (!Configuration::containsPath("NavigationModuleConfiguration") &&
			Configuration::containsPath("NavigationConfiguration")) {
		printd(WARNING,
				"Navigation::loadConfig(): Deprecated path entry NavigationConfiguration found in general configuration file! Use NavigationModuleConfiguration instead!\n");
		configFileConcatenatedPath = getConcatenatedPath(configFile, "NavigationConfiguration");
	} else {
		configFileConcatenatedPath = getConcatenatedPath(configFile, "NavigationModuleConfiguration");
	} // else

	// load xml document via xmlConfigLoader
	std::auto_ptr<const XmlDocument> document(
			xmlConfigLoader.loadConfiguration(configFileConcatenatedPath));
	if (!document.get()) {
		printd(ERROR,
				"Navigation::loadConfig(): error at loading of configuration file %s!\n",
				configFile.c_str());
		return false;
	} // if

	bool success = true;

	// get elements for all three models
	const XmlElement* translationModelElement = document->getElement("navigation.translationModel");
	const XmlElement* orientationModelElement = document->getElement("navigation.orientationModel");
	const XmlElement* speedModelElement = document->getElement("navigation.speedModel");

	// delete old models (if used)
	if (translationModel) {
		delete translationModel;
		translationModel = NULL;
	} // if
	if (orientationModel) {
		delete orientationModel;
		orientationModel = NULL;
	} // if
	if (speedModel) {
		delete speedModel;
		speedModel = NULL;
	} // if

	// load translationModel
	std::string type;
	if (translationModelElement) {
		std::auto_ptr<ArgumentVector> arguments;
		type = translationModelElement->getAttributeValue("type");
		if (translationModelElement->hasSubElement("arguments")) {
			arguments.reset(readArgumentsFromXmlElement(translationModelElement));
		} // if
		printd(INFO, "Navigation::loadConfig(): trying to load translation model %s\n",
				type.c_str());
		translationModel = getTranslationModel(type, arguments.get());
		if (translationModel) {
			printd(INFO, "Navigation::loadConfig(): successfully loaded translation model %s\n",
					type.c_str());
		} else {
			printd(ERROR,
					"Navigation::loadConfig(): failed to load translation model %s\n",
					type.c_str());
			success = false;
		} // else
	} // if
	else {
		printd(WARNING,
				"Navigation::loadConfig(): no TranslationModel set in Navigation module configuration! TranslationModel will be ignored!\n");
	} // else

	// load orientationModel
	if (orientationModelElement) {
		std::auto_ptr<ArgumentVector> arguments;
		type = orientationModelElement->getAttributeValue("type");
		float angle = orientationModelElement->getAttributeValueAsFloat("angle");
		if (orientationModelElement->hasSubElement("arguments")) {
			arguments.reset(readArgumentsFromXmlElement(orientationModelElement));
		} // if
		printd(INFO, "Navigation::loadConfig(): trying to load orientation model %s\n",
				type.c_str());
		orientationModel = getOrientationModel(type, arguments.get());
		if (orientationModel) {
			orientationModel->setAngle(angle);
			printd(INFO, "Navigation::loadConfig(): successfully loaded orientation model %s\n",
					type.c_str());
		} else {
			printd(ERROR,
					"Navigation::loadConfig(): failed to load orientation model %s\n",
					type.c_str());
			success = false;
		} // else
	} // if
	else {
		printd(WARNING,
				"Navigation::loadConfig(): no OrientationModel set in Navigation module configuration! OrientationModel will be ignored!\n");
	} // else

	// load speedModel
	if (speedModelElement) {
		std::auto_ptr<ArgumentVector> arguments;
		type = speedModelElement->getAttributeValue("type");
		float speed = speedModelElement->getAttributeValueAsFloat("speed");
		if (speedModelElement->hasSubElement("arguments")) {
			arguments.reset(readArgumentsFromXmlElement(speedModelElement));
		} // if
		printd(INFO, "Navigation::loadConfig(): trying to load speed model %s\n",
				type.c_str());
		speedModel = getSpeedModel(type, arguments.get());
		if (speedModel) {
			speedModel->setSpeed(speed);
			printd(INFO, "Navigation::loadConfig(): successfully loaded speed model %s\n",
					type.c_str());
		} else {
			printd(ERROR,
					"Navigation::loadConfig(): failed to load speed model %s\n",
					type.c_str());
			success = false;
		} // else
	} // if
	else {
		printd(WARNING,
				"Navigation::loadConfig(): no SpeedModel set in Navigation module configuration! SpeedModel will be ignored!\n");
	} // else

	return success;
} // loadConfig
Exemple #20
0
int
fb64_is(unsigned char *data, int cnt, struct fb *fbp)
{
	unsigned char *p;
	int state = fbp->state[DIR_DECRYPT-1];

	if (cnt-- < 1)
		goto failure;

	switch (*data++) {
	case FB64_IV:
		if (cnt != sizeof(Block)) {
			if (encrypt_debug_mode)
				printf("CFB64: initial vector failed on size\r\n");
			state = FAILED;
			goto failure;
		}

		if (encrypt_debug_mode)
			printf("CFB64: initial vector received\r\n");

		if (encrypt_debug_mode)
			printf("Initializing Decrypt stream\r\n");

		fb64_stream_iv((void *)data, &fbp->streams[DIR_DECRYPT-1]);

		p = fbp->fb_feed + 3;
		*p++ = ENCRYPT_REPLY;
		p++;
		*p++ = FB64_IV_OK;
		*p++ = IAC;
		*p++ = SE;
		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
		net_write(fbp->fb_feed, p - fbp->fb_feed);

		state = fbp->state[DIR_DECRYPT-1] = IN_PROGRESS;
		break;

	default:
		if (encrypt_debug_mode) {
			printf("Unknown option type: %d\r\n", *(data-1));
			printd(data, cnt);
			printf("\r\n");
		}
		/* FALL THROUGH */
	failure:
		/*
		 * We failed.  Send an FB64_IV_BAD option
		 * to the other side so it will know that
		 * things failed.
		 */
		p = fbp->fb_feed + 3;
		*p++ = ENCRYPT_REPLY;
		p++;
		*p++ = FB64_IV_BAD;
		*p++ = IAC;
		*p++ = SE;
		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
		net_write(fbp->fb_feed, p - fbp->fb_feed);

		break;
	}
	return(fbp->state[DIR_DECRYPT-1] = state);
}
Exemple #21
0
void myprintf(char *fmt, ...)
{
    int i = 0;
    char *cp;
    int *bp;
    int *ip;
    int retPC;
    
    cp = fmt;
    bp = (int *)getbp();
    ip = bp;
    retPC = *(ip++);
    // To make ip point to first argument, we have to iterate it by 2
    ip += 2;


    
    i = 0;
    // We loop through the string.
    while(fmt[i] != '\0')
    {
        if(fmt[i] == '\n')  // Case where character is a newline
        {
            putc('\n');
            putc('\r');
        }
        else if(fmt[i] == '%')  // User wants to print either a char, string, int, etc.
        {
            char *cPtr = 0;
            switch(fmt[++i])
            {
                case 's':
                    cPtr = (char *)*ip;
                    prints(cPtr);
                    break;
                case 'u':
                    printu(*ip);    
                    break;
                case 'd':
                    printd(*ip);
                    break;
                case 'o':
                    printo(*ip);
                    break;
                case 'x':
                    printx(*ip);
                    break;
                case 'c':
                    putc(*ip);
                    break;
                default:
                    break;
            }
            ip++;
        }
        else
        {
            putc(fmt[i]);    // Case where just a regular character
        }
        i++;
    }
    
    return;
}
Exemple #22
0
/*
 * This is called when an AUTH SEND is received.
 * It should never arrive on the server side (as only the server can
 * send an AUTH SEND).
 * You should probably respond to it if you can...
 *
 * If you want to respond to the types out of order (i.e. even
 * if he sends  LOGIN KERBEROS and you support both, you respond
 * with KERBEROS instead of LOGIN (which is against what the
 * protocol says)) you will have to hack this code...
 */
void
auth_send (unsigned char *data, int cnt)
{
  TN_Authenticator *ap;
  static unsigned char str_none[] = { IAC, SB, TELOPT_AUTHENTICATION,
    TELQUAL_IS, AUTHTYPE_NULL, 0,
    IAC, SE
  };
  if (Server)
    {
      if (auth_debug_mode)
	{
	  printf (">>>%s: auth_send called!\r\n", Name);
	}
      return;
    }

  if (auth_debug_mode)
    {
      printf (">>>%s: auth_send got:", Name);
      printd (data, cnt);
      printf ("\r\n");
    }

  /*
   * Save the data, if it is new, so that we can continue looking
   * at it if the authorization we try doesn't work
   */
  if (data < _auth_send_data ||
      data > _auth_send_data + sizeof (_auth_send_data))
    {
      auth_send_cnt = cnt > sizeof (_auth_send_data)
	? sizeof (_auth_send_data) : cnt;
      memmove ((void *) _auth_send_data, (void *) data, auth_send_cnt);
      auth_send_data = _auth_send_data;
    }
  else
    {
      /*
       * This is probably a no-op, but we just make sure
       */
      auth_send_data = data;
      auth_send_cnt = cnt;
    }
  while ((auth_send_cnt -= 2) >= 0)
    {
      if (auth_debug_mode)
	printf (">>>%s: He supports %s (%d) %s (%d)\r\n",
		Name, AUTHTYPE_NAME_OK (auth_send_data[0]) ?
		AUTHTYPE_NAME (auth_send_data[0]) :
		"unknown",
		auth_send_data[0],
		auth_send_data[1] &
		AUTH_HOW_MASK &
		AUTH_HOW_MUTUAL ? "MUTUAL" : "ONEWAY", auth_send_data[1]);
      if ((i_support & ~i_wont_support) & typemask (*auth_send_data))
	{
	  ap = findauthenticator (auth_send_data[0], auth_send_data[1]);
	  if (ap && ap->send)
	    {
	      if (auth_debug_mode)
		printf (">>>%s: Trying %s (%d) %s (%d)\r\n",
			Name,
			AUTHTYPE_NAME_OK (auth_send_data[0]) ?
			AUTHTYPE_NAME (auth_send_data[0]) :
			"unknown",
			auth_send_data[0],
			auth_send_data[1] &
			AUTH_HOW_MASK &
			AUTH_HOW_MUTUAL ?
			"MUTUAL" : "ONEWAY", auth_send_data[1]);
	      if ((*ap->send) (ap))
		{
		  /*
		   * Okay, we found one we like
		   * and did it.
		   * we can go home now.
		   */
		  if (auth_debug_mode)
		    printf (">>>%s: Using type %s (%d)\r\n",
			    Name,
			    AUTHTYPE_NAME_OK (*auth_send_data) ?
			    AUTHTYPE_NAME (*auth_send_data) :
			    "unknown", *auth_send_data);
		  auth_send_data += 2;
		  return;
		}
	    }
	  /* else
	   *      just continue on and look for the
	   *      next one if we didn't do anything.
	   */
	}
      auth_send_data += 2;
    }
  net_write (str_none, sizeof (str_none));
  printsub ('>', &str_none[2], sizeof (str_none) - 2);
  if (auth_debug_mode)
    printf (">>>%s: Sent failure message\r\n", Name);
  auth_finished (0, AUTH_REJECT);
# ifdef KANNAN
  /*
   *  We requested strong authentication, however no mechanisms worked.
   *  Therefore, exit on client end.
   */
  printf ("Unable to securely authenticate user ... exit\n");
  exit (EXIT_SUCCESS);
# endif	/* KANNAN */
}
Exemple #23
0
int main(int argc, char **argv)
{
	char *ds;
	int pid;
	pthread_t rcvr;

	register_printf_specifier('i', printf_ipaddr, printf_ipaddr_info);

	msglen = interval = 0;
	nmsg = NR_MSG;

	argv0 = argv[0];
	if (argc <= 1)
		usage();
	argc--, argv++;
	while (**argv == '-'){
		switch(argv[0][1]){
		case '6':
			proto = &v6pr;
			break;
		case 'a':
			addresses = 1;
			break;
		case 'd':
			debug++;
			break;
		case 'f':
			flood = 1;
			break;
		case 'i':
			argc--,argv++;
			interval = atoi(*argv);
			if(interval < 0)
				usage();
			break;
		case 'l':
			lostonly++;
			break;
		case 'n':
			argc--,argv++;
			nmsg = atoi(*argv);
			if(nmsg < 0)
				usage();
			break;
		case 'q':
			quiet = 1;
			break;
		case 'r':
			pingrint = 1;
			break;
		case 's':
			argc--,argv++;
			msglen = atoi(*argv);
			break;
		case 'w':
			argc--,argv++;
			waittime = atoi(*argv);
			if(waittime < 0)
				usage();
			break;
		default:
			usage();
			break;
		}
		
		argc--,argv++;
	}

	if(msglen < proto->iphdrsz + ICMP_HDRSIZE)
		msglen = proto->iphdrsz + ICMP_HDRSIZE;
	if(msglen < 64)
		msglen = 64;
	if(msglen >= 64*1024)
		msglen = 64*1024-1;
	if(interval <= 0 && !flood)
		interval = SLEEPMS;

	if(argc < 1)
		usage();

	/* TODO: consider catching ctrl-c and other signals. */

	if (!isv4name(argv[0]))
		proto = &v6pr;
	ds = netmkaddr(argv[0], proto->net, "1");
	printf("ping: dial %s\n", ds);
	fd = dial(ds, 0, 0, 0);
	if(fd < 0){
		fprintf(stderr, "%s: couldn't dial %s: %r\n", argv0, ds);
		exit(1);
	}

	if (!quiet)
		printf("sending %d %d byte messages %d ms apart to %s\n",
			nmsg, msglen, interval, ds);

	/* Spawning the receiver on a separate thread, possibly separate core */
	if (pthread_create(&rcvr, NULL, &rcvr_thread, NULL)) {
		perror("Failed to create recevier");
		exit(-1);
	}
	sender(fd, msglen, interval, nmsg);
	/* races with prints from the rcvr.  either lock, or live with it! */
	printd("Sent, now joining\n");
	pthread_join(rcvr, NULL);
	return 0;
}
bool
WithingsDownload::getBodyMeasures(QString &error, QDateTime from, QDateTime to, QList<BodyMeasure> &data)
{
    response = "";

    QString strNokiaToken = "";
    QString strNokiaRefreshToken = "";
    QString access_token = "";

    strNokiaToken = appsettings->cvalue(context->athlete->cyclist, GC_NOKIA_TOKEN).toString();
    strNokiaRefreshToken = appsettings->cvalue(context->athlete->cyclist, GC_NOKIA_REFRESH_TOKEN).toString();

    if(strNokiaRefreshToken.isEmpty() || strNokiaRefreshToken == "" || strNokiaRefreshToken == "0" ) {
        #ifdef Q_OS_MACX
        #define GC_PREF tr("Golden Cheetah->Preferences")
        #else
        #define GC_PREF tr("Tools->Options")
        #endif
        QString advise = QString(tr("Error fetching OAuth credentials.  Please make sure to complete the Withings authorization procedure found under %1.")).arg(GC_PREF);
        QMessageBox oautherr(QMessageBox::Critical, tr("OAuth Error"), advise);
        oautherr.exec();
        return false;
    }

    if(!strNokiaRefreshToken.isEmpty()) {
        printd("OAuth 2.0 API\n");

#if QT_VERSION > 0x050000
        QUrlQuery postData;
#else
        QUrl postData;
#endif

        QString refresh_token = appsettings->cvalue(context->athlete->cyclist, GC_NOKIA_REFRESH_TOKEN).toString();

        postData.addQueryItem("grant_type", "refresh_token");
        postData.addQueryItem("client_id", GC_NOKIA_CLIENT_ID );
        postData.addQueryItem("client_secret", GC_NOKIA_CLIENT_SECRET );
        postData.addQueryItem("refresh_token", refresh_token );

        QUrl url = QUrl( "https://account.withings.com/oauth2/token" );

        emit downloadStarted(100);

        QNetworkRequest request(url);
        request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
        nam->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
        printd("url %s %s\n", url.toString().toStdString().c_str(), postData.toString().toStdString().c_str());

        // blocking request
        loop.exec(); // we go on after receiving the data in SLOT(onRequestReady(QByteArray))

        printd("response: %s\n", response.toStdString().c_str());


        if (response.contains("\"access_token\"", Qt::CaseInsensitive))
        {
                QJsonParseError parseResult;
                QJsonDocument migrateJson = QJsonDocument::fromJson(response.toUtf8(), &parseResult);

                access_token = migrateJson.object()["access_token"].toString();
                QString refresh_token = migrateJson.object()["refresh_token"].toString();
                QString userid = QString("%1").arg(migrateJson.object()["userid"].toInt());


                if (access_token != "") appsettings->setCValue(context->athlete->cyclist, GC_NOKIA_TOKEN, access_token);
                if (refresh_token != "") appsettings->setCValue(context->athlete->cyclist, GC_NOKIA_REFRESH_TOKEN, refresh_token);
                if (userid != "") appsettings->setCValue(context->athlete->cyclist, GC_WIUSER, userid);


            #if QT_VERSION > 0x050000
                QUrlQuery params;
            #else
                QUrl params;
            #endif

                emit downloadStarted(100);

                params.addQueryItem("action", "getmeas");
                //params.addQueryItem("userid", userid);
                params.addQueryItem("access_token", access_token);
                params.addQueryItem("startdate", QString::number(from.toMSecsSinceEpoch()/1000));
                params.addQueryItem("enddate", QString::number(to.toMSecsSinceEpoch()/1000));


                QUrl url = QUrl( "https://wbsapi.withings.net/measure?" + params.toString() );

                printd("URL: %s\n", url.url().toStdString().c_str());

                QNetworkRequest request(url);
                //request.setRawHeader("Authorization", QString("Bearer %1").arg(access_token).toLatin1());

                nam->get(request);

                emit downloadProgress(50);

                // blocking request
                loop.exec(); // we go on after receiving the data in SLOT(onRequestReady(QByteArray))

                emit downloadEnded(100);

        }

    }
    printd("response: %s\n", response.toStdString().c_str());

    QJsonParseError parseResult;
    if (response.contains("\"status\":0", Qt::CaseInsensitive)) {
    		parseResult = parse(response, data);
    } else {
        QMessageBox oautherr(QMessageBox::Critical, tr("Error"),
                             tr("There was an error during fetching. Please check the error description."));
        oautherr.setDetailedText(response); // probably blank
        oautherr.exec();
        return false;

    }

    if (QJsonParseError::NoError != parseResult.error) {
        QMessageBox oautherr(QMessageBox::Critical, tr("Error"),
                             tr("Error parsing Withings API response. Please check the error description."));
        QString errorStr = parseResult.errorString() + " at offset " + QString::number(parseResult.offset);
        error = errorStr.simplified();
        oautherr.setDetailedText(error);
        oautherr.exec();
        return false;
    };
    return true;
}
Exemple #25
0
Status_t Menu_Set_Time(struct Menu_State_s *Menu_State_p, const uint32 Key, void *Ptr)
{
    FuncIN(MENU_SET_TIME);

    Status_t Status = GENERAL_ERROR;
    RtcTime_t Time_s;
    static uint32 EnterFlag = 0;

    if(EnterFlag == 0)
    {
        RTC_Get_Time(&Time_s);

        Hour = Time_s.Hour;
        Minute = Time_s.Minute;
        Second = Time_s.Second;
    }

    clrd();
    printd(1, "Set Time");
    printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
    Menu_Time_Update_Disp_Ptr_Pos();

    printc("(%s): Enter! Key = 0x%08X\n", __func__, Key);

    switch(Key)
    {
    case ENTER_KEY_EVENT:
        // First enter in this state
        if(EnterFlag == 0)
        {
            EnterFlag = 1;
            break;
        }

        Time_s.Hour = Hour;
        Time_s.Minute = Minute;
        Time_s.Second = Second;

        Status = RTC_Set_Time(&Time_s);
        VERIFY(Status, Status);

        if(Status == SUCCESS)
            printd(2, "%02u:%02u:%02u Time Set!", Hour, Minute, Second);
        else
            printd(2, "%02u:%02u:%02u ERROR!!!", Hour, Minute, Second);

        break;
    case CANCEL_KEY_EVENT:
        clrd();

        Hour = 0;
        Minute = 0;
        Second = 0;

        PointerPosition = 1;

        EnterFlag = 0;

        EXIT_SUCCESS_FUNC(MENU_SET_TIME);
    case UP_KEY_EVENT:
        Menu_Time_Increment_Ptr_Pos_Number();
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case DOWN_KEY_EVENT:
        Menu_Time_Decrement_Ptr_Pos_Number();
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case LEFT_KEY_EVENT:
        if(PointerPosition > 1)
        {
            PointerPosition--;
            Menu_Time_Update_Disp_Ptr_Pos();
        }
        break;
    case RIGHT_KEY_EVENT:
        if(PointerPosition < 6)
        {
            PointerPosition++;
            Menu_Time_Update_Disp_Ptr_Pos();
        }
        break;
    case EXIT_KEY_EVENT:
        clrd();

        Hour = 0;
        Minute = 0;
        Second = 0;

        PointerPosition = 1;

        EnterFlag = 0;

        EXIT_SUCCESS_FUNC(MENU_SET_TIME);
    case MENU_KEY_EVENT:
        clrd();

        Hour = 0;
        Minute = 0;
        Second = 0;

        PointerPosition = 1;

        EnterFlag = 0;

        EXIT_SUCCESS_FUNC(MENU_SET_TIME);
    case NUM1_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(1);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM2_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(2);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM3_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(3);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM4_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(4);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM5_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(5);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM6_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(6);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM7_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(7);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM8_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(8);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM9_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(9);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    case NUM0_KEY_EVENT:
        Menu_Time_Set_Ptr_Pos_Number(0);
        printd(2, "%02u:%02u:%02u", Hour, Minute, Second);
        break;
    default:
        Fatal_Abort(-INVALID_INPUT_PARAMETER);
    } // switch(Key)

    syncd();

    EXIT_SUCCESS_FUNC(MENU_SET_TIME);
}
Exemple #26
0
static void printk(const char *descr, krb5_keyblock *k) {
    krb5_data d;
    d.data = (char *) k->contents;
    d.length = k->length;
    printd(descr, &d);
}
Exemple #27
0
int main(int argc, char* argv[])
{
	// Define our variables.
	FILE* load;
	uint16_t flash[0x10000];
	char leading[0x100];
	unsigned int i;
	bool uread = true;
	vm_t* vm;
	int nerrors;
	bstring ss, st;

	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file, or - to read from standard input.");
	struct arg_file* execution_dump_file = arg_file0("e", "execution-dump", "<file>", "Produce a very large execution dump file.");
	struct arg_lit* debug_mode = arg_lit0("d", "debug", "Show each executed instruction.");
	struct arg_lit* terminate_mode = arg_lit0("t", "show-on-terminate", "Show state of machine when program is terminated.");
	struct arg_lit* legacy_mode = arg_lit0("l", "legacy", "Automatically initialize hardware to legacy values.");
	struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
	struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
	struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
	struct arg_end* end = arg_end(20);
	void* argtable[] = { input_file, debug_mode, execution_dump_file, terminate_mode, legacy_mode, little_endian_mode, verbose, quiet, end };

	// Parse arguments.
	nerrors = arg_parse(argc, argv, argtable);

	version_print(bautofree(bfromcstr("Emulator")));
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "emulator");

		printd(LEVEL_DEFAULT, "syntax:\n    dtemu");
		arg_print_syntax(stderr, argtable, "\n");
		printd(LEVEL_DEFAULT, "options:\n");
		arg_print_glossary(stderr, argtable, "	  %-25s %s\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Set verbosity level.
	debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

	// Set global path variable.
	osutil_setarg0(bautofree(bfromcstr(argv[0])));

	// Set endianness.
	isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

	// Zero out the flash space.
	for (i = 0; i < 0x10000; i++)
		flash[i] = 0x0;

	// Zero out the leading space.
	for (i = 0; i < 0x100; i++)
		leading[i] = 0x0;

	// Load from either file or stdin.
	if (strcmp(input_file->filename[0], "-") != 0)
	{
		// Open file.
		load = fopen(input_file->filename[0], "rb");

		if (load == NULL)
		{
			fprintf(stderr, "emulator: unable to load %s from disk.\n", argv[1]);
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
	}
	else
	{
		// Windows needs stdin in binary mode.
#ifdef _WIN32
		_setmode(_fileno(stdin), _O_BINARY);
#endif

		// Set load to stdin.
		load = stdin;
	}

	// Read up to 0x10000 words.
	for (i = 0; i < 0x10000 && !feof(load); i++)
		iread(&flash[i], load);
	fclose(load);

	// Check to see if the first X bytes matches the header
	// for intermediate code and stop if it does.
	ss = bfromcstr("");
	st = bfromcstr(ldata_objfmt);
	for (i = 0; i < strlen(ldata_objfmt); i++)
		bconchar(ss, leading[i]);
	if (biseq(ss, st))
	{
		fprintf(stderr, "emulator: it appears you passed intermediate code for execution.  link\n");
		fprintf(stderr, "	   the input code with the toolchain linker to execute it.\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// And then use the VM.
	vm = vm_create();
	vm->debug = (debug_mode->count > 0);
	vm_flash(vm, flash);
	vm_hw_timer_init(vm);
	vm_hw_io_init(vm);
	vm_hw_lem1802_init(vm);
	vm_hw_lua_init(vm);
	if (legacy_mode->count > 0)
	{
		vm_hw_lem1802_mem_set_screen(vm, 0x8000);
		vm_hw_io_set_legacy(true);
	}
	vm_execute(vm, execution_dump_file->count > 0 ? execution_dump_file->filename[0] : NULL);

#ifdef __EMSCRIPTEN__
	printd(LEVEL_WARNING, "warning: not cleaning up resources in Emscripten.\n");
#else
	if (terminate_mode->count > 0)
	{
		fprintf(stderr, "\n");
		fprintf(stderr, "A:   0x%04X	 [A]:	0x%04X\n", vm->registers[REG_A], vm->ram[vm->registers[REG_A]]);
		fprintf(stderr, "B:   0x%04X	 [B]:	0x%04X\n", vm->registers[REG_B], vm->ram[vm->registers[REG_B]]);
		fprintf(stderr, "C:   0x%04X	 [C]:	0x%04X\n", vm->registers[REG_C], vm->ram[vm->registers[REG_C]]);
		fprintf(stderr, "X:   0x%04X	 [X]:	0x%04X\n", vm->registers[REG_X], vm->ram[vm->registers[REG_X]]);
		fprintf(stderr, "Y:   0x%04X	 [Y]:	0x%04X\n", vm->registers[REG_Y], vm->ram[vm->registers[REG_Y]]);
		fprintf(stderr, "Z:   0x%04X	 [Z]:	0x%04X\n", vm->registers[REG_Z], vm->ram[vm->registers[REG_Z]]);
		fprintf(stderr, "I:   0x%04X	 [I]:	0x%04X\n", vm->registers[REG_I], vm->ram[vm->registers[REG_I]]);
		fprintf(stderr, "J:   0x%04X	 [J]:	0x%04X\n", vm->registers[REG_J], vm->ram[vm->registers[REG_J]]);
		fprintf(stderr, "PC:  0x%04X	 SP:	0x%04X\n", vm->pc, vm->sp);
		fprintf(stderr, "EX:  0x%04X	 IA:	0x%04X\n", vm->ex, vm->ia);
	}

	vm_hw_lua_free(vm);
	vm_hw_timer_free(vm);
	vm_hw_io_free(vm);
	vm_hw_lem1802_free(vm);
	vm_free(vm);

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
#endif
}
Exemple #28
0
static void test_cts()
{
    static const char input[4*16] =
        "I would like the General Gau's Chicken, please, and wonton soup.";
    static const unsigned char aeskey[16] = "chicken teriyaki";
    static const int lengths[] = { 17, 31, 32, 47, 48, 64 };

    unsigned int i;
    char outbuf[64], encivbuf[16], decivbuf[16];
    krb5_crypto_iov iov;
    krb5_data in, enciv, deciv;
    krb5_keyblock keyblock;
    krb5_key key;
    krb5_error_code err;

    iov.flags = KRB5_CRYPTO_TYPE_DATA;
    iov.data.data = outbuf;
    in.data = (char *)input;
    enciv.length = deciv.length = 16;
    enciv.data = encivbuf;
    deciv.data = decivbuf;
    keyblock.contents = (krb5_octet *)aeskey;
    keyblock.length = 16;
    keyblock.enctype = ENCTYPE_AES128_CTS_HMAC_SHA1_96;

    err = krb5_k_create_key(NULL, &keyblock, &key);
    if (err) {
        printf("error %ld from krb5_k_create_key\n", (long)err);
        exit(1);
    }

    memset(enciv.data, 0, 16);
    printk("AES 128-bit key", &keyblock);
    for (i = 0; i < sizeof(lengths)/sizeof(lengths[0]); i++) {
        memset(enciv.data, 0, 16);
        memset(deciv.data, 0, 16);

        printf("\n");
        iov.data.length = in.length = lengths[i];
        memcpy(outbuf, input, lengths[i]);
        printd("IV", &enciv);
        err = krb5int_aes_encrypt(key, &enciv, &iov, 1);
        if (err) {
            printf("error %ld from krb5int_aes_encrypt\n", (long)err);
            exit(1);
        }
        printd("Input", &in);
        printd("Output", &iov.data);
        printd("Next IV", &enciv);
        err = krb5int_aes_decrypt(key, &deciv, &iov, 1);
        if (err) {
            printf("error %ld from krb5int_aes_decrypt\n", (long)err);
            exit(1);
        }
        if (memcmp(outbuf, input, lengths[i]) != 0) {
            printd("Decryption result DOESN'T MATCH", &iov.data);
            exit(1);
        }
        if (memcmp(enciv.data, deciv.data, 16)) {
            printd("Decryption IV result DOESN'T MATCH", &deciv);
            exit(1);
        }
    }
    krb5_k_free_key(NULL, key);
}
/**
@brief "expose-event"/"draw" signal callback
@param widget where the signal was initiated
@param cr pointer to cairo data OR event pointer to event data
@param rt pointer to runtime data

@return FALSE always
*/
static gboolean _e2_gesture_dialog_exposed_cb (GtkWidget *widget,
#ifdef USE_GTK3_0
 cairo_t *cr,
#else
 GdkEventExpose *event,
#endif
 E2_GestureDialogRuntime *rt)
{
	//this arrives third during dialog creation, and also later
	printd (DEBUG, "drawing area exposed");

	NEEDCLOSEBGL
#ifdef USE_GTK2_18
	if (gtk_widget_get_visible (widget))
#else
	if (GTK_WIDGET_VISIBLE (widget))
#endif
	{
		guint indx;
		gpointer points_array;
		GdkPoint *pd;
#ifndef USE_GTK3_0
		if (rt->gc == NULL)
		{
			GtkStyle *style = gtk_widget_get_style (widget);
			rt->gc = style->black_gc;
		}
#endif
		gint npoints = stroke_get_count (rt->handle);

		if (npoints == 0)
		{
			if (rt->sequence != NULL)
			{
				printd (DEBUG, "recontruct stroke from runtime content");
				stroke_fake (rt->handle, rt->sequence);
				npoints = stroke_replay (rt->handle, &points_array);
			}
			else
			{
				const gchar *sequence = gtk_entry_get_text (GTK_ENTRY (rt->entry));
				if (*sequence != '\0')
				{
					printd (DEBUG, "recontruct stroke from entry content");
					stroke_fake (rt->handle, sequence);
					npoints = stroke_replay (rt->handle, &points_array);
				}
			}

			if (npoints > 0)
			{
#ifdef USE_GTK3_0
				_e2_gesture_dialog_cairo_setup (cr, widget);
				for (pd = (GdkPoint *)points_array, indx = 0; indx < npoints; pd++, indx++)
					cairo_line_to (cr, (gdouble)pd->x, (gdouble)pd->y);
				cairo_stroke (cr);
#else
				GtkAllocation alloc;
# ifdef USE_GTK2_18
				gtk_widget_get_allocation (widget, &alloc);
# else
				alloc = widget->allocation;
# endif
				stroke_get_scale (rt->handle, &alloc.x, &alloc.y);

				gfloat xfactor = (gfloat)alloc.width / alloc.x;
				gfloat yfactor = (gfloat)alloc.height / alloc.y;
				if (xfactor == 1. && yfactor == 1.)
				{
					//CHECKME what's happening here?
					gdk_draw_points (GDK_DRAWABLE (event->window), rt->gc,
						(GdkPoint *)points_array, npoints);
				}
				else
				{
					for (pd = (GdkPoint *)points_array, indx = 0; indx < npoints; pd++, indx++)
					{
						pd->x *= xfactor;
						pd->y *= yfactor;
					}
					gdk_draw_lines (GDK_DRAWABLE (event->window), rt->gc,
						(GdkPoint *)points_array, npoints);
				}
#endif
				free (points_array); //not g_free()
				stroke_clear (rt->handle);
			}
		}
		else
		{
			npoints = stroke_replay (rt->handle, &points_array);
			printd (DEBUG, "exposure - redraw existing stroke with %d points", npoints);
#ifdef USE_GTK3_0
			_e2_gesture_dialog_cairo_setup (cr, widget);
			for (pd = (GdkPoint *)points_array, indx = 0; indx < npoints; pd++, indx++)
				cairo_line_to (cr, (gdouble)pd->x, (gdouble)pd->y);
			cairo_stroke (cr);
#else
			gdk_draw_points (GDK_DRAWABLE (event->window), rt->gc,
				(GdkPoint *)points_array, npoints);
#endif
			free (points_array); //not g_free()
		}
	}

	NEEDOPENBGL
	return FALSE;
}
Exemple #30
0
const float& ArgumentVector::Argument::get(float& dst) const {
	if (type != Argument::FLOAT)
		printd(WARNING, "Argument::get(): WARNING: conversion from non-float to float type!\n");
	dst = *((float*)value);
	return dst;
} // get