Example #1
0
static void setupArguments(bContext *C, bArgs *ba, SYS_SystemHandle *syshandle)
{
	static char output_doc[] = "<path>"
		"\n\tSet the render path and file name."
		"\n\tUse // at the start of the path to"
		"\n\t\trender relative to the blend file."
		"\n\tThe # characters are replaced by the frame number, and used to define zero padding."
		"\n\t\tani_##_test.png becomes ani_01_test.png"
		"\n\t\ttest-######.png becomes test-000001.png"
		"\n\t\tWhen the filename does not contain #, The suffix #### is added to the filename"
		"\n\tThe frame number will be added at the end of the filename."
		"\n\t\teg: blender -b foobar.blend -o //render_ -F PNG -x 1 -a"
		"\n\t\t//render_ becomes //render_####, writing frames as //render_0001.png//";

	static char format_doc[] = "<format>"
		"\n\tSet the render format, Valid options are..."
		"\n\t\tTGA IRIS JPEG MOVIE IRIZ RAWTGA"
		"\n\t\tAVIRAW AVIJPEG PNG BMP FRAMESERVER"
		"\n\t(formats that can be compiled into blender, not available on all systems)"
		"\n\t\tHDR TIFF EXR MULTILAYER MPEG AVICODEC QUICKTIME CINEON DPX DDS";

	static char playback_doc[] = "<options> <file(s)>"
		"\n\tPlayback <file(s)>, only operates this way when not running in background."
		"\n\t\t-p <sx> <sy>\tOpen with lower left corner at <sx>, <sy>"
		"\n\t\t-m\t\tRead from disk (Don't buffer)"
		"\n\t\t-f <fps> <fps-base>\t\tSpecify FPS to start with"
		"\n\t\t-j <frame>\tSet frame step to <frame>"
		"\n\t\t-s <frame>\tPlay from <frame>"
		"\n\t\t-e <frame>\tPlay until <frame>";

	static char game_doc[] = "Game Engine specific options"
		"\n\t-g fixedtime\t\tRun on 50 hertz without dropping frames"
		"\n\t-g vertexarrays\t\tUse Vertex Arrays for rendering (usually faster)"
		"\n\t-g nomipmap\t\tNo Texture Mipmapping"
		"\n\t-g linearmipmap\t\tLinear Texture Mipmapping instead of Nearest (default)";

	static char debug_doc[] = "\n\tTurn debugging on\n"
		"\n\t* Prints every operator call and their arguments"
		"\n\t* Disables mouse grab (to interact with a debugger in some cases)"
		"\n\t* Keeps python sys.stdin rather than setting it to None";

	//BLI_argsAdd(ba, pass, short_arg, long_arg, doc, cb, C);

	/* end argument processing after -- */
	BLI_argsAdd(ba, -1, "--", NULL, "\n\tEnds option processing, following arguments passed unchanged. Access via python's sys.argv", end_arguments, NULL);

	/* first pass: background mode, disable python and commands that exit after usage */
	BLI_argsAdd(ba, 1, "-h", "--help", "\n\tPrint this help text and exit", print_help, ba);
	/* Windows only */
	BLI_argsAdd(ba, 1, "/?", NULL, "\n\tPrint this help text and exit (windows only)", print_help, ba);

	BLI_argsAdd(ba, 1, "-v", "--version", "\n\tPrint Blender version and exit", print_version, NULL);
	
	/* only to give help message */
#ifndef WITH_PYTHON_SECURITY /* default */
#  define   PY_ENABLE_AUTO ", (default)"
#  define   PY_DISABLE_AUTO ""
#else
#  define   PY_ENABLE_AUTO ""
#  define   PY_DISABLE_AUTO ", (compiled as non-standard default)"
#endif

	BLI_argsAdd(ba, 1, "-y", "--enable-autoexec", "\n\tEnable automatic python script execution" PY_ENABLE_AUTO, enable_python, NULL);
	BLI_argsAdd(ba, 1, "-Y", "--disable-autoexec", "\n\tDisable automatic python script execution (pydrivers & startup scripts)" PY_DISABLE_AUTO, disable_python, NULL);

	BLI_argsAdd(ba, 1, NULL, "--disable-crash-handler", "\n\tDisable the crash handler", disable_crash_handler, NULL);

#undef PY_ENABLE_AUTO
#undef PY_DISABLE_AUTO
	
	BLI_argsAdd(ba, 1, "-b", "--background", "<file>\n\tLoad <file> in background (often used for UI-less rendering)", background_mode, NULL);

	BLI_argsAdd(ba, 1, "-a", NULL, playback_doc, playback_mode, NULL);

	BLI_argsAdd(ba, 1, "-d", "--debug", debug_doc, debug_mode, ba);

#ifdef WITH_FFMPEG
	BLI_argsAdd(ba, 1, NULL, "--debug-ffmpeg", "\n\tEnable debug messages from FFmpeg library", debug_mode_generic, (void *)G_DEBUG_FFMPEG);
#endif

#ifdef WITH_FREESTYLE
	BLI_argsAdd(ba, 1, NULL, "--debug-freestyle", "\n\tEnable debug/profiling messages from Freestyle rendering", debug_mode_generic, (void *)G_DEBUG_FREESTYLE);
#endif

	BLI_argsAdd(ba, 1, NULL, "--debug-python", "\n\tEnable debug messages for python", debug_mode_generic, (void *)G_DEBUG_PYTHON);
	BLI_argsAdd(ba, 1, NULL, "--debug-events", "\n\tEnable debug messages for the event system", debug_mode_generic, (void *)G_DEBUG_EVENTS);
	BLI_argsAdd(ba, 1, NULL, "--debug-handlers", "\n\tEnable debug messages for event handling", debug_mode_generic, (void *)G_DEBUG_HANDLERS);
	BLI_argsAdd(ba, 1, NULL, "--debug-wm",     "\n\tEnable debug messages for the window manager", debug_mode_generic, (void *)G_DEBUG_WM);
	BLI_argsAdd(ba, 1, NULL, "--debug-all",    "\n\tEnable all debug messages (excludes libmv)", debug_mode_generic, (void *)G_DEBUG_ALL);

	BLI_argsAdd(ba, 1, NULL, "--debug-fpe", "\n\tEnable floating point exceptions", set_fpe, NULL);

#ifdef WITH_LIBMV
	BLI_argsAdd(ba, 1, NULL, "--debug-libmv", "\n\tEnable debug messages from libmv library", debug_mode_libmv, NULL);
#endif

	BLI_argsAdd(ba, 1, NULL, "--debug-value", "<value>\n\tSet debug value of <value> on startup\n", set_debug_value, NULL);
	BLI_argsAdd(ba, 1, NULL, "--debug-jobs",  "\n\tEnable time profiling for background jobs.", debug_mode_generic, (void *)G_DEBUG_JOBS);

	BLI_argsAdd(ba, 1, NULL, "--verbose", "<verbose>\n\tSet logging verbosity level.", set_verbosity, NULL);

	BLI_argsAdd(ba, 1, NULL, "--factory-startup", "\n\tSkip reading the "STRINGIFY (BLENDER_STARTUP_FILE)" in the users home directory", set_factory_startup, NULL);

	/* TODO, add user env vars? */
	BLI_argsAdd(ba, 1, NULL, "--env-system-datafiles",  "\n\tSet the "STRINGIFY_ARG (BLENDER_SYSTEM_DATAFILES)" environment variable", set_env, NULL);
	BLI_argsAdd(ba, 1, NULL, "--env-system-scripts",    "\n\tSet the "STRINGIFY_ARG (BLENDER_SYSTEM_SCRIPTS)" environment variable", set_env, NULL);
	BLI_argsAdd(ba, 1, NULL, "--env-system-python",     "\n\tSet the "STRINGIFY_ARG (BLENDER_SYSTEM_PYTHON)" environment variable", set_env, NULL);

	/* second pass: custom window stuff */
	BLI_argsAdd(ba, 2, "-p", "--window-geometry", "<sx> <sy> <w> <h>\n\tOpen with lower left corner at <sx>, <sy> and width and height as <w>, <h>", prefsize, NULL);
	BLI_argsAdd(ba, 2, "-w", "--window-border", "\n\tForce opening with borders (default)", with_borders, NULL);
	BLI_argsAdd(ba, 2, "-W", "--window-borderless", "\n\tForce opening without borders", without_borders, NULL);
	BLI_argsAdd(ba, 2, "-con", "--start-console", "\n\tStart with the console window open (ignored if -b is set), (Windows only)", start_with_console, NULL);
	BLI_argsAdd(ba, 2, "-R", NULL, "\n\tRegister .blend extension, then exit (Windows only)", register_extension, NULL);
	BLI_argsAdd(ba, 2, "-r", NULL, "\n\tSilently register .blend extension, then exit (Windows only)", register_extension, ba);
	BLI_argsAdd(ba, 2, NULL, "--no-native-pixels", "\n\tDo not use native pixel size, for high resolution displays (MacBook 'Retina')", native_pixels, ba);

	/* third pass: disabling things and forcing settings */
	BLI_argsAddCase(ba, 3, "-nojoystick", 1, NULL, 0, "\n\tDisable joystick support", no_joystick, syshandle);
	BLI_argsAddCase(ba, 3, "-noglsl", 1, NULL, 0, "\n\tDisable GLSL shading", no_glsl, NULL);
	BLI_argsAddCase(ba, 3, "-noaudio", 1, NULL, 0, "\n\tForce sound system to None", no_audio, NULL);
	BLI_argsAddCase(ba, 3, "-setaudio", 1, NULL, 0, "\n\tForce sound system to a specific device\n\tNULL SDL OPENAL JACK", set_audio, NULL);

	/* fourth pass: processing arguments */
	BLI_argsAdd(ba, 4, "-g", NULL, game_doc, set_ge_parameters, syshandle);
	BLI_argsAdd(ba, 4, "-f", "--render-frame", "<frame>\n\tRender frame <frame> and save it.\n\t+<frame> start frame relative, -<frame> end frame relative.", render_frame, C);
	BLI_argsAdd(ba, 4, "-a", "--render-anim", "\n\tRender frames from start to end (inclusive)", render_animation, C);
	BLI_argsAdd(ba, 4, "-S", "--scene", "<name>\n\tSet the active scene <name> for rendering", set_scene, C);
	BLI_argsAdd(ba, 4, "-s", "--frame-start", "<frame>\n\tSet start to frame <frame> (use before the -a argument)", set_start_frame, C);
	BLI_argsAdd(ba, 4, "-e", "--frame-end", "<frame>\n\tSet end to frame <frame> (use before the -a argument)", set_end_frame, C);
	BLI_argsAdd(ba, 4, "-j", "--frame-jump", "<frames>\n\tSet number of frames to step forward after each rendered frame", set_skip_frame, C);
	BLI_argsAdd(ba, 4, "-P", "--python", "<filename>\n\tRun the given Python script file", run_python_file, C);
	BLI_argsAdd(ba, 4, NULL, "--python-text", "<name>\n\tRun the given Python script text block", run_python_text, C);
	BLI_argsAdd(ba, 4, NULL, "--python-console", "\n\tRun blender with an interactive console", run_python_console, C);
	BLI_argsAdd(ba, 4, NULL, "--addons", "\n\tComma separated list of addons (no spaces)", set_addons, C);

	BLI_argsAdd(ba, 4, "-o", "--render-output", output_doc, set_output, C);
	BLI_argsAdd(ba, 4, "-E", "--engine", "<engine>\n\tSpecify the render engine\n\tuse -E help to list available engines", set_engine, C);

	BLI_argsAdd(ba, 4, "-F", "--render-format", format_doc, set_image_type, C);
	BLI_argsAdd(ba, 4, "-t", "--threads", "<threads>\n\tUse amount of <threads> for rendering and other operations\n\t[1-" STRINGIFY(BLENDER_MAX_THREADS) "], 0 for systems processor count.", set_threads, NULL);
	BLI_argsAdd(ba, 4, "-x", "--use-extension", "<bool>\n\tSet option to add the file extension to the end of the file", set_extension, C);

}
Example #2
0
		kr = mach_msg(&hdr, MACH_RCV_LARGE | MACH_RCV_MSG, 0, hdr.msgh_size, gPort, 0, 0);
		if (MACH_RCV_TOO_LARGE != kr) helplog(ASL_LEVEL_ERR, "kr: %d: %s", kr, mach_error_string(kr));
		
		safe_vproc_transaction_begin();
		
		kr = mach_msg_server_once(helper_server, MAX_MSG_SIZE, gPort,
			MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT) | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0));
		if (KERN_SUCCESS != kr)
			{ helplog(ASL_LEVEL_ERR, "mach_msg_server: %s\n", mach_error_string(kr)); exit(EXIT_FAILURE); }
		
		safe_vproc_transaction_end();
		}
	exit(EXIT_SUCCESS);
	}

// Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
// e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
// To expand "version" to its value before making the string, use STRINGIFY(version) instead
#define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
#define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)

// For convenience when using the "strings" command, this is the last thing in the file
// The "@(#) " pattern is a special prefix the "what" command looks for
const char VersionString_SCCS[] = "@(#) mDNSResponderHelper " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";

#if _BUILDING_XCODE_PROJECT_
// If the process crashes, then this string will be magically included in the automatically-generated crash log
const char *__crashreporter_info__ = VersionString_SCCS + 5;
asm(".desc ___crashreporter_info__, 0x10");
#endif
Example #3
0
struct image_t *viewvideo_function(struct image_t *img)
{
  // Resize image if needed
  struct image_t img_small;
  image_create(&img_small,
               img->w / viewvideo.downsize_factor,
               img->h / viewvideo.downsize_factor,
               IMAGE_YUV422);

  // Create the JPEG encoded image
  struct image_t img_jpeg;
  image_create(&img_jpeg, img_small.w, img_small.h, IMAGE_JPEG);

#if VIEWVIDEO_USE_NETCAT
  char nc_cmd[64];
  sprintf(nc_cmd, "nc %s %d 2>/dev/null", STRINGIFY(VIEWVIDEO_HOST), VIEWVIDEO_PORT_OUT);
#endif

  if (viewvideo.is_streaming) {

    // Only resize when needed
    if (viewvideo.downsize_factor != 1) {
      image_yuv422_downsample(img, &img_small, viewvideo.downsize_factor);
      jpeg_encode_image(&img_small, &img_jpeg, VIEWVIDEO_QUALITY_FACTOR, VIEWVIDEO_USE_NETCAT);
    } else {
      jpeg_encode_image(img, &img_jpeg, VIEWVIDEO_QUALITY_FACTOR, VIEWVIDEO_USE_NETCAT);
    }

#if VIEWVIDEO_USE_NETCAT
    // Open process to send using netcat (in a fork because sometimes kills itself???)
    pid_t pid = fork();

    if (pid < 0) {
      printf("[viewvideo] Could not create netcat fork.\n");
    } else if (pid == 0) {
      // We are the child and want to send the image
      FILE *netcat = popen(nc_cmd, "w");
      if (netcat != NULL) {
        fwrite(img_jpeg.buf, sizeof(uint8_t), img_jpeg.buf_size, netcat);
        pclose(netcat); // Ignore output, because it is too much when not connected
      } else {
        printf("[viewvideo] Failed to open netcat process.\n");
      }

      // Exit the program since we don't want to continue after transmitting
      exit(0);
    } else {
      // We want to wait until the child is finished
      wait(NULL);
    }
#else
    if (viewvideo.use_rtp) {

      // Send image with RTP
      rtp_frame_send(
        &video_sock,              // UDP socket
        &img_jpeg,
        0,                        // Format 422
        VIEWVIDEO_QUALITY_FACTOR, // Jpeg-Quality
        0,                        // DRI Header
        VIEWVIDEO_RTP_TIME_INC    // 90kHz time increment
      );
      // Extra note: when the time increment is set to 0,
      // it is automaticaly calculated by the send_rtp_frame function
      // based on gettimeofday value. This seems to introduce some lag or jitter.
      // An other way is to compute the time increment and set the correct value.
      // It seems that a lower value is also working (when the frame is received
      // the timestamp is always "late" so the frame is displayed immediately).
      // Here, we set the time increment to the lowest possible value
      // (1 = 1/90000 s) which is probably stupid but is actually working.
    }
#endif

  }

  // Free all buffers
  image_free(&img_jpeg);
  image_free(&img_small);
  return NULL; // No new images were created
}
/** Write accounting data to Couchbase documents
 *
 * Handle accounting requests and store the associated data into JSON documents
 * in couchbase mapping attribute names to JSON element names per the module configuration.
 *
 * When an existing document already exists for the same accounting section the new attributes
 * will be merged with the currently existing data.  When conflicts arrise the new attribute
 * value will replace or be added to the existing value.
 *
 * @param instance The module instance.
 * @param request  The accounting request object.
 * @return Operation status (#rlm_rcode_t).
 */
static rlm_rcode_t mod_accounting(void *instance, REQUEST *request)
{
	rlm_couchbase_t *inst = instance;       /* our module instance */
	rlm_couchbase_handle_t *handle = NULL;  /* connection pool handle */
	rlm_rcode_t rcode = RLM_MODULE_OK;      /* return code */
	VALUE_PAIR *vp;                         /* radius value pair linked list */
	char buffer[MAX_KEY_SIZE];
	char const *dockey;			/* our document key */
	char document[MAX_VALUE_SIZE];          /* our document body */
	char element[MAX_KEY_SIZE];             /* mapped radius attribute to element name */
	int status = 0;                         /* account status type */
	int docfound = 0;                       /* document found toggle */
	lcb_error_t cb_error = LCB_SUCCESS;     /* couchbase error holder */
	ssize_t slen;

	/* assert packet as not null */
	rad_assert(request->packet != NULL);

	/* sanity check */
	if ((vp = fr_pair_find_by_num(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) == NULL) {
		/* log debug */
		RDEBUG("could not find status type in packet");
		/* return */
		return RLM_MODULE_NOOP;
	}

	/* set status */
	status = vp->vp_integer;

	/* acknowledge the request but take no action */
	if (status == PW_STATUS_ACCOUNTING_ON || status == PW_STATUS_ACCOUNTING_OFF) {
		/* log debug */
		RDEBUG("handling accounting on/off request without action");
		/* return */
		return RLM_MODULE_OK;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set couchbase instance */
	lcb_t cb_inst = handle->handle;

	/* set cookie */
	cookie_t *cookie = handle->cookie;

	/* attempt to build document key */
	slen = tmpl_expand(&dockey, buffer, sizeof(buffer), request, inst->acct_key, NULL, NULL);
	if (slen < 0) {
		rcode = RLM_MODULE_FAIL;
		goto finish;
	}
	if ((dockey == buffer) && is_truncated((size_t)slen, sizeof(buffer))) {
		REDEBUG("Key too long, expected < " STRINGIFY(sizeof(buffer)) " bytes, got %zi bytes", slen);
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* attempt to fetch document */
	cb_error = couchbase_get_key(cb_inst, cookie, dockey);

	/* check error and object */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) {
		/* log error */
		RERROR("failed to execute get request or parse returned json object");
		/* free and reset json object */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
			cookie->jobj = NULL;
		}
	/* check cookie json object */
	} else if (cookie->jobj) {
		/* set doc found */
		docfound = 1;
		/* debugging */
		RDEBUG3("parsed json body from couchbase: %s", json_object_to_json_string(cookie->jobj));
	}

	/* start json document if needed */
	if (docfound != 1) {
		/* debugging */
		RDEBUG("no existing document found - creating new json document");
		/* create new json object */
		cookie->jobj = json_object_new_object();
		/* set 'docType' element for new document */
		json_object_object_add(cookie->jobj, "docType", json_object_new_string(inst->doctype));
		/* default startTimestamp and stopTimestamp to null values */
		json_object_object_add(cookie->jobj, "startTimestamp", NULL);
		json_object_object_add(cookie->jobj, "stopTimestamp", NULL);
	}

	/* status specific replacements for start/stop time */
	switch (status) {
	case PW_STATUS_START:
		/* add start time */
		if ((vp = fr_pair_find_by_num(request->packet->vps, PW_EVENT_TIMESTAMP, 0, TAG_ANY)) != NULL) {
			/* add to json object */
			json_object_object_add(cookie->jobj, "startTimestamp",
					       mod_value_pair_to_json_object(request, vp));
		}
		break;

	case PW_STATUS_STOP:
		/* add stop time */
		if ((vp = fr_pair_find_by_num(request->packet->vps, PW_EVENT_TIMESTAMP, 0, TAG_ANY)) != NULL) {
			/* add to json object */
			json_object_object_add(cookie->jobj, "stopTimestamp",
					       mod_value_pair_to_json_object(request, vp));
		}
		/* check start timestamp and adjust if needed */
		mod_ensure_start_timestamp(cookie->jobj, request->packet->vps);
		break;

	case PW_STATUS_ALIVE:
		/* check start timestamp and adjust if needed */
		mod_ensure_start_timestamp(cookie->jobj, request->packet->vps);
		break;

	default:
		/* don't doing anything */
		rcode = RLM_MODULE_NOOP;
		/* return */
		goto finish;
	}

	/* loop through pairs and add to json document */
	for (vp = request->packet->vps; vp; vp = vp->next) {
		/* map attribute to element */
		if (mod_attribute_to_element(vp->da->name, inst->map, &element) == 0) {
			/* debug */
			RDEBUG3("mapped attribute %s => %s", vp->da->name, element);
			/* add to json object with mapped name */
			json_object_object_add(cookie->jobj, element, mod_value_pair_to_json_object(request, vp));
		}
	}

	/* copy json string to document and check size */
	if (strlcpy(document, json_object_to_json_string(cookie->jobj), sizeof(document)) >= sizeof(document)) {
		/* this isn't good */
		RERROR("could not write json document - insufficient buffer space");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* debugging */
	RDEBUG3("setting '%s' => '%s'", dockey, document);

	/* store document/key in couchbase */
	cb_error = couchbase_set_key(cb_inst, dockey, document, inst->expire);

	/* check return */
	if (cb_error != LCB_SUCCESS) {
		RERROR("failed to store document (%s): %s (0x%x)", dockey, lcb_strerror(NULL, cb_error), cb_error);
	}

finish:
	/* free and reset json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* release our connection handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return rcode;
}
Example #5
0
#include "atm.h"
#include "atm_bridge.h"
#include "frame_relay.h"
#include "eth_switch.h"
#ifdef GEN_ETH
#include "gen_eth.h"
#endif
#ifdef PROFILE
#include "profiler.h"
#endif

/* Default name for logfile */
#define LOGFILE_DEFAULT_NAME  "dynamips_log.txt"

/* Operating system name */
const char *os_name = STRINGIFY(OSNAME);

/* Software version */
const char *sw_version = DYNAMIPS_VERSION"-"JIT_ARCH;

/* Software version tag */
const char *sw_version_tag = "2015060118";

/* Hypervisor */
int hypervisor_mode = 0;
int hypervisor_tcp_port = 0;
char *hypervisor_ip_address = NULL;

/* Log file */
char *log_file_name = NULL;
FILE *log_file = NULL;
Example #6
0
int main(void) {

    /*
    # Comments are replaced by spaces.
    */
    {
        int/* */a = 1;
        assert(a == 1);
    }

    /*
    # Newline in macro

    # Multiline macro

        Impossible:

        - http://stackoverflow.com/questions/10419530/multi-line-preprocessor-macros
        - http://stackoverflow.com/questions/98944/how-to-generate-a-newline-in-a-cpp-macro
    */

    /*
    # #define

        You can put preprocessor directives anywhere
        but putting on global scope is the more standard and simple approach

        Use defines with discretion: they make it much harder to debug!
    */
    {

        /*
        Syntax: the line must start with `#`,
        but there can be spaces after it to give indentation.
        */
        {
#define SPACE_AFTER_HASH 1
            assert(SPACE_AFTER_HASH == 1);
        }

        /*
        # Constants

            Use sparingly.

            - constants have scope
            - produce meaningful error messages
        */
        {
            {
#define CTE 1
                assert(CTE == 1);
            }

            /*
            Don't forget to protect arithmetic operations
            or associativity may get you.
            */
            {
                /* Use parenthesis or order of operation might destroy you: */
#define PROTECT_FAIL 1 + 1
                assert(PROTECT_FAIL * 2 == 3);
#define PROTECT (1 + 1)
                assert(PROTECT * 2 == 4);
            }

            /*
            Expansion is lazy: macros do not expand in `#define`
            but only when the macro is used.
            */
            {
#define LAZY0 LAZY1
#define LAZY1 LAZY2
#define LAZY2 2
                assert(LAZY2 == 2);
            }
        }

        /* # Redefine macros */
        {
            /* Cannot redefine macros directly. */
            {
#define REDEFINE_FAIL 1
                /* ERROR */
                /*#define REDEFINE_FAIL 2*/
            }

            /* Must first undef. */
            {
#define REDEFINE 1
#undef REDEFINE
#define REDEFINE 2
                assert(REDEFINE == 2);
            }
        }

        /* # Functions (preprocessor) */
        {
            /*
            Generates:

                assert(1 + 1 == 2);

            Not:

                assert(2 == 2);
            */
            {
#define SUM(x, y) x + y
                assert(SUM(1, 1) == 2);
            }

            /*
            # Comma protection

                The macro engine has to do some kind of parsing to determine that
                the comma of the function (1) is not the comma of the macro (2).

                What it seems to do is simply check if the comma is between pairs of:

                - parenthesis
                - double quotes

                and if yes ignore it.

                This does not however cover C++ template parameters, and `assert` + template is a common break case
                http://stackoverflow.com/questions/4496842/pass-method-with-template-arguments-to-a-macro

                Pure C also has cases in which it is necessary to use parenthesis,
                for example when the comma operator is used.

                A more complicated case in which protecting parenthesis break:
                http://stackoverflow.com/questions/9187614/how-do-i-have-a-comma-inside-braces-inside-a-macro-argument-when-parentheses-cau
            */
            {
                assert(SUM(int_int_int_func(1, 1), 1) == 3);
                /*                           ^   ^ */
                /*                           1   2 */

                int i = 1;
                assert(SUM((i++, i), 1) == 3);
                /*                 ^ */
                /*                 comma operator */

                /* ERROR must protect the comma operator. */
                /*assert(SUM(i++, i, 1) == 3);*/

#define CAT(x, y) x y
                /* Strings are treated as a single token, so commas inside strings are fine. */
                assert(strcmp(CAT("1,", "2"), "1,2") == 0);
            }

            /*
            # Function inside argument

                - http://stackoverflow.com/questions/163365/how-do-i-make-a-c-macro-behave-like-a-function
                - http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros
            */
            {
                /* TODO */
            }

            /*
            # Argument inside string

            # #
            */
            {
                /* Strings are treated as single tokens, so arguments don't expand by default. */
#define ARG_IN_STRING_BAD(x) "x"
                assert(strcmp(ARG_IN_STRING_BAD("a"), "x") == 0);

                /*
                Solution: use # stringification.

                It simply adds "" around the argument and expands it.
                */
#define STRINGIFY(x) #x
                assert(strcmp(STRINGIFY(a), "a") == 0);
                assert(strcmp(STRINGIFY(""), "\"\"") == 0);
                /* ERROR: parsing fails because of unbalanced `"`. */
                /*assert(strcmp(STRINGIFY("), "\"") == 0);*/

#define STRINGIFY_CAT(x) "a" STRINGIFY(x) "c"
                assert(strcmp(STRINGIFY_CAT(b), "abc") == 0);

                /*
                This fails however for macro arguments, which don't expand when `# arg` is used!

                Solution Use a two step expansion process...

                - http://stackoverflow.com/questions/8283596/whats-the-difference-between-these-two-macros?lq=1
                - http://stackoverflow.com/questions/6742501/whats-the-exact-step-of-macro-expanding

                TODO what is the rationale for that exception of not expanding upon `#`?
                */
#define STRINGIFY_ARG a
                assert(strcmp(STRINGIFY(STRINGIFY_ARG), "STRINGIFY_ARG") == 0);
            }

            /* # variadic macro functions */
            {
                char s[4];
#define SPRINTF(string, format, ...) sprintf(string, format, __VA_ARGS__)
                SPRINTF(s, "%c%c", 'a', 'b');
                assert(strcmp(s, "ab") == 0);
            }

#if __STDC_VERSION__ >= 199901L
            /*
            # Empty macro arguments

                http://stackoverflow.com/questions/7666344/are-empty-macro-arguments-legal-in-c11
            */
            {
#define EMPTY(x) x ## 2 ==
                assert(EMPTY(1) 12);

                /*
                TODO if the argument is empty,
                does it still count for concatenation?
                */
                assert(EMPTY() 2);
            }
#endif
        }

        /*
        # #include

            It is possible, and very confusing, to include any type of file,
            not just header files.
        */
        {
            int i = 0;
#include "preprocessor.inc"
            assert(i == 1);
        }
    }

    /*
    # #undef

        Undo a previous define.
    */
    {
#define UNDEF_TEST 1
#undef UNDEF_TEST
#ifdef UNDEF_TEST
# error
#endif
    }

    /*
    # Concatenate

    # Double hash preprocessor operator

    # ##

        `##` allows to concatenate a preprocessor function arguments without spaces between them.
    */
    {
        /* Basic. */
        {
#define CAT_NO_SPACE(x) x ## d
            int CAT_NO_SPACE(c_) = 1;
            assert(c_d == 1);
        }

        /*
        Multiple concatenation insanity:
        http://stackoverflow.com/questions/1489932/c-preprocessor-and-concatenation
        */
        {
            {
#define CAT_FAIL_VAR 0
#define CAT_FAIL x ## CAT_FAIL_VAR
                int CAT_FAIL = 1;
                assert(xCAT_FAIL_VAR == 1);
            }

            /* Solution. */
            {
#define CAT_VAR 0
#define PASTER(x,y) x ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define CAT_OK EVALUATOR(x, CAT_VAR)
                int CAT_OK = 1;
                assert(x0 == 1);
            }
        }
    }

    /*
    # #ifdef

        Check if preprocessor variable is defined.

        # or and ifdef

            http://stackoverflow.com/questions/965700/c-preprocessor-testing-definedness-of-multiple-macros

            Almost the same as `#if defined()`,
            except you can use `#if defined()` with `|| on a single line as:

                #if defined(X) || defined(Y)

            while

                #ifdef(X) || ifdef(Y)
                #ifdef X || Y

            compiles but does not do what you expect:
            TODO legal?

            For `&&`, we could get away with:

                #ifdef(X)
                #ifdef(Y)

            but there is no alternative for `||`.

    # #ifndef

        Negation of ifdef.

    # #defined

        Like ifdef, but more flexible
        as you can use it inside `#if` with boolean operators.
    */
    {
#ifdef COMMANDLINE
        /* gcc -DCOMMANDLINE c.c */
        puts("C");
#else
        /* gcc c.c */
        puts("no C");
#endif
    }

    /*
    # #if

    # #else

    # #elif

        The preprocessor can do certain integer arithmetic operations such as: +, -, ==, <.
    */
    {
#if 1 == 0
# error
#elif 1 == 1
#else
# error
#endif

#define INIF 1
#if INIF + 1 == 2
#else
# error
#endif

#if 16 == 0x10
#else
# error
#endif

        /* Undefined evaluate equal. */
        {
#if NOT_DEFINED == NOT_DEFINED2
#else
# error
#endif
        }

        /*
        Cannot compare strings directly!
        http://stackoverflow.com/questions/2335888/how-to-compare-string-in-c-conditional-preprocessor-directives
        Always define to integers.
        */
#define STR1 1
#define STR2 2
#define STR STR1

#if STR == STR1
#elif STR == STR2
# error
#endif
    }

    /*
    # && preprocessor

    # and preprocessor
    */
#define C 1
#if defined(C) && C > 0
#else
# error
#endif

    /*
    # #error

        Print an error message to stderr and stop compilation.

        Useful to enforce preprocessor conditions.
    */
    {
        /* #error "the error message" */
    }

    /*
    # null directive

        A `#` followed by newline is ignored.
    */
    {
#
    }

    /*
    # #pragma

        C99 specifies that:

            # pragma X Y Z ...

        -   if `X != STDC`, does something implementation defined, and therefore not portable.

            Examples: `#pragma once`

        -   else, then the statement must take a form:

                # pragma STDC FP_CONTRACT on-off-switch
                # pragma STDC FENV_ACCESS on-off-switch
                # pragma STDC CX_LIMITED_RANGE on-off-switch

            all of which are portable.
    */

    /*
    # #line

        Set the line and optionally filename that is seen by `__FILE__` and `__LINE__`.
    */
    {
        /*#line 1*/
    }

    /*
    # Predefined preprocessor macros

    # Standard preprocessor defines

        Some preprocessor vars are automatically defined by certain compilers
        although they are not c standards. Those are not discussed here.

        List of standard defines: http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

        List all them on GCC:

            gcc -dM -E - < /dev/null | sort

        Sample output:

            #define _LP64 1
            #define _STDC_PREDEF_H 1
            #define __ATOMIC_ACQUIRE 2
            #define __ATOMIC_ACQ_REL 4
            #define __ATOMIC_CONSUME 1
            #define __ATOMIC_HLE_ACQUIRE 65536
            #define __ATOMIC_HLE_RELEASE 131072
            #define __ATOMIC_RELAXED 0
            #define __ATOMIC_RELEASE 3
            #define __ATOMIC_SEQ_CST 5
    */
    {
        /*
        # STDC_VERSION

        # __STDC_VERSION__

            String representing version of the c std lib. Format: yyyymm (base 10).

            Some values:

            - C11: 201112L
            - C99: 199901L

            http://sourceforge.net/p/predef/wiki/Standards/

            Apperas undefined in C99
        */
        {
            printf("__STDC_VERSION__ = %li\n", __STDC_VERSION__);
        }

        /*
        # __STDC__

        # STDC

            1 if the implementation is conforming, 0 otherwise.

            TODO check: on GCC, 1 with `-std=cXX`, 0 with `-std=gnuXX`.
        */
        {
            printf("__STDC__ = %d\n", __STDC__);
        }

        /*
        # __STDC_HOSTED__

        # STDC

            Indicate if the compilation is hosted or not.

        # Hosted

        # Freestanding

            Concept defined in ANSI C.

            Basically, a freestanding implementation does not need to provide an stdlib.

            In GCC, controlled by the `-ffreestainding` option.
        */
        {
            printf("__STDC_HOSTED__ = %d\n", __STDC_HOSTED__);
        }


        /*
        # __cplusplus

            Defined only if using C++ compiler.

            C99 says that C must not define it.
        */
#ifdef __cplusplus
        printf("__cplusplus\n");
#endif

        /*
        # __FILE__

            Absolute or relative path of current file.
        */
        {
            printf("__FILE__ = %s\n", __FILE__);
        }

        /*
        # __LINE__

            Current source code line.

            Useful for debugging.

            If in a `.h`, position inside the `.h` before inclusion.
        */
        {
            printf("__LINE__ = %d\n", __LINE__);
        }

        printf("__DATE__ = %s\n", __DATE__);

        printf("__TIME__ = %s\n", __TIME__);

#ifdef __WIN32__
        /* Automatically defined by certain compilers on windows: */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__WIN32__");
#endif

#ifdef _LIBC
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("_LIBC");
#endif

#ifdef __ILP32__
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("__ILP32__");
#endif

#ifdef ___X32_SYSCALL_BIT
        /* TODO what is this */
        /* TODO gcc specific or not? if yes move out of here. */
        puts("___X32_SYSCALL_BIT");
#endif

        /*
        # IEEE-754

            IEC 60559 has the same contents as the IEEE 754-2008,
            Outside of the C standard it is commonly known by the IEEE name, or simply as IEEE floating point.

            IEEE dates from 1985.

        # __STDC_IEC_559__

        # IEC 60599

            Standard on which floating point formats and operations should be available
            on an implementation, and how they should work.

            Good overview wiki article: <http://en.wikipedia.org/wiki/IEEE_floating_point>

            Many CUPs implement large parts of IEC 60599, which C implementations can use if available.

            The C standard specifies that implementing the IEC 60599 is not mandatory.

            If the macro `__STDC_IEC_559__` is defined this means that the implementation is compliant
            to the interface specified in Annex F of the C11 standard.

            C99 introduced many features which allow greater conformance to IEC 60599.
        */
        {
#ifdef __STDC_IEC_559__
            puts("__STDC_IEC_559__");

            /*
            I think it guaranteed by the standard on annex F:

            - The float type matches the IEC 60559 single format.
            - The double type matches the IEC 60559 double format.
            - The long double type matches an IEC 60559 extended format,307) else a
              non-IEC 60559 extended format, else the IEC 60559 double format.
            */
            assert(sizeof(float) == 4);
            assert(sizeof(double) == 8);
#endif
        }

        /*
        # Expand macro to another macro

            Nope:
            http://stackoverflow.com/questions/1262063/preprocessor-macro-expansion-to-another-preprocessor-directive
        */

#ifndef __STDC_NO_ATOMICS__
        /* Indicates no C11 support for `_Atomic` and `<stdatomic.h>`. */
        puts("__STDC_NO_ATOMICS__");
#else
#include <stdatomic.h>
        _Atomic int i;
#endif
    }

    return EXIT_SUCCESS;
}
static char const	*localstatedir = NULL;
static char const	*prefix = NULL;
static char const	*my_name = NULL;
static char const	*sbindir = NULL;
static char const	*run_dir = NULL;
static char const	*syslog_facility = NULL;
static bool		do_colourise = false;

static char const	*radius_dir = NULL;	//!< Path to raddb directory


/*
 *  Security configuration for the server.
 */
static const CONF_PARSER security_config[] = {
	{ "max_attributes",  FR_CONF_POINTER(PW_TYPE_INTEGER, &fr_max_attributes), STRINGIFY(0) },
	{ "reject_delay",  FR_CONF_POINTER(PW_TYPE_INTEGER, &main_config.reject_delay), STRINGIFY(0) },
	{ "status_server", FR_CONF_POINTER(PW_TYPE_BOOLEAN, &main_config.status_server), "no"},
	{ "allow_vulnerable_openssl", FR_CONF_POINTER(PW_TYPE_STRING, &main_config.allow_vulnerable_openssl), "no"},
	{ NULL, -1, 0, NULL, NULL }
};


/*
 *	Logging configuration for the server.
 */
static const CONF_PARSER logdest_config[] = {
	{ "destination",  FR_CONF_POINTER(PW_TYPE_STRING, &radlog_dest), "files" },
	{ "syslog_facility",  FR_CONF_POINTER(PW_TYPE_STRING, &syslog_facility), STRINGIFY(0) },

	{ "file",  FR_CONF_POINTER(PW_TYPE_STRING, &main_config.log_file), "${logdir}/radius.log" },
Example #8
0
          NULL,       MNT_FATAL|MNT_IN_CONTAINER },
        { "sysfs",      "/sys",                      "sysfs",      NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
          NULL,       MNT_FATAL|MNT_IN_CONTAINER },
        { "devtmpfs",   "/dev",                      "devtmpfs",   "mode=755", MS_NOSUID|MS_STRICTATIME,
          NULL,       MNT_FATAL|MNT_IN_CONTAINER },
        { "securityfs", "/sys/kernel/security",      "securityfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
          NULL,       MNT_NONE },
#ifdef HAVE_SMACK
        { "smackfs",    "/sys/fs/smackfs",           "smackfs",    "smackfsdef=*", MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
          use_smack,  MNT_FATAL },
        { "tmpfs",      "/dev/shm",                  "tmpfs",      "mode=1777,smackfsroot=*", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
          use_smack,  MNT_FATAL },
#endif
        { "tmpfs",      "/dev/shm",                  "tmpfs",      "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
          NULL,       MNT_FATAL|MNT_IN_CONTAINER },
        { "devpts",     "/dev/pts",                  "devpts",     "mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC,
          NULL,       MNT_IN_CONTAINER },
#ifdef HAVE_SMACK
        { "tmpfs",      "/run",                      "tmpfs",      "mode=755,smackfsroot=*", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
          use_smack,  MNT_FATAL },
#endif
        { "tmpfs",      "/run",                      "tmpfs",      "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME,
          NULL,       MNT_FATAL|MNT_IN_CONTAINER },
        { "tmpfs",      "/sys/fs/cgroup",            "tmpfs",      "mode=755", MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
          NULL,       MNT_IN_CONTAINER },
#ifdef HAVE_XATTR
        { "cgroup",     "/sys/fs/cgroup/systemd",    "cgroup",     "none,name=systemd,xattr", MS_NOSUID|MS_NOEXEC|MS_NODEV,
          NULL,       MNT_IN_CONTAINER },
#endif
        { "cgroup",     "/sys/fs/cgroup/systemd",    "cgroup",     "none,name=systemd", MS_NOSUID|MS_NOEXEC|MS_NODEV,
          NULL,       MNT_IN_CONTAINER },
static int eap_sim_get_challenge(eap_handler_t *handler, VALUE_PAIR *vps, int idx, eap_sim_state_t *ess)
{
	REQUEST *request = handler->request;
	VALUE_PAIR *vp, *ki, *algo_version;

	rad_assert(idx >= 0 && idx < 3);

	/*
	 *	Generate a new RAND value, and derive Kc and SRES from Ki
	 */
	ki = pairfind(vps, PW_EAP_SIM_KI, 0, TAG_ANY);
	if (ki) {
		int i;

		/*
		 *	Check to see if have a Ki for the IMSI, this allows us to generate the rest
		 *	of the triplets.
		 */
		algo_version = pairfind(vps, PW_EAP_SIM_ALGO_VERSION, 0, TAG_ANY);
		if (!algo_version) {
			REDEBUG("Found Ki, but missing EAP-Sim-Algo-Version");
			return 0;
		}

		for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
			ess->keys.rand[idx][i] = fr_rand();
		}

		switch (algo_version->vp_integer) {
		case 1:
			comp128v1(ess->keys.sres[idx], ess->keys.Kc[idx], ki->vp_octets, ess->keys.rand[idx]);
			break;

		case 2:
			comp128v23(ess->keys.sres[idx], ess->keys.Kc[idx], ki->vp_octets, ess->keys.rand[idx],
				   true);
			break;

		case 3:
			comp128v23(ess->keys.sres[idx], ess->keys.Kc[idx], ki->vp_octets, ess->keys.rand[idx],
				   false);
			break;

		case 4:
			REDEBUG("Comp128-4 algorithm is not supported as details have not yet been published. "
				"If you have details of this algorithm please contact the FreeRADIUS "
				"maintainers");
			return 0;

		default:
			REDEBUG("Unknown/unsupported algorithm Comp128-%i", algo_version->vp_integer);
		}

		if (RDEBUG_ENABLED2) {
			char buffer[33];	/* 32 hexits (16 bytes) + 1 */
			char *p;

			RDEBUG2("Generated following triplets for round %i:", idx);

			RINDENT();
			p = buffer;
			for (i = 0; i < EAPSIM_RAND_SIZE; i++) {
				p += sprintf(p, "%02x", ess->keys.rand[idx][i]);
			}
			RDEBUG2("RAND : 0x%s", buffer);

			p = buffer;
			for (i = 0; i < EAPSIM_SRES_SIZE; i++) {
				p += sprintf(p, "%02x", ess->keys.sres[idx][i]);
			}
			RDEBUG2("SRES : 0x%s", buffer);

			p = buffer;
			for (i = 0; i < EAPSIM_KC_SIZE; i++) {
				p += sprintf(p, "%02x", ess->keys.Kc[idx][i]);
			}
			RDEBUG2("Kc   : 0x%s", buffer);
			REXDENT();
		}
		return 1;
	}

	/*
	 *	Use known RAND, SRES, and Kc values, these may of been pulled in from an AuC,
	 *	or created by sending challenges to the SIM directly.
	 */
	vp = pairfind(vps, PW_EAP_SIM_RAND1 + idx, 0, TAG_ANY);
	if (!vp) {
		/* bad, we can't find stuff! */
		REDEBUG("control:EAP-SIM-RAND%i not found", idx + 1);
		return 0;
	}
	if (vp->length != EAPSIM_RAND_SIZE) {
		REDEBUG("control:EAP-SIM-RAND%i is not " STRINGIFY(EAPSIM_RAND_SIZE) " bytes, got %zu bytes",
			idx + 1, vp->length);
		return 0;
	}
	memcpy(ess->keys.rand[idx], vp->vp_octets, EAPSIM_RAND_SIZE);

	vp = pairfind(vps, PW_EAP_SIM_SRES1 + idx, 0, TAG_ANY);
	if (!vp) {
		/* bad, we can't find stuff! */
		REDEBUG("control:EAP-SIM-SRES%i not found", idx + 1);
		return 0;
	}
	if (vp->length != EAPSIM_SRES_SIZE) {
		REDEBUG("control:EAP-SIM-SRES%i is not " STRINGIFY(EAPSIM_SRES_SIZE) " bytes, got %zu bytes",
			idx + 1, vp->length);
		return 0;
	}
	memcpy(ess->keys.sres[idx], vp->vp_octets, EAPSIM_SRES_SIZE);

	vp = pairfind(vps, PW_EAP_SIM_KC1 + idx, 0, TAG_ANY);
	if (!vp) {
		/* bad, we can't find stuff! */
		REDEBUG("control:EAP-SIM-Kc%i not found", idx + 1);
		return 0;
	}
	if (vp->length != EAPSIM_KC_SIZE) {
		REDEBUG("control:EAP-SIM-Kc%i is not 8 bytes, got %zu bytes", idx + 1, vp->length);
		return 0;
	}
	memcpy(ess->keys.Kc[idx], vp->vp_octets, EAPSIM_KC_SIZE);
	if (vp->length != EAPSIM_KC_SIZE) {
		REDEBUG("control:EAP-SIM-Kc%i is not " STRINGIFY(EAPSIM_KC_SIZE) " bytes, got %zu bytes",
			idx + 1, vp->length);
		return 0;
	}
	memcpy(ess->keys.Kc[idx], vp->vp_strvalue, EAPSIM_KC_SIZE);

	return 1;
}
Example #10
0
int main(int argc, char **argv)
{
    char   tmp[MAX_PATH];
    char*  tmpend = tmp + sizeof(tmp);
    char*  args[128];
    int    n;
    char*  opt;
    /* The emulator always uses the first serial port for kernel messages
     * and the second one for qemud. So start at the third if we need one
     * for logcat or 'shell'
     */
    int    serial = 2;
    int    shell_serial = 0;

    int    forceArmv7 = 0;

    AndroidHwConfig*  hw;
    AvdInfo*          avd;
    AConfig*          skinConfig;
    char*             skinPath;
    int               inAndroidBuild;
    uint64_t          defaultPartitionSize = convertMBToBytes(66);

    AndroidOptions  opts[1];
    /* net.shared_net_ip boot property value. */
    char boot_prop_ip[64];
    boot_prop_ip[0] = '\0';

    args[0] = argv[0];

    if ( android_parse_options( &argc, &argv, opts ) < 0 ) {
        exit(1);
    }

#ifdef _WIN32
    socket_init();
#endif

    handle_ui_options(opts);

    while (argc-- > 1) {
        opt = (++argv)[0];

        if(!strcmp(opt, "-qemu")) {
            argc--;
            argv++;
            break;
        }

        if (!strcmp(opt, "-help")) {
            emulator_help();
        }

        if (!strncmp(opt, "-help-",6)) {
            STRALLOC_DEFINE(out);
            opt += 6;

            if (!strcmp(opt, "all")) {
                android_help_all(out);
            }
            else if (android_help_for_option(opt, out) == 0) {
                /* ok */
            }
            else if (android_help_for_topic(opt, out) == 0) {
                /* ok */
            }
            if (out->n > 0) {
                printf("\n%.*s", out->n, out->s);
                exit(0);
            }

            fprintf(stderr, "unknown option: -help-%s\n", opt);
            fprintf(stderr, "please use -help for a list of valid topics\n");
            exit(1);
        }

        if (opt[0] == '-') {
            fprintf(stderr, "unknown option: %s\n", opt);
            fprintf(stderr, "please use -help for a list of valid options\n");
            exit(1);
        }

        fprintf(stderr, "invalid command-line parameter: %s.\n", opt);
        fprintf(stderr, "Hint: use '@foo' to launch a virtual device named 'foo'.\n");
        fprintf(stderr, "please use -help for more information\n");
        exit(1);
    }

    if (opts->version) {
        printf("Android emulator version %s\n"
               "Copyright (C) 2006-2011 The Android Open Source Project and many others.\n"
               "This program is a derivative of the QEMU CPU emulator (www.qemu.org).\n\n",
#if defined ANDROID_BUILD_ID
               VERSION_STRING " (build_id " STRINGIFY(ANDROID_BUILD_ID) ")" );
#else
               VERSION_STRING);
#endif
        printf("  This software is licensed under the terms of the GNU General Public\n"
               "  License version 2, as published by the Free Software Foundation, and\n"
               "  may be copied, distributed, and modified under those terms.\n\n"
               "  This program is distributed in the hope that it will be useful,\n"
               "  but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
               "  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
               "  GNU General Public License for more details.\n\n");

        exit(0);
    }
Example #11
0
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ROST is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along wth ROST; see the file COPYING.  If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */

#include "ios_macros.h"
CLICON_MODE=STRINGIFY(IOS_CONFIG);


/* IP ACCESS-LIST */
ip("Global IP configuration") access-list("IP access-list") {

    /* ACCESS-LIST STANDARD 1-99, 1300-1999 */
    standard("Standard Access List") (<1-99:int32 range[1:99]>("Standard IP access-list number") |<1300-1999:int32 range[1300:1999]>  ("Standard IP access-list number (expanded range)")), cli_ios_mode((int)IOS_MODE_ACLSTD), ADMIN;
	      
    /* ACCESS-LIST EXTEBNDED 100/199, 2000-2699 */
    extended("Extended Access List") (<100-199:int32 range[100:199]>("Extended IP access-list number")|<2000-2699:int32 range[2000:2699]>("Extended IP access-list number (expanded range)")),  cli_ios_mode((int)IOS_MODE_ACLEXT), ADMIN;
    
    /* ACCESS-LIST STANDARD <name> */
    standard("Standard Access List") <name:string>("IP zebra access-list name"), cli_ios_mode((int)IOS_MODE_ACLNSTD), ADMIN;
	      
} /* IP ACCESS-LIST */
#define TEST_VALUE 0x7f817f81

#define STR(x) #x
#define STRINGIFY(x) STR(x)

static const char
vertex_source[] =
	"#version 130\n"
	"\n"
	"attribute vec4 piglit_vertex;\n"
	"attribute uint a_value;\n"
	"\n"
	"void\n"
	"main()\n"
	"{\n"
	"  if (a_value == " STRINGIFY(TEST_VALUE) "u)\n"
	"    gl_FrontColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
	"  else\n"
	"    gl_FrontColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
	"  gl_Position = piglit_vertex;\n"
	"}\n";

static const float green[] = { 0.0f, 1.0f, 0.0f };

static bool
run_test(void)
{
	GLuint prog;
	GLint attrib;
	bool pass;
Example #13
0
static void *listenForMessages( void *ptr )
{  
    struct sockaddr_in si_me;
    struct sockaddr_in si_other;
    socklen_t slen = sizeof(si_other);
    ssize_t readBytes = 0;
    char buf[BUFLEN+1]; //add space fer terminating \0
    char msgId[MSGIDLEN+1]; //add space fer terminating \0
    int port = PORT;

    DLT_REGISTER_APP("SNSS", "SENSOSRS-SERVICE");
    DLT_REGISTER_CONTEXT(gContext,"SSRV", "Global Context");

    LOG_INFO(gContext,"SensorsService listening on port %d...",port);

    if((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
    {
        LOG_ERROR_MSG(gContext,"socket() failed!");
        exit(EXIT_FAILURE);
    }

    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;

    si_me.sin_port = htons(port);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(s, (struct sockaddr *)&si_me, sizeof(si_me)) == -1)
    {
        LOG_ERROR_MSG(gContext,"socket() failed!");
        exit(EXIT_FAILURE);
    }

    while(isRunning == true)
    {
        //use select to introduce a timeout - alloy shutdown even when no data are received
        fd_set readfs;    /* file descriptor set */
        int    maxfd;     /* maximum file desciptor used */        
        int res;
        struct timeval Timeout;
        /* set timeout value within input loop */
        Timeout.tv_usec = 0;  /* milliseconds */
        Timeout.tv_sec  = 1;  /* seconds */
        FD_SET(s, &readfs);
        maxfd = s+1;
        /* block until input becomes available */
        res = select(maxfd, &readfs, NULL, NULL, &Timeout);

        if (res > 0)
        {
            
            readBytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *)&si_other, &slen);

            if(readBytes < 0)
            {
                LOG_ERROR_MSG(gContext,"recvfrom() failed!");
                exit(EXIT_FAILURE);
            }
            
            buf[readBytes] = '\0';

            LOG_DEBUG_MSG(gContext,"------------------------------------------------");
    
            LOG_DEBUG(gContext,"Received Packet from %s:%d", 
                      inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));

            sscanf(buf, "%*[^'$']$%" STRINGIFY(MSGIDLEN) "[^',']", msgId);
    
            LOG_DEBUG(gContext,"MsgID:%s", msgId);
            LOG_DEBUG(gContext,"Len:%u", (unsigned int)strlen(buf));
            LOG_INFO(gContext,"Data:%s", buf);

            LOG_DEBUG_MSG(gContext,"------------------------------------------------");

            if(strcmp("GVSNSGYR", msgId) == 0)
            {
                processGVSNSGYR(buf);
            }
            else if(strcmp("GVSNSWHE", msgId) == 0)
            {
                processGVSNSWHE(buf);
            }
            else if(strcmp("GVSNSVSP", msgId) == 0)
            {
                processGVSNSVSP(buf);
            }
        }
    }

    close(s);

    return EXIT_SUCCESS;
}
Example #14
0
int main(int argc, char ** argv)
{
	int i,c,id;
	char buf[1024];
	char major_root, minor_root;
	struct stat sb;

	if ((argc != 4) && (argc != 5))
		usage();
	if (argc == 5) {
		if (strcmp(argv[4], "FLOPPY")) {
			if (stat(argv[4], &sb)) {
				perror(argv[4]);
				die("Couldn't stat root device.");
			}
			major_root = MAJOR(sb.st_rdev);
			minor_root = MINOR(sb.st_rdev);
		} else {
			major_root = 0;
			minor_root = 0;
		}
	} else {
		major_root = DEFAULT_MAJOR_ROOT;
		minor_root = DEFAULT_MINOR_ROOT;
	}
	fprintf(stderr, "Root device is (%d, %d)\n", major_root, minor_root);
	if ((major_root != 2) && (major_root != 3) &&
	    (major_root != 0)) {
		fprintf(stderr, "Illegal root device (major = %d)\n",
			major_root);
		die("Bad root device --- major #");
	}
	for (i=0;i<sizeof buf; i++) buf[i]=0;
	if ((id=open(argv[1],O_RDONLY,0))<0)
		die("Unable to open 'boot'");
	if (read(id,buf,MINIX_HEADER) != MINIX_HEADER)
		die("Unable to read header of 'boot'");
	if (((long *) buf)[0]!=0x04100301)
		die("Non-Minix header of 'boot'");
	if (((long *) buf)[1]!=MINIX_HEADER)
		die("Non-Minix header of 'boot'");
	if (((long *) buf)[3]!=0)
		die("Illegal data segment in 'boot'");
	if (((long *) buf)[4]!=0)
		die("Illegal bss in 'boot'");
	if (((long *) buf)[5] != 0)
		die("Non-Minix header of 'boot'");
	if (((long *) buf)[7] != 0)
		die("Illegal symbol table in 'boot'");
	i=read(id,buf,sizeof buf);
	fprintf(stderr,"Boot sector %d bytes.\n",i);
	if (i != 512)
		die("Boot block must be exactly 512 bytes");
	if ((*(unsigned short *)(buf+510)) != 0xAA55)
		die("Boot block hasn't got boot flag (0xAA55)");
	buf[508] = (char) minor_root;
	buf[509] = (char) major_root;	
	i=write(1,buf,512);
	if (i!=512)
		die("Write call failed");
	close (id);
	
	if ((id=open(argv[2],O_RDONLY,0))<0)
		die("Unable to open 'setup'");
	if (read(id,buf,MINIX_HEADER) != MINIX_HEADER)
		die("Unable to read header of 'setup'");
	if (((long *) buf)[0]!=0x04100301)
		die("Non-Minix header of 'setup'");
	if (((long *) buf)[1]!=MINIX_HEADER)
		die("Non-Minix header of 'setup'");
	if (((long *) buf)[3]!=0)
		die("Illegal data segment in 'setup'");
	if (((long *) buf)[4]!=0)
		die("Illegal bss in 'setup'");
	if (((long *) buf)[5] != 0)
		die("Non-Minix header of 'setup'");
	if (((long *) buf)[7] != 0)
		die("Illegal symbol table in 'setup'");
	for (i=0 ; (c=read(id,buf,sizeof buf))>0 ; i+=c )
		if (write(1,buf,c)!=c)
			die("Write call failed");
	close (id);
	if (i > SETUP_SECTS*512)
		die("Setup exceeds " STRINGIFY(SETUP_SECTS)
			" sectors - rewrite build/boot/setup");
	fprintf(stderr,"Setup is %d bytes.\n",i);
	for (c=0 ; c<sizeof(buf) ; c++)
		buf[c] = '\0';
	while (i<SETUP_SECTS*512) {
		c = SETUP_SECTS*512-i;
		if (c > sizeof(buf))
			c = sizeof(buf);
		if (write(1,buf,c) != c)
			die("Write call failed");
		i += c;
	}
	
	if ((id=open(argv[3],O_RDONLY,0))<0)
		die("Unable to open 'system'");
	if (read(id,buf,GCC_HEADER) != GCC_HEADER)
		die("Unable to read header of 'system'");
	if (((long *) buf)[5] != 0)
		die("Non-GCC header of 'system'");
	for (i=0 ; (c=read(id,buf,sizeof buf))>0 ; i+=c )
		if (write(1,buf,c)!=c)
			die("Write call failed");
	close(id);
	fprintf(stderr,"System is %d bytes.\n",i);
	if (i > SYS_SIZE*16)
		die("System is too big");
	return(0);
}
Example #15
0
bool GollyApp::OnInit()
{
    SetAppName(_("Golly"));    // for use in Warning/Fatal dialogs
    
    // create a stopwatch so we can use Time() to get elapsed millisecs
    stopwatch = new wxStopWatch();
    
    // set variable seed for later rand() calls
    srand(time(0));
    
#if defined(__WXMAC__) && !wxCHECK_VERSION(2,7,2)
    // prevent rectangle animation when windows open/close
    wxSystemOptions::SetOption(wxMAC_WINDOW_PLAIN_TRANSITION, 1);
    // prevent position problem in wxTextCtrl with wxTE_DONTWRAP style
    // (but doesn't fix problem with I-beam cursor over scroll bars)
    wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_MLTE, 1);
#endif
    
    // get current working directory before calling SetAppDirectory
    wxString initdir = wxFileName::GetCwd();
    if (initdir.Last() != wxFILE_SEP_PATH) initdir += wxFILE_SEP_PATH;
    
    // make sure current working directory contains application otherwise
    // we can't open Help files
    SetAppDirectory( wxString(argv[0]).mb_str(wxConvLocal) );
    
    // now set global gollydir for use in GetPrefs and elsewhere
    gollydir = wxFileName::GetCwd();
    if (gollydir.Last() != wxFILE_SEP_PATH) gollydir += wxFILE_SEP_PATH;
    
    // let non-wx modules call Fatal, Warning, BeginProgress, etc
    lifeerrors::seterrorhandler(&wxerrhandler);
    
    // allow .html files to include common graphic formats,
    // and .icons files to be in any of these formats;
    // note that wxBMPHandler is always installed, so it needs not be added,
    // and we can assume that if HAVE_WX_BMP_HANDLER is not defined, then
    // the handlers have not been auto-detected (and we just install them all).
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_GIF_HANDLER)
    wxImage::AddHandler(new wxGIFHandler);
#endif
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_PNG_HANDLER)
    wxImage::AddHandler(new wxPNGHandler);
#endif
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_TIFF_HANDLER)
    wxImage::AddHandler(new wxTIFFHandler);
#endif
    
    // wxInternetFSHandler is needed to allow downloading files
    wxFileSystem::AddHandler(new wxInternetFSHandler);
    wxFileSystem::AddHandler(new wxZipFSHandler);
    
    // get main window location and other user preferences
    GetPrefs();
    
    // create main window (also initializes viewptr, bigview, statusptr)
    mainptr = new MainFrame();
    if (mainptr == NULL) Fatal(_("Failed to create main window!"));
    
    // initialize some stuff before showing main window
    mainptr->SetRandomFillPercentage();
    mainptr->SetMinimumStepExponent();
    
    wxString banner = _("This is Golly version ");
    banner +=         _(STRINGIFY(VERSION)); 
    banner +=         _(".  Copyright 2013 The Golly Gang.");
    statusptr->SetMessage(banner);
    
    mainptr->NewPattern();
    
    // script/pattern files are stored in the pendingfiles array for later processing
    // in OnIdle; this avoids a crash in Win app if a script is run before showing
    // the main window, and also avoids event problems in Win app with a long-running
    // script (eg. user can't hit escape to abort script)
    const wxString START_PERL = wxT("golly-start.pl");
    const wxString START_PYTHON = wxT("golly-start.py");
    wxString startscript = gollydir + START_PERL;
    if (wxFileExists(startscript)) {
        mainptr->pendingfiles.Add(startscript);
    } else {
        // look in user-specific data directory
        startscript = datadir + START_PERL;
        if (wxFileExists(startscript)) {
            mainptr->pendingfiles.Add(startscript);
        }
    }
    startscript = gollydir + START_PYTHON;
    if (wxFileExists(startscript)) {
        mainptr->pendingfiles.Add(startscript);
    } else {
        // look in user-specific data directory
        startscript = datadir + START_PYTHON;
        if (wxFileExists(startscript)) {
            mainptr->pendingfiles.Add(startscript);
        }
    }
    
    // argc is > 1 if command line has one or more script/pattern files
    for (int n = 1; n < argc; n++) {
        wxFileName filename(argv[n]);
        // convert given path to a full path if not one already; this allows users
        // to do things like "../golly bricklayer.py" from within Scripts folder
        if (!filename.IsAbsolute()) filename = initdir + argv[n];
        mainptr->pendingfiles.Add(filename.GetFullPath());
    }
    
    // show main window
    if (maximize) mainptr->Maximize(true);
    mainptr->Show(true);
    SetTopWindow(mainptr);
    
    // true means call wxApp::OnRun() which will enter the main event loop;
    // false means exit immediately
    return true;
}
Example #16
0
#elif defined(HAVE_HISTORY_H)
#include <history.h>
#define USE_READLINE_HISTORY (1)
#endif /* defined(HAVE_READLINE_HISTORY_H) */

#endif /* HAVE_READLINE_HISTORY */

#endif /* HAVE_LIBREADLINE */

/*
 *	For configuration file stuff.
 */
char const *progname = "radmin";
char const *radmin_version = "radmin version " RADIUSD_VERSION_STRING
#ifdef RADIUSD_VERSION_COMMIT
" (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
#endif
", built on " __DATE__ " at " __TIME__;


/*
 *	The rest of this is because the conffile.c, etc. assume
 *	they're running inside of the server.  And we don't (yet)
 *	have a "libfreeradius-server", or "libfreeradius-util".
 */
log_debug_t debug_flag = 0;
struct main_config_t main_config;

bool check_config = false;

static FILE *outputfp = NULL;
Example #17
0
 * Boston, MA 02110-1301 USA.
 *
 */


#include "stereo_enhancer.h"

#include "embed.h"
#include "plugin_export.h"

extern "C"
{

Plugin::Descriptor PLUGIN_EXPORT stereoenhancer_plugin_descriptor =
{
	STRINGIFY( PLUGIN_NAME ),
	"StereoEnhancer Effect",
	QT_TRANSLATE_NOOP( "pluginBrowser",
				"Plugin for enhancing stereo separation of a stereo input file" ),
	"Lou Herard <lherard/at/gmail.com>",
	0x0100,
	Plugin::Effect,
	new PluginPixmapLoader("logo"),
	NULL,
	NULL
} ;

}


Example #18
0
 * less dimensions or other restrictions */
#define DEFAULT_TEX_WIDTH 128
#define DEFAULT_TEX_HEIGHT 64
#define DEFAULT_TEX_DEPTH 8

/* List of texture targets to test, terminated by GL_NONE */
static const GLenum *test_targets;

/* If set to GL_TRUE then the texture sub image upload will be read
 * from a PBO */
static GLboolean use_pbo = GL_FALSE;

static const char fragment_1d_array[] =
	"#extension GL_EXT_texture_array : require\n"
	"uniform sampler1DArray tex;\n"
	"const float TEX_HEIGHT = " STRINGIFY(DEFAULT_TEX_HEIGHT) ".0;\n"
	"void\n"
	"main()\n"
	"{\n"
	"        float layer = gl_TexCoord[0].t * TEX_HEIGHT - 0.5;\n"
	"        gl_FragColor = texture1DArray(tex, vec2(gl_TexCoord[0].s,\n"
	"                                                layer));\n"
	"}\n";

static const char fragment_2d_array[] =
	"#extension GL_EXT_texture_array : require\n"
	"uniform sampler2DArray tex;\n"
	"const float TEX_DEPTH = " STRINGIFY(DEFAULT_TEX_DEPTH) ".0;\n"
	"void\n"
	"main()\n"
	"{\n"
Example #19
0
int
main ()
{
  int err, i;
  cl_platform_id platform;
  cl_device_id device;
  cl_context context;
  cl_context_properties context_props[3];
  cl_command_queue queue;
  cl_program program;
  cl_kernel kernel;
  cl_mem buffer;

  size_t len;
  const char *program_source = NULL;
  char *device_extensions = NULL;
  char kernel_build_opts[256];
  size_t size = sizeof (cl_int) * SIZE;
  const size_t global_work_size[] = {SIZE, 0, 0}; /* size of each dimension */
  cl_int *data;

  /* In order to see which devices the OpenCL implementation on your platform
     provides you may issue a call to the print_clinfo () fuction.  */

  /* Initialize the data the OpenCl program operates on.  */
  data = (cl_int*) calloc (1, size);
  if (data == NULL)
    {
      fprintf (stderr, "calloc failed\n");
      exit (EXIT_FAILURE);
    }

  /* Pick the first platform.  */
  CHK (clGetPlatformIDs (1, &platform, NULL));
  /* Get the default device and create context.  */
  CHK (clGetDeviceIDs (platform, CL_DEVICE_TYPE_DEFAULT, 1, &device, NULL));
  context_props[0] = CL_CONTEXT_PLATFORM;
  context_props[1] = (cl_context_properties) platform;
  context_props[2] = 0;
  context = clCreateContext (context_props, 1, &device, NULL, NULL, &err);
  CHK_ERR ("clCreateContext", err);
  queue = clCreateCommandQueue (context, device, 0, &err);
  CHK_ERR ("clCreateCommandQueue", err);

  /* Query OpenCL extensions of that device.  */
  CHK (clGetDeviceInfo (device, CL_DEVICE_EXTENSIONS, 0, NULL, &len));
  device_extensions = (char *) malloc (len);
  CHK (clGetDeviceInfo (device, CL_DEVICE_EXTENSIONS, len, device_extensions,
			NULL));
  strcpy (kernel_build_opts, "-Werror -cl-opt-disable");
  if (strstr (device_extensions, "cl_khr_fp64") != NULL)
    strcpy (kernel_build_opts + strlen (kernel_build_opts),
	    " -D HAVE_cl_khr_fp64");
  if (strstr (device_extensions, "cl_khr_fp16") != NULL)
    strcpy (kernel_build_opts + strlen (kernel_build_opts),
	    " -D HAVE_cl_khr_fp16");

  /* Read the OpenCL kernel source into the main memory.  */
  program_source = read_file (STRINGIFY (CL_SOURCE), &len);
  if (program_source == NULL)
    {
      fprintf (stderr, "file does not exist: %s\n", STRINGIFY (CL_SOURCE));
      exit (EXIT_FAILURE);
    }

  /* Build the OpenCL kernel.  */
  program = clCreateProgramWithSource (context, 1, &program_source,
				       &len, &err);
  free ((void*) program_source);
  CHK_ERR ("clCreateProgramWithSource", err);
  err = clBuildProgram (program, 0, NULL, kernel_build_opts, NULL,
			NULL);
  if (err != CL_SUCCESS)
    {
      size_t len;
      char *clbuild_log = NULL;
      CHK (clGetProgramBuildInfo (program, device, CL_PROGRAM_BUILD_LOG, 0,
				  NULL, &len));
      clbuild_log = malloc (len);
      if (clbuild_log)
	{
	  CHK (clGetProgramBuildInfo (program, device, CL_PROGRAM_BUILD_LOG,
				      len, clbuild_log, NULL));
	  fprintf (stderr, "clBuildProgram failed with:\n%s\n", clbuild_log);
 	  free (clbuild_log);
        }
      exit (EXIT_FAILURE);
  }

  /* In some cases it might be handy to save the OpenCL program binaries to do
     further analysis on them.  In order to do so you may call the following
     function: save_program_binaries (program);.  */

  kernel = clCreateKernel (program, "testkernel", &err);
  CHK_ERR ("clCreateKernel", err);

  /* Setup the input data for the kernel.  */
  buffer = clCreateBuffer (context, CL_MEM_USE_HOST_PTR, size, data, &err);
  CHK_ERR ("clCreateBuffer", err);

  /* Execute the kernel (data parallel).  */
  CHK (clSetKernelArg (kernel, 0, sizeof (buffer), &buffer));
  CHK (clEnqueueNDRangeKernel (queue, kernel, 1, NULL, global_work_size, NULL,
			       0, NULL, NULL));

  /* Fetch the results (blocking).  */
  CHK (clEnqueueReadBuffer (queue, buffer, CL_TRUE, 0, size, data, 0, NULL,
			    NULL));

  /* Compare the results.  */
  for (i = 0; i < SIZE; i++)
    {
      if (data[i] != 0x1)
	{
	  fprintf (stderr, "error: data[%d]: %d != 0x1\n", i, data[i]);
	  exit (EXIT_FAILURE);
	}
    }

  /* Cleanup.  */
  CHK (clReleaseMemObject (buffer));
  CHK (clReleaseKernel (kernel));
  CHK (clReleaseProgram (program));
  CHK (clReleaseCommandQueue (queue));
  CHK (clReleaseContext (context));
  free (data);

  return 0;
}
Example #20
0
File: type.c Project: zillow/ctds
                          NULL);
    return 0;
    UNUSED(kwargs);
}

SQL_TYPE_DEF(VarBinary, s_SqlVarBinary_doc);

struct SqlChar
{
    SqlType_HEAD;
};

static const char s_SqlChar_doc[] =
    "SqlChar(value)\n"
    "\n"
    "SQL CHAR type wrapper. The value's UTF-8-encoded length must be <= " STRINGIFY(TDS_CHAR_MAX_SIZE) ".\n"
    "\n"
    ":param object value: The value to wrap or :py:data:`None`.\n";

static int SqlChar_init(PyObject* self, PyObject* args, PyObject* kwargs)
{
    char* utf8bytes = NULL;
    Py_ssize_t nutf8bytes = 0;
    if (!PyArg_ParseTuple(args, "et#", "utf-8", &utf8bytes, &nutf8bytes))
    {
        PyObject* none;

        PyErr_Clear();

        if (!PyArg_ParseTuple(args, "O", &none))
        {
Example #21
0
/** Handle authorization requests using Couchbase document data
 *
 * Attempt to fetch the document assocaited with the requested user by
 * using the deterministic key defined in the configuration.  When a valid
 * document is found it will be parsed and the containing value pairs will be
 * injected into the request.
 *
 * @param  instance The module instance.
 * @param  request  The authorization request.
 * @return Operation status (#rlm_rcode_t).
 */
static rlm_rcode_t mod_authorize(void *instance, REQUEST *request)
{
	rlm_couchbase_t *inst = instance;       /* our module instance */
	rlm_couchbase_handle_t *handle = NULL;  /* connection pool handle */
	char buffer[MAX_KEY_SIZE];
	char const *dockey;            		/* our document key */
	lcb_error_t cb_error = LCB_SUCCESS;     /* couchbase error holder */
	rlm_rcode_t rcode = RLM_MODULE_OK;      /* return code */
	ssize_t slen;

	/* assert packet as not null */
	rad_assert(request->packet != NULL);

	/* attempt to build document key */
	slen = tmpl_expand(&dockey, buffer, sizeof(buffer), request, inst->user_key, NULL, NULL);
	if (slen < 0) return RLM_MODULE_FAIL;
	if ((dockey == buffer) && is_truncated((size_t)slen, sizeof(buffer))) {
		REDEBUG("Key too long, expected < " STRINGIFY(sizeof(buffer)) " bytes, got %zi bytes", slen);
		return RLM_MODULE_FAIL;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set couchbase instance */
	lcb_t cb_inst = handle->handle;

	/* set cookie */
	cookie_t *cookie = handle->cookie;

	/* fetch document */
	cb_error = couchbase_get_key(cb_inst, cookie, dockey);

	/* check error */
	if (cb_error != LCB_SUCCESS || !cookie->jobj) {
		/* log error */
		RERROR("failed to fetch document or parse return");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* debugging */
	RDEBUG3("parsed user document == %s", json_object_to_json_string(cookie->jobj));

	/* inject config value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "config", request);

	/* inject reply value pairs defined in this json oblect */
	mod_json_object_to_value_pairs(cookie->jobj, "reply", request);

	finish:

	/* free json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* release handle */
	if (handle) {
		fr_connection_release(inst->pool, handle);
	}

	/* return */
	return rcode;
}
Example #22
0
#define STRINGIFY2(arg) #arg
#define STRINGIFY(arg) STRINGIFY2(arg)

extern const char *buildstring;
const char *buildstring =
#ifndef NO_BUILD_TIMESTAMPS
__TIME__ " " __DATE__ " "
#endif
#ifdef SVNREVISION
STRINGIFY(SVNREVISION)
#else
"-"
#endif
#ifdef BUILDTYPE
" " STRINGIFY(BUILDTYPE)
#endif
;
Example #23
0
/** Check if a given user is already logged in.
 *
 * Process accounting data to determine if a user is already logged in. Sets request->simul_count
 * to the current session count for this user.
 *
 * Check twice. If on the first pass the user exceeds his maximum number of logins, do a second
 * pass and validate all logins by querying the terminal server.
 *
 * @param instance The module instance.
 * @param request  The checksimul request object.
 * @return Operation status (#rlm_rcode_t).
 */
static rlm_rcode_t mod_checksimul(void *instance, REQUEST *request) {
	rlm_couchbase_t *inst = instance;      /* our module instance */
	rlm_rcode_t rcode = RLM_MODULE_OK;     /* return code */
	rlm_couchbase_handle_t *handle = NULL; /* connection pool handle */
	char vpath[256];

	char buffer[MAX_KEY_SIZE];
	char const *vkey;                      /* view path and query key */
	char docid[MAX_KEY_SIZE];              /* document id returned from view */
	char error[512];                       /* view error return */
	int idx = 0;                           /* row array index counter */
	char element[MAX_KEY_SIZE];            /* mapped radius attribute to element name */
	lcb_error_t cb_error = LCB_SUCCESS;    /* couchbase error holder */
	json_object *json, *jval;              /* json object holders */
	json_object *jrows = NULL;             /* json object to hold view rows */
	VALUE_PAIR *vp;                        /* value pair */
	uint32_t client_ip_addr = 0;           /* current client ip address */
	char const *client_cs_id = NULL;       /* current client calling station id */
	char *user_name = NULL;                /* user name from accounting document */
	char *session_id = NULL;               /* session id from accounting document */
	char *cs_id = NULL;                    /* calling station id from accounting document */
	uint32_t nas_addr = 0;                 /* nas address from accounting document */
	uint32_t nas_port = 0;                 /* nas port from accounting document */
	uint32_t framed_ip_addr = 0;           /* framed ip address from accounting document */
	char framed_proto = 0;                 /* framed proto from accounting document */
	int session_time = 0;                  /* session time from accounting document */
	ssize_t slen;

	/* do nothing if this is not enabled */
	if (inst->check_simul != true) {
		RDEBUG3("mod_checksimul returning noop - not enabled");
		return RLM_MODULE_NOOP;
	}

	/* ensure valid username in request */
	if ((!request->username) || (request->username->vp_length == '\0')) {
		RDEBUG3("mod_checksimul - invalid username");
		return RLM_MODULE_INVALID;
	}

	slen = tmpl_expand(&vkey, buffer, sizeof(buffer), request, inst->simul_vkey, NULL, NULL);
	if (slen < 0) return RLM_MODULE_FAIL;
	if ((vkey == buffer) && is_truncated((size_t)slen, sizeof(buffer))) {
		REDEBUG("Key too long, expected < " STRINGIFY(sizeof(buffer)) " bytes, got %zi bytes", slen);
		return RLM_MODULE_FAIL;
	}

	/* get handle */
	handle = fr_connection_get(inst->pool);

	/* check handle */
	if (!handle) return RLM_MODULE_FAIL;

	/* set couchbase instance */
	lcb_t cb_inst = handle->handle;

	/* set cookie */
	cookie_t *cookie = handle->cookie;

	/* build view path */
	snprintf(vpath, sizeof(vpath), "%s?key=\"%s\"&stale=update_after",
		 inst->simul_view, vkey);

	/* query view for document */
	cb_error = couchbase_query_view(cb_inst, cookie, vpath, NULL);

	/* check error and object */
	if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) {
		/* log error */
		RERROR("failed to execute view request or parse return");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* debugging */
	RDEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

	/* check for error in json object */
	if (json_object_object_get_ex(cookie->jobj, "error", &json)) {
		/* build initial error buffer */
		strlcpy(error, json_object_get_string(json), sizeof(error));
		/* get error reason */
		if (json_object_object_get_ex(cookie->jobj, "reason", &json)) {
			/* append divider */
			strlcat(error, " - ", sizeof(error));
			/* append reason */
			strlcat(error, json_object_get_string(json), sizeof(error));
		}
		/* log error */
		RERROR("view request failed with error: %s", error);
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* check for document id in return */
	if (!json_object_object_get_ex(cookie->jobj, "rows", &json)) {
		/* log error */
		RERROR("failed to fetch rows from view payload");
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* get and hold rows */
	jrows = json_object_get(json);

	/* free cookie object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	/* check for valid row value */
	if (!jrows || !fr_json_object_is_type(jrows, json_type_array)) {
		/* log error */
		RERROR("no valid rows returned from view: %s", vpath);
		/* set return */
		rcode = RLM_MODULE_FAIL;
		/* return */
		goto finish;
	}

	/* debugging */
	RDEBUG3("jrows == %s", json_object_to_json_string(jrows));

	/* set the count */
	request->simul_count = json_object_array_length(jrows);

	/* debugging */
	RDEBUG("found %d open sessions for %s", request->simul_count, request->username->vp_strvalue);

	/* check count */
	if (request->simul_count < request->simul_max) {
		rcode = RLM_MODULE_OK;
		goto finish;
	}

	/*
	 * Current session count exceeds configured maximum.
	 * Continue on to verify the sessions if configured otherwise stop here.
	 */
	if (inst->verify_simul != true) {
		rcode = RLM_MODULE_OK;
		goto finish;
	}

	/* debugging */
	RDEBUG("verifying session count");

	/* reset the count */
	request->simul_count = 0;

	/* get client ip address for MPP detection below */
	if ((vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_IP_ADDRESS, 0, TAG_ANY)) != NULL) {
		client_ip_addr = vp->vp_ipaddr;
	}

	/* get calling station id for MPP detection below */
	if ((vp = fr_pair_find_by_num(request->packet->vps, PW_CALLING_STATION_ID, 0, TAG_ANY)) != NULL) {
		client_cs_id = vp->vp_strvalue;
	}

	/* loop across all row elements */
	for (idx = 0; idx < json_object_array_length(jrows); idx++) {
		/* clear docid */
		memset(docid, 0, sizeof(docid));

		/* fetch current index */
		json = json_object_array_get_idx(jrows, idx);

		/* get document id */
		if (json_object_object_get_ex(json, "id", &jval)) {
			/* copy and check length */
			if (strlcpy(docid, json_object_get_string(jval), sizeof(docid)) >= sizeof(docid)) {
				RERROR("document id from row longer than MAX_KEY_SIZE (%d)", MAX_KEY_SIZE);
				continue;
			}
		}

		/* check for valid doc id */
		if (docid[0] == 0) {
			RWARN("failed to fetch document id from row - skipping");
			continue;
		}

		/* fetch document */
		cb_error = couchbase_get_key(cb_inst, cookie, docid);

		/* check error and object */
		if (cb_error != LCB_SUCCESS || cookie->jerr != json_tokener_success || !cookie->jobj) {
			/* log error */
			RERROR("failed to execute get request or parse return");
			/* set return */
			rcode = RLM_MODULE_FAIL;
			/* return */
			goto finish;
		}

		/* debugging */
		RDEBUG3("cookie->jobj == %s", json_object_to_json_string(cookie->jobj));

		/* get element name for User-Name attribute */
		if (mod_attribute_to_element("User-Name", inst->map, &element) == 0) {
			/* get and check username element */
			if (!json_object_object_get_ex(cookie->jobj, element, &jval)){
				RDEBUG("cannot zap stale entry without username");
				rcode = RLM_MODULE_FAIL;
				goto finish;
			}
			/* copy json string value to user_name */
			user_name = talloc_typed_strdup(request, json_object_get_string(jval));
		} else {
			RDEBUG("failed to find map entry for User-Name attribute");
			rcode = RLM_MODULE_FAIL;
			goto finish;
		}

		/* get element name for Acct-Session-Id attribute */
		if (mod_attribute_to_element("Acct-Session-Id", inst->map, &element) == 0) {
			/* get and check session id element */
			if (!json_object_object_get_ex(cookie->jobj, element, &jval)){
				RDEBUG("cannot zap stale entry without session id");
				rcode = RLM_MODULE_FAIL;
				goto finish;
			}
			/* copy json string value to session_id */
			session_id = talloc_typed_strdup(request, json_object_get_string(jval));
		} else {
			RDEBUG("failed to find map entry for Acct-Session-Id attribute");
			rcode = RLM_MODULE_FAIL;
			goto finish;
		}

		/* get element name for NAS-IP-Address attribute */
		if (mod_attribute_to_element("NAS-IP-Address", inst->map, &element) == 0) {
			/* attempt to get and nas address element */
			if (json_object_object_get_ex(cookie->jobj, element, &jval)){
				nas_addr = inet_addr(json_object_get_string(jval));
			}
		}

		/* get element name for NAS-Port attribute */
		if (mod_attribute_to_element("NAS-Port", inst->map, &element) == 0) {
			/* attempt to get nas port element */
			if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
				nas_port = (uint32_t) json_object_get_int(jval);
			}
		}

		/* check terminal server */
		int check = rad_check_ts(nas_addr, nas_port, user_name, session_id);

		/* take action based on check return */
		if (check == 0) {
			/* stale record - zap it if enabled */
			if (inst->delete_stale_sessions) {
				/* get element name for Framed-IP-Address attribute */
				if (mod_attribute_to_element("Framed-IP-Address", inst->map, &element) == 0) {
					/* attempt to get framed ip address element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						framed_ip_addr = inet_addr(json_object_get_string(jval));
					}
				}

				/* get element name for Framed-Port attribute */
				if (mod_attribute_to_element("Framed-Port", inst->map, &element) == 0) {
					/* attempt to get framed port element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						if (strcmp(json_object_get_string(jval), "PPP") == 0) {
							framed_proto = 'P';
						} else if (strcmp(json_object_get_string(jval), "SLIP") == 0) {
							framed_proto = 'S';
						}
					}
				}

				/* get element name for Acct-Session-Time attribute */
				if (mod_attribute_to_element("Acct-Session-Time", inst->map, &element) == 0) {
					/* attempt to get session time element */
					if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
						session_time = json_object_get_int(jval);
					}
				}

				/* zap session */
				session_zap(request, nas_addr, nas_port, user_name, session_id,
					    framed_ip_addr, framed_proto, session_time);
			}
		} else if (check == 1) {
			/* user is still logged in - increase count */
			++request->simul_count;

			/* get element name for Framed-IP-Address attribute */
			if (mod_attribute_to_element("Framed-IP-Address", inst->map, &element) == 0) {
				/* attempt to get framed ip address element */
				if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
					framed_ip_addr = inet_addr(json_object_get_string(jval));
				} else {
					/* ensure 0 if not found */
					framed_ip_addr = 0;
				}
			}

			/* get element name for Calling-Station-Id attribute */
			if (mod_attribute_to_element("Calling-Station-Id", inst->map, &element) == 0) {
				/* attempt to get framed ip address element */
				if (json_object_object_get_ex(cookie->jobj, element, &jval)) {
					/* copy json string value to cs_id */
					cs_id = talloc_typed_strdup(request, json_object_get_string(jval));
				} else {
					/* ensure null if not found */
					cs_id = NULL;
				}
			}

			/* Does it look like a MPP attempt? */
			if (client_ip_addr && framed_ip_addr && framed_ip_addr == client_ip_addr) {
				request->simul_mpp = 2;
			} else if (client_cs_id && cs_id && !strncmp(cs_id, client_cs_id, 16)) {
				request->simul_mpp = 2;
			}

		} else {
			/* check failed - return error */
			REDEBUG("failed to check the terminal server for user '%s'", user_name);
			rcode = RLM_MODULE_FAIL;
			goto finish;
		}

		/* free and reset document user name talloc */
		if (user_name) TALLOC_FREE(user_name);

		/* free and reset document calling station id talloc */
		if (cs_id) TALLOC_FREE(cs_id);

		/* free and reset document session id talloc */
		if (session_id) TALLOC_FREE(session_id);

		/* free and reset json object before fetching next row */
		if (cookie->jobj) {
			json_object_put(cookie->jobj);
			cookie->jobj = NULL;
		}
	}

	/* debugging */
	RDEBUG("Retained %d open sessions for %s after verification",
	       request->simul_count, request->username->vp_strvalue);

finish:
	if (user_name) talloc_free(user_name);
	if (cs_id) talloc_free(cs_id);
	if (session_id) talloc_free(session_id);

	/* free rows */
	if (jrows) json_object_put(jrows);

	/* free and reset json object */
	if (cookie->jobj) {
		json_object_put(cookie->jobj);
		cookie->jobj = NULL;
	}

	if (handle) fr_connection_release(inst->pool, handle);

	/*
	 * The Auth module apparently looks at request->simul_count,
	 * not the return value of this module when deciding to deny
	 * a call for too many sessions.
	 */
	return rcode;
}
Example #24
0
int
main (int argc, char *argv[])
{
    void *local;
    command_t *command;
    alias_t *alias;
    unsigned int i, j;
    const char **argv_local;

    talloc_enable_null_tracking ();

    local = talloc_new (NULL);

    g_mime_init (0);
    g_type_init ();

    if (argc == 1)
	return notmuch (local);

    if (STRNCMP_LITERAL (argv[1], "--help") == 0)
	return notmuch_help_command (NULL, 0, NULL);

    if (STRNCMP_LITERAL (argv[1], "--version") == 0) {
	printf ("notmuch " STRINGIFY(NOTMUCH_VERSION) "\n");
	return 0;
    }

    for (i = 0; i < ARRAY_SIZE (aliases); i++) {
	alias = &aliases[i];

	if (strcmp (argv[1], alias->name) == 0)
	{
	    int substitutions;

	    argv_local = talloc_size (local, sizeof (char *) *
				      (argc + MAX_ALIAS_SUBSTITUTIONS - 1));
	    if (argv_local == NULL) {
		fprintf (stderr, "Out of memory.\n");
		return 1;
	    }

	    /* Copy all substution arguments from the alias. */
	    argv_local[0] = argv[0];
	    for (j = 0; j < MAX_ALIAS_SUBSTITUTIONS; j++) {
		if (alias->substitutions[j] == NULL)
		    break;
		argv_local[j+1] = alias->substitutions[j];
	    }
	    substitutions = j;

	    /* And copy all original arguments (skipping the argument
	     * that matched the alias of course. */
	    for (j = 2; j < (unsigned) argc; j++) {
		argv_local[substitutions+j-1] = argv[j];
	    }

	    argc += substitutions - 1;
	    argv = (char **) argv_local;
	}
    }

    for (i = 0; i < ARRAY_SIZE (commands); i++) {
	command = &commands[i];

	if (strcmp (argv[1], command->name) == 0)
	    return (command->function) (local, argc - 2, &argv[2]);
    }

    fprintf (stderr, "Error: Unknown command '%s' (see \"notmuch help\")\n",
	     argv[1]);

    talloc_free (local);

    return 1;
}
Example #25
0
File: main.cpp Project: CCJY/coliru
int main(void) {
    // your code goes here
    printf("%s\n",STRINGIFY(EVSYS_CHMUX(REG)));
	return 0;
}
Example #26
0
#warning "Are you sure you don't want to use the bottom_camera or front_camera?"
// The video device buffers (the amount of V4L2 buffers)
#ifndef VIDEO_THREAD_DEVICE_BUFFERS
#define VIDEO_THREAD_DEVICE_BUFFERS 10
#endif
PRINT_CONFIG_VAR(VIDEO_THREAD_DEVICE_BUFFERS)
#ifndef VIDEO_THREAD_SUBDEV
#define VIDEO_THREAD_SUBDEV NULL
#endif
#ifndef VIDEO_THREAD_FILTERS
#define VIDEO_THREAD_FILTERS 0
#endif
struct video_config_t custom_camera = {
  .w = VIDEO_THREAD_VIDEO_WIDTH,
  .h = VIDEO_THREAD_VIDEO_HEIGHT,
  .dev_name = STRINGIFY(VIDEO_THREAD_DEVICE),
  .subdev_name = VIDEO_THREAD_SUBDEV,
  .buf_cnt = VIDEO_THREAD_DEVICE_BUFFERS,
  .filters = VIDEO_THREAD_FILTERS
};
#define VIDEO_THREAD_CAMERA custom_camera
#endif
PRINT_CONFIG_VAR(VIDEO_THREAD_CAMERA)


// Frames Per Seconds
#ifndef VIDEO_THREAD_FPS
#define VIDEO_THREAD_FPS 4
#endif
PRINT_CONFIG_VAR(VIDEO_THREAD_FPS)