Example #1
0
static A_Err
FBIO_FlattenOptions(
	AEIO_BasicData	*basic_dataP,
	AEIO_InSpecH	specH,
	AEIO_Handle		*flat_optionsPH)
{ 
	A_Err	err		=	A_Err_NONE,
			err2	=	A_Err_NONE; 

	AEIO_Handle			optionsH	= NULL;
	
	FBIO_FileHeader		*flat_headerP	= NULL,
						*old_headerP	= NULL;

	AEGP_SuiteHandler	suites(basic_dataP->pica_basicP);	
	
	//	Given the AEIO_InSpecH, acquire the non-flat
	//	options handle and use it to create a flat
	//	version. Do NOT de-allocate the non-flat
	//	options handle!
	
	ERR(suites.IOInSuite4()->AEGP_GetInSpecOptionsHandle(specH, reinterpret_cast<void**>(&optionsH)));

	if (optionsH) {
		ERR(suites.MemorySuite1()->AEGP_LockMemHandle(optionsH, reinterpret_cast<void**>(&old_headerP)));
	}
			
	if (old_headerP){
		ERR(suites.MemorySuite1()->AEGP_NewMemHandle(	S_mem_id,
														"flattened_options", 
														sizeof(FBIO_FileHeader), 
														AEGP_MemFlag_CLEAR, 
														flat_optionsPH));
	}

	if (*flat_optionsPH){
		ERR(suites.MemorySuite1()->AEGP_LockMemHandle(*flat_optionsPH, (void**)&flat_headerP));
	}			
	if (!err && flat_headerP) {
		// Here is where you should provide a disk-safe copy of your options data
		ERR(PretendToReadFileHeader(basic_dataP, flat_headerP));
	}

	if (optionsH)
	{
		ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(optionsH));
	}
	if (*flat_optionsPH)
	{
		ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(*flat_optionsPH));
	}

	return err;
};		
Example #2
0
/* Verify anti-symmetry and transitivity for comparator CMP on sorted array
   of N SIZE-sized elements pointed to by BASE.  */
void
qsort_chk (void *base, size_t n, size_t size,
	   int (*cmp)(const void *, const void *))
{
#if 0
#define LIM(n) (n)
#else
  /* Limit overall time complexity to O(n log n).  */
#define LIM(n) ((n) <= 16 ? (n) : 12 + floor_log2 (n))
#endif
#define ELT(i) ((const char *) base + (i) * size)
#define CMP(i, j) cmp (ELT (i), ELT (j))
#define ERR2(i, j) qsort_chk_error (ELT (i), ELT (j), NULL, cmp)
#define ERR3(i, j, k) qsort_chk_error (ELT (i), ELT (j), ELT (k), cmp)
  size_t i1, i2, i, j;
  /* This outer loop iterates over maximum spans [i1, i2) such that
     elements within each span compare equal to each other.  */
  for (i1 = 0; i1 < n; i1 = i2)
    {
      /* Position i2 one past last element that compares equal to i1'th.  */
      for (i2 = i1 + 1; i2 < n; i2++)
	if (CMP (i1, i2))
	  break;
	else if (CMP (i2, i1))
	  return ERR2 (i1, i2);
      size_t lim1 = LIM (i2 - i1), lim2 = LIM (n - i2);
      /* Verify that other pairs within current span compare equal.  */
      for (i = i1 + 1; i + 1 < i2; i++)
	for (j = i + 1; j < i1 + lim1; j++)
	  if (CMP (i, j))
	    return ERR3 (i, i1, j);
	  else if (CMP (j, i))
	    return ERR2 (i, j);
      /* Verify that elements within this span compare less than
         elements beyond the span.  */
      for (i = i1; i < i2; i++)
	for (j = i2; j < i2 + lim2; j++)
	  if (CMP (i, j) >= 0)
	    return ERR3 (i, i1, j);
	  else if (CMP (j, i) <= 0)
	    return ERR2 (i, j);
    }
#undef ERR3
#undef ERR2
#undef CMP
#undef ELT
#undef LIM
}
Example #3
0
PF_Err	
AcquireBackgroundColor(	PF_InData		*in_data,
						PF_OutData		*out_data,
						PF_ParamDef		*params[],
						PF_EventExtra	*event_extra,
						PF_App_Color	*app_color)
{

	PF_Err			err 	= PF_Err_NONE,
					err2 	= PF_Err_NONE;

	PFAppSuite1		*app_suiteP = NULL;

	err = AEFX_AcquireSuite(	in_data,
								out_data,
								kPFAppSuite,
								kPFAppSuiteVersion1,
								NULL,
								(void**)&app_suiteP);

	if (app_suiteP) {
		ERR(app_suiteP->PF_AppGetBgColor(app_color));
	}

	ERR2(AEFX_ReleaseSuite(	in_data,
							out_data,
							kPFAppSuite,
							kPFAppSuiteVersion1,
							NULL));
	return err;
}
Example #4
0
static A_Err
UpdateMenuHook(
    AEGP_GlobalRefcon		plugin_refconPV,	/* >> */
    AEGP_UpdateMenuRefcon	refconPV,			/* >> */
    AEGP_WindowType			active_window)		/* >> */
{
    A_Err 				err 			=	A_Err_NONE,
                                 err2			=	A_Err_NONE;

    AEGP_ItemH			active_itemH	=	NULL;

    AEGP_ItemType		item_type		=	AEGP_ItemType_NONE;

    AEGP_SuiteHandler	suites(sP);

    ERR(suites.ItemSuite6()->AEGP_GetActiveItem(&active_itemH));

    if (active_itemH) {
        ERR(suites.ItemSuite6()->AEGP_GetItemType(active_itemH, &item_type));

        if (AEGP_ItemType_COMP 		==	item_type	||
                AEGP_ItemType_FOOTAGE	==	item_type)	{
            ERR(suites.CommandSuite1()->AEGP_EnableCommand(S_Grabba_cmd));
        }
    } else {
        ERR2(suites.CommandSuite1()->AEGP_DisableCommand(S_Grabba_cmd));
    }
    return err;
}
Example #5
0
static A_Err
CommandHook(
    AEGP_GlobalRefcon	plugin_refconPV,		/* >> */
    AEGP_CommandRefcon	refconPV,				/* >> */
    AEGP_Command		command,				/* >> */
    AEGP_HookPriority	hook_priority,			/* >> */
    A_Boolean			already_handledB,		/* >> */
    A_Boolean			*handledPB)				/* << */
{
    A_Err			err 		= 	A_Err_NONE,
                          err2 		= 	A_Err_NONE;

    AEGP_SuiteHandler	suites(sP);

    if (S_Grabba_cmd == command) {

        AEGP_ItemH			active_itemH	=	NULL;
        AEGP_RenderOptionsH	roH				=	NULL;

        ERR(suites.ItemSuite6()->AEGP_GetActiveItem(&active_itemH));

        if (active_itemH) {
            ERR(suites.RenderOptionsSuite1()->AEGP_NewFromItem(S_my_id, active_itemH, &roH));

            if (!err && roH) {
                AEGP_FrameReceiptH	receiptH 	= NULL;
                AEGP_WorldH			frameH		= NULL;
                A_Time				timeT		= {0,1};
                AEGP_WorldType		type		= AEGP_WorldType_NONE;

                ERR(suites.RenderOptionsSuite1()->AEGP_SetTime(roH, timeT)); // avoid "div by 0"
                ERR(suites.RenderOptionsSuite1()->AEGP_GetWorldType(roH, &type));
                ERR(suites.RenderSuite2()->AEGP_RenderAndCheckoutFrame(roH, NULL, NULL, &receiptH));

                if (receiptH) {
                    ERR(suites.RenderSuite2()->AEGP_GetReceiptWorld(receiptH, &frameH));

                    // 	WooHOO! Pixel Party!

                    // 	We Crash, So You Don't Have To...
                    //
                    //	A nice developer like yourself might instinctually
                    //	AEGP_Dispose() of the frame you just got. Actually,
                    //	After Effects will manage that frame for you. Do
                    //	not dispose! Thanks for being so considerate. Now
                    //	go wash your hands.

                    ERR2(suites.RenderSuite2()->AEGP_CheckinFrame(receiptH));
                }
            }
            ERR(suites.RenderOptionsSuite1()->AEGP_Dispose(roH));
        }
        *handledPB = TRUE;
    }
    return err;
}
Example #6
0
/* that can confuse xkbcomp parser */
static Bool
checkName(char *name, const char *string)
{
    char *i = name, *opar = NULL;
    Bool ret = True;

    if (!name)
        return True;

    while (*i)
    {
        if (opar == NULL)
        {
            if (*i == '(')
                opar = i;
        }
        else
        {
            if ((*i == '(') || (*i == '|') || (*i == '+'))
            {
                ret = False;
                break;
            }
            if (*i == ')')
                opar = NULL;
        }
        i++;
    }
    if (opar)
        ret = False;
    if (!ret)
    {
        char c;
        int n = 1;
        for (i = opar + 1; *i && n; i++)
        {
            if (*i == '(')
                n++;
            if (*i == ')')
                n--;
        }
        if (*i)
            i++;
        c = *i;
        *i = '\0';
        ERR1("Illegal map name '%s' ", opar);
        *i = c;
        ERR2("in %s name '%s'\n", string, name);
    }
    return ret;
}
Example #7
0
static A_Err
UpdateMenuHook(
			   AEGP_GlobalRefcon		plugin_refconPV,	/* >> */
			   AEGP_UpdateMenuRefcon	refconPV,			/* >> */
			   AEGP_WindowType			active_window)		/* >> */
			   {
	A_Err 				err 					=	A_Err_NONE,
	err2					=	A_Err_NONE;
	AEGP_SuiteHandler	suites(sP);
	AEGP_LayerH			layerH 					=	NULL;
	AEGP_StreamRefH		stroke_group_streamH 	=	NULL;
	
	try {
		ERR(suites.LayerSuite5()->AEGP_GetActiveLayer(&layerH));
		
		if (layerH){
			ERR(CheckForPaintStreams(layerH, &stroke_group_streamH));
			if (stroke_group_streamH){
				ERR(suites.CommandSuite1()->AEGP_SetMenuCommandName(S_Streamie_cmd, STR(StrID_Name)));
				ERR(suites.CommandSuite1()->AEGP_EnableCommand(S_Streamie_cmd));
			} else	{
				ERR(suites.CommandSuite1()->AEGP_DisableCommand(S_Streamie_cmd));
			}
		} else {
			ERR(suites.CommandSuite1()->AEGP_SetMenuCommandName(S_Streamie_cmd, STR(StrID_CommandName)));
		}
		if (stroke_group_streamH){
			ERR2(suites.StreamSuite2()->AEGP_DisposeStream(stroke_group_streamH));
		}	
	} catch (A_Err &thrown_err){
		err = thrown_err;
	}	
	if (err) { // not !err, err!
		ERR2(suites.UtilitySuite3()->AEGP_ReportInfo(S_my_id, STR(StrID_Troubles)));
	}
	return err;
}
Example #8
0
/**
 * Open a connection to the display and print error if it fails.
 *
 * @return True on success or False otherwise.
 */
Bool
getDisplay(int argc, char **argv)
{
    int major, minor, why;

    major = XkbMajorVersion;
    minor = XkbMinorVersion;
    dpy =
        XkbOpenDisplay(settings.display.value, NULL, NULL, &major, &minor,
                       &why);
    if (!dpy)
    {
        if (settings.display.value == NULL)
            settings.display.value = getenv("DISPLAY");
        if (settings.display.value == NULL)
            settings.display.value = "default display";
        switch (why)
        {
        case XkbOD_BadLibraryVersion:
            ERR3("%s was compiled with XKB version %d.%02d\n", argv[0],
                 XkbMajorVersion, XkbMinorVersion);
            ERR2("Xlib supports incompatible version %d.%02d\n",
                 major, minor);
            break;
        case XkbOD_ConnectionRefused:
            ERR1("Cannot open display \"%s\"\n", settings.display.value);
            break;
        case XkbOD_NonXkbServer:
            ERR1("XKB extension not present on %s\n", settings.display.value);
            break;
        case XkbOD_BadServerVersion:
            ERR3("%s was compiled with XKB version %d.%02d\n", argv[0],
                 XkbMajorVersion, XkbMinorVersion);
            ERR3("Server %s uses incompatible version %d.%02d\n",
                 settings.display.value, major, minor);
            break;
        default:
            ERR1("Unknown error %d from XkbOpenDisplay\n", why);
            break;
        }
        return False;
    }
    if (synch)
        XSynchronize(dpy, True);
    return True;
}
Example #9
0
/* read */
static int fifo_read(ubx_block_t *i, ubx_data_t* msg)
{
	int ret=0;
	unsigned long readsz=0, readsz1=0, readsz2=0, used;
	struct fifo_block_info *bbi;

	bbi = (struct fifo_block_info*) i->private_data;

	if((ret=pthread_mutex_lock(&bbi->mutex))!=0) {
		ERR2(ret, "failed to lock mutex");
		goto out;
	}

	if(bbi->rdptr == bbi->wrptr) {
		goto out_unlock;
	}

	if(msg->type != bbi->type) {
		ERR("invalid read type '%s' (expected '%s'", get_typename(msg), bbi->type->name);
		ret=EPORT_INVALID_TYPE;
		goto out_unlock;
	}

	/* bytes */
	used = used_space(bbi);
	readsz=(used<readsz) ? used : readsz;

	/* chunk 2*/
	if(bbi->rdptr > bbi->wrptr) {
		readsz2 = readsz - (bbi->buff + bbi->size - bbi->wrptr);
		readsz1 = readsz-readsz2;
	}

	memcpy(msg->data, bbi->rdptr, readsz1);
	bbi->rdptr=&bbi->buff[readsz1];

	if(readsz2>0) {
		
	}

	ret=readsz/bbi->type->size;		/* compute # elements read */
 out_unlock:
	pthread_mutex_unlock(&bbi->mutex);
 out:
	return ret;
}
Example #10
0
A_Err
EntryPointFunc(
    struct SPBasicSuite		*pica_basicP,		/* >> */
    A_long				 	major_versionL,		/* >> */
    A_long					minor_versionL,		/* >> */
    AEGP_PluginID			aegp_plugin_id,		/* >> */
    AEGP_GlobalRefcon		*global_refconV)	/* << */
{
    S_my_id										= aegp_plugin_id;
    A_Err 					err 				= A_Err_NONE,
                                        err2 				= A_Err_NONE;

    sP = pica_basicP;

    AEGP_SuiteHandler suites(pica_basicP);


    ERR(suites.CommandSuite1()->AEGP_GetUniqueCommand(&S_Grabba_cmd));


    ERR(suites.CommandSuite1()->AEGP_InsertMenuCommand(	S_Grabba_cmd,
            "Grabba",
            AEGP_Menu_EXPORT,
            AEGP_MENU_INSERT_SORTED));

    ERR(suites.RegisterSuite5()->AEGP_RegisterCommandHook(	S_my_id,
            AEGP_HP_BeforeAE,
            AEGP_Command_ALL,
            CommandHook,
            0));
    ERR(suites.RegisterSuite5()->AEGP_RegisterDeathHook(S_my_id, DeathHook,	NULL));

    ERR(suites.RegisterSuite5()->AEGP_RegisterUpdateMenuHook(S_my_id, UpdateMenuHook, NULL));

    ERR(suites.RegisterSuite5()->AEGP_RegisterIdleHook(S_my_id, IdleHook, NULL));

    if (err) { // not !err, err!
        ERR2(suites.UtilitySuite3()->AEGP_ReportInfo(S_my_id, "Grabba : Could not register command hook."));
    }
    return err;
}
Example #11
0
/**
 * base_check_watchdog - check if expired or trigger.
 * currently only second resolution!
 *
 * @param base
 * @param trig if != 0 then trigger watchdog
 */
static void base_check_watchdog(struct youbot_base_info* base, int trig)
{
	struct timespec ts_cur;

	if(clock_gettime(CLOCK_MONOTONIC, &ts_cur) != 0) {
		ERR2(errno, "clock_gettime failed");
		goto out;
	}

	if(trig) {
		base->last_cmd = ts_cur;
		goto out;
	}

	if(ts_cur.tv_sec - base->last_cmd.tv_sec >= BASE_TIMEOUT) {
		ERR("watchdog timeout out, setting control_mode to MOTORSTOP");
		base->control_mode=YOUBOT_CMODE_MOTORSTOP;
		goto out;
	}
 out:
	return;
}
Example #12
0
A_Err
EntryPointFunc(
	struct SPBasicSuite		*pica_basicP,		/* >> */
	A_long				 	major_versionL,		/* >> */		
	A_long					minor_versionL,		/* >> */		
	AEGP_PluginID			aegp_plugin_id,		/* >> */
	AEGP_GlobalRefcon		*global_refconP)	/* << */
{
	A_Err 			err					=	A_Err_NONE, 
					err2 				=	A_Err_NONE;
					sP					=	pica_basicP;
					S_my_id				=	aegp_plugin_id;	

	try {
		AEGP_SuiteHandler	suites(sP);

		ERR(suites.CommandSuite1()->AEGP_GetUniqueCommand(&S_Text_Twiddler_cmd));

		ERR(suites.CommandSuite1()->AEGP_InsertMenuCommand(	S_Text_Twiddler_cmd, 
															STR(StrID_Selection), 
															AEGP_Menu_LAYER, 
															AEGP_MENU_INSERT_AT_TOP));

		ERR(suites.RegisterSuite5()->AEGP_RegisterCommandHook(	S_my_id, 
																AEGP_HP_BeforeAE, 
																AEGP_Command_ALL, 
																CommandHook, 
																NULL));

		ERR(suites.RegisterSuite5()->AEGP_RegisterUpdateMenuHook(S_my_id, UpdateMenuHook, NULL));

		if (err) { // not !err, err!
			ERR2(suites.UtilitySuite3()->AEGP_ReportInfo(S_my_id, STR(StrID_Troubles)));
		}
	} catch (A_Err &thrown_err){
		err = thrown_err;
	}
	return err;
}
int doall(int except_flag)
{
	itemcount = 0;
	try {
		// before and after the run, removing any
		// old environment/database.
		//
		removeall();
		t1(except_flag);
		t2(except_flag);
		t3(except_flag);
		t4(except_flag);
		t5(except_flag);
		t6(except_flag);

		removeall();
		return 0;
	}
	catch (DbException &dbe) {
		ERR2("EXCEPTION RECEIVED", dbe.what());
	}
	return 1;
}
Example #14
0
static A_Err	
FBIO_InitInSpecFromFile(
	AEIO_BasicData		*basic_dataP,
	const A_UTF16Char	*file_pathZ,
	AEIO_InSpecH		specH)
{ 
	/*	Read the file referenced by the path. Use the 
		file information to set all fields of the AEIO_InSpecH.
	*/

	A_Err			err				=	A_Err_NONE,
					err2			=	A_Err_NONE;
	AEIO_Handle		optionsH		=	NULL,
					old_optionsH	=	NULL;
	FBIO_FileHeader	*headerP;

	AEGP_SuiteHandler	suites(basic_dataP->pica_basicP);

	if (!err) {
		/*		What are we doing here? 

			+	Allocate a new OptionsH to hold our file header info.
			+	Lock it in memory, copy our local header into the OptionsH.
			+	Unlock handle so AE can move it at will.
		
		*/
		
		ERR(suites.MemorySuite1()->AEGP_NewMemHandle(	S_mem_id,
														"SDK_IO optionsH", 
														sizeof(FBIO_FileHeader), 
														AEGP_MemFlag_CLEAR, 
														&optionsH));
													
		if (optionsH){
			ERR(suites.MemorySuite1()->AEGP_LockMemHandle(optionsH, reinterpret_cast<void **>(&headerP)));
		}	
		if (!err){
			
			ERR(PretendToReadFileHeader(basic_dataP, headerP));

			ERR(suites.IOInSuite4()->AEGP_SetInSpecOptionsHandle(	specH, 
																	optionsH, 
																	reinterpret_cast<void **>(&old_optionsH)));
		
			// [23547] Do _not_ free the old options handle here.  This results in a crash when user chooses 
			// Reload Footage, the handle is freed here, and FBIO_DisposeOutputOptions() is called later on.
			//if (old_optionsH){
				// ERR(suites.MemorySuite1()->AEGP_FreeMemHandle(old_optionsH));
			//}
		}

		/*	
			Set specH information based on what we (pretended to) read from the file.
		*/

		ERR(suites.IOInSuite4()->AEGP_SetInSpecDepth(specH, headerP->bitdepthS)); // always 32 bits for .fak files
		ERR(suites.IOInSuite4()->AEGP_SetInSpecDuration(specH, &(headerP->durationT)));
		ERR(suites.IOInSuite4()->AEGP_SetInSpecDimensions(	specH, 
															static_cast<A_long>(headerP->widthLu),
															static_cast<A_long>(headerP->heightLu)));

		if (!err){
			AEIO_AlphaLabel	alpha;
			AEFX_CLR_STRUCT(alpha);

			alpha.alpha		=	AEIO_Alpha_PREMUL;
			alpha.flags		=	AEIO_AlphaPremul;
			alpha.version	=	AEIO_AlphaLabel_VERSION;
			alpha.red		=	146;
			alpha.green		=	123;
			alpha.blue		=	23;
			
			err = suites.IOInSuite4()->AEGP_SetInSpecAlphaLabel(specH, &alpha);
		}
		ERR2(suites.MemorySuite1()->AEGP_UnlockMemHandle(optionsH));
	}
	return err;
}
Example #15
0
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
  int i, rv;
  const char *user = NULL;
  char *password;
  unsigned int slot_num = 0;
  int is_a_screen_saver = 0;
  struct configuration_st *configuration;
  int pkcs11_pam_fail = PAM_AUTHINFO_UNAVAIL;

  pkcs11_handle_t *ph;
  cert_object_t *chosen_cert = NULL;
  cert_object_t **cert_list;
  int ncert;
  unsigned char random_value[128];
  unsigned char *signature;
  unsigned long signature_length;
  /* enough space to hold an issuer DN */
  char env_temp[256] = "";
  char **issuer, **serial;
  const char *login_token_name = NULL;

  pam_prompt(pamh, PAM_TEXT_INFO , NULL, _("Smartcard authentication starts"));

  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc,argv);
  if (!configuration ) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* Either slot_description or slot_num, but not both, needs to be used */
  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* fail if we are using a remote server
   * local login: DISPLAY=:0
   * XDMCP login: DISPLAY=host:0 */
  {
	  char *display = getenv("DISPLAY");

	  if (display)
	  {
		  if (strncmp(display, "localhost:", 10) != 0 && (display[0] != ':')
			  && (display[0] != '\0')) {
			  ERR1("Remote login (from %s) is not (yet) supported", display);
			  pam_syslog(pamh, LOG_ERR,
				  "Remote login (from %s) is not (yet) supported", display);
			  return PAM_AUTHINFO_UNAVAIL;
		  }
	  }
  }

#ifdef ENABLE_NLS
  setlocale(LC_ALL, "");
  bindtextdomain(PACKAGE, "/usr/share/locale");
  textdomain(PACKAGE);
#endif

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    ERR("Failed to initialize crypto");
    if (!configuration->quiet)
      pam_syslog(pamh,LOG_ERR, "Failed to initialize crypto");
    return PAM_AUTHINFO_UNAVAIL;
  }


  /*
   * card_only means:
   *  1) always get the userid from the certificate.
   *  2) don't prompt for the user name if the card is present.
   *  3) if the token is present, then we must use the cardAuth mechanism.
   *
   * wait_for_card means:
   *  1) nothing if card_only isn't set
   *  2) if logged in, block in pam conversation until the token used for login
   *     is inserted
   *  3) if not logged in, block until a token that could be used for logging in
   *     is inserted
   * right now, logged in means PKC11_LOGIN_TOKEN_NAME is set,
   * but we could something else later (like set some per-user state in
   * a pam session module keyed off uid)
   */
  if (configuration->card_only) {
	char *service;
	if (configuration->screen_savers) {
	    DBG("Is it a screen saver?");
		pam_get_item(pamh, PAM_SERVICE, &service);
	    for (i=0; configuration->screen_savers[i]; i++) {
		if (strcmp(configuration->screen_savers[i], service) == 0) {
		    is_a_screen_saver = 1;
		    break;
		}
	    }
	}

	pkcs11_pam_fail = PAM_CRED_INSUFFICIENT;

	/* look to see if username is already set */
	pam_get_item(pamh, PAM_USER, &user);
	if (user) {
	    DBG1("explicit username = [%s]", user);
	}
  } else {
	rv = pam_get_item(pamh, PAM_USER, &user);
	if (rv != PAM_SUCCESS || user == NULL || user[0] == '\0') {
	  pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("Please insert your %s or enter your username."),
		  _(configuration->token_type));
	  /* get user name */
	  rv = pam_get_user(pamh, &user, NULL);

	  if (rv != PAM_SUCCESS) {
		pam_syslog(pamh, LOG_ERR,
			"pam_get_user() failed %s", pam_strerror(pamh, rv));
		return PAM_USER_UNKNOWN;
	  }
	}
	DBG1("username = [%s]", user);
  }
  login_token_name = getenv("PKCS11_LOGIN_TOKEN_NAME");

  /* if we are using a screen saver, and we didn't log in using the smart card
   * drop to the next pam module.  */
  if (is_a_screen_saver && !login_token_name) {
    return PAM_IGNORE;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    ERR2("load_pkcs11_module() failed loading %s: %s",
		configuration->pkcs11_modulepath, get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "load_pkcs11_module() failed loading %s: %s",
			configuration->pkcs11_modulepath, get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2302: PKCS#11 module failed loading"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("init_pkcs11_module() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "init_pkcs11_module() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2304: PKCS#11 module could not be initialized"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel_and_tokenlabel(ph,
      configuration->slot_description, login_token_name, &slot_num);
  } else if (configuration->slot_num != -1) {
    rv = find_slot_by_number_and_label(ph, configuration->slot_num,
                                     login_token_name, &slot_num);
  }

  if (rv != 0) {
    ERR("no suitable token available");
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "no suitable token available");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2306: No suitable token available"));
		sleep(configuration->err_display_time);
	}

    if (!configuration->card_only) {
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    }

    /* we must have a smart card, either because we've configured it as such,
     * or because we used one to log in */
    if (login_token_name || configuration->wait_for_card) {
      if (login_token_name) {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Please insert your smart card called \"%.32s\"."),
			login_token_name);
      } else {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
                 _("Please insert your smart card."));
      }

      if (configuration->slot_description != NULL) {
	rv = wait_for_token_by_slotlabel(ph, configuration->slot_description,
          login_token_name, &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = wait_for_token(ph, configuration->slot_num,
                          login_token_name, &slot_num);
      }

      if (rv != 0) {
        release_pkcs11_module(ph);
        return pkcs11_pam_fail;
      }
    } else if (user) {
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2308: No smartcard found"));
			sleep(configuration->err_display_time);
		}

      /* we have a user and no smart card, go to the next pam module */
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    } else {
      /* we haven't prompted for the user yet, get the user and see if
       * the smart card has been inserted in the mean time */
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
	    _("Please insert your %s or enter your username."),
		_(configuration->token_type));
      rv = pam_get_user(pamh, &user, NULL);

      /* check one last time for the smart card before bouncing to the next
       * module */
      if (configuration->slot_description != NULL) {
	rv = find_slot_by_slotlabel(ph, configuration->slot_description,
	  &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = find_slot_by_number(ph, configuration->slot_num, &slot_num);
      }

      if (rv != 0) {
        /* user gave us a user id and no smart card go to next module */
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2310: No smartcard found"));
			sleep(configuration->err_display_time);
		}

        release_pkcs11_module(ph);
        return PAM_AUTHINFO_UNAVAIL;
      }
    }
  } else {
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("%s found."), _(configuration->token_type));
  }
  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    ERR1("open_pkcs11_session() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "open_pkcs11_session() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2312: open PKCS#11 session failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  }

  rv = get_slot_login_required(ph);
  if (rv == -1) {
    ERR1("get_slot_login_required() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_slot_login_required() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2314: Slot login failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  } else if (rv) {
    /* get password */
	pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		_("Welcome %.32s!"), get_slot_tokenlabel(ph));

	/* no CKF_PROTECTED_AUTHENTICATION_PATH */
	rv = get_slot_protected_authentication_path(ph);
	if ((-1 == rv) || (0 == rv))
	{
		char password_prompt[128];

		snprintf(password_prompt,  sizeof(password_prompt), _("%s PIN: "), _(configuration->token_type));
		if (configuration->use_first_pass) {
			rv = pam_get_pwd(pamh, &password, NULL, PAM_AUTHTOK, 0);
		} else if (configuration->try_first_pass) {
			rv = pam_get_pwd(pamh, &password, password_prompt, PAM_AUTHTOK,
					PAM_AUTHTOK);
		} else {
			rv = pam_get_pwd(pamh, &password, password_prompt, 0, PAM_AUTHTOK);
		}
		if (rv != PAM_SUCCESS) {
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2316: password could not be read"));
				sleep(configuration->err_display_time);
			}
			release_pkcs11_module(ph);
			pam_syslog(pamh, LOG_ERR,
					"pam_get_pwd() failed: %s", pam_strerror(pamh, rv));
			return pkcs11_pam_fail;
		}
#ifdef DEBUG_SHOW_PASSWORD
		DBG1("password = [%s]", password);
#endif

		/* check password length */
		if (!configuration->nullok && strlen(password) == 0) {
			release_pkcs11_module(ph);
			memset(password, 0, strlen(password));
			free(password);
			pam_syslog(pamh, LOG_ERR,
					"password length is zero but the 'nullok' argument was not defined.");
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2318: Empty smartcard PIN not allowed."));
				sleep(configuration->err_display_time);
			}
			return PAM_AUTH_ERR;
		}
	}
	else
	{
		pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Enter your %s PIN on the pinpad"), _(configuration->token_type));
		/* use pin pad */
		password = NULL;
	}

    /* call pkcs#11 login to ensure that the user is the real owner of the card
     * we need to do thise before get_certificate_list because some tokens
     * can not read their certificates until the token is authenticated */
    rv = pkcs11_login(ph, password);
    /* erase and free in-memory password data asap */
	if (password)
	{
		memset(password, 0, strlen(password));
		free(password);
	}
    if (rv != 0) {
      ERR1("open_pkcs11_login() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "open_pkcs11_login() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2320: Wrong smartcard PIN"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }
  }

  cert_list = get_certificate_list(ph, &ncert);
  if (rv<0) {
    ERR1("get_certificate_list() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_certificate_list() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2322: No certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find a valid and matching certificates */
  for (i = 0; i < ncert; i++) {
    X509 *x509 = (X509 *)get_X509_certificate(cert_list[i]);
    if (!x509 ) continue; /* sanity check */
    DBG1("verifying the certificate #%d", i + 1);
	if (!configuration->quiet) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("verifying certificate"));
	}

      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509,&configuration->policy);
      if (rv < 0) {
        ERR1("verify_certificate() failed: %s", get_error());
        if (!configuration->quiet) {
          pam_syslog(pamh, LOG_ERR,
                   "verify_certificate() failed: %s", get_error());
			switch (rv) {
				case -2: // X509_V_ERR_CERT_HAS_EXPIRED:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2324: Certificate has expired"));
					break;
				case -3: // X509_V_ERR_CERT_NOT_YET_VALID:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2326: Certificate not yet valid"));
					break;
				case -4: // X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2328: Certificate signature invalid"));
					break;
				default:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2330: Certificate invalid"));
					break;
			}
			sleep(configuration->err_display_time);
		}
        continue; /* try next certificate */
      } else if (rv != 1) {
        ERR1("verify_certificate() failed: %s", get_error());
        continue; /* try next certificate */
      }

    /* CA and CRL verified, now check/find user */

    if ( is_spaced_str(user) ) {
      /*
	if provided user is null or empty extract and set user
	name from certificate
      */
	DBG("Empty login: try to deduce from certificate");
	user=find_user(x509);
	if (!user) {
          ERR2("find_user() failed: %s on cert #%d", get_error(),i+1);
          if (!configuration->quiet)
            pam_syslog(pamh, LOG_ERR,
                     "find_user() failed: %s on cert #%d",get_error(),i+1);
	  continue; /* try on next certificate */
	} else {
          DBG1("certificate is valid and matches user %s",user);
	  /* try to set up PAM user entry with evaluated value */
	  rv = pam_set_item(pamh, PAM_USER,(const void *)user);
	  if (rv != PAM_SUCCESS) {
	    ERR1("pam_set_item() failed %s", pam_strerror(pamh, rv));
            if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR,
                       "pam_set_item() failed %s", pam_strerror(pamh, rv));
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2332: setting PAM userentry failed"));
				sleep(configuration->err_display_time);
			}
	    goto auth_failed_nopw;
	}
          chosen_cert = cert_list[i];
          break; /* end loop, as find user success */
      }
    } else {
      /* User provided:
         check whether the certificate matches the user */
        rv = match_user(x509, user);
        if (rv < 0) { /* match error; abort and return */
          ERR1("match_user() failed: %s", get_error());
			if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR, "match_user() failed: %s", get_error());
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2334: No matching user"));
				sleep(configuration->err_display_time);
			}
	  goto auth_failed_nopw;
        } else if (rv == 0) { /* match didn't success */
          DBG("certificate is valid but does not match the user");
	  continue; /* try next certificate */
        } else { /* match success */
          DBG("certificate is valid and matches the user");
          chosen_cert = cert_list[i];
          break;
      }
    } /* if is_spaced string */
  } /* for (i=0; i<ncerts; i++) */

  /* now myCert points to our found certificate or null if no user found */
  if (!chosen_cert) {
    ERR("no valid certificate which meets all requirements found");
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR,
				"no valid certificate which meets all requirements found");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2336: No matching certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }


  /* if signature check is enforced, generate random data, sign and verify */
  if (configuration->policy.signature_policy) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("Checking signature"));


#ifdef notdef
    rv = get_private_key(ph);
    if (rv != 0) {
      ERR1("get_private_key() failed: %s", get_error());
      if (!configuration->quiet)
        pam_syslog(pamh, LOG_ERR,
                 "get_private_key() failed: %s", get_error());
      goto auth_failed_nopw;
    }
#endif

    /* read random value */
    rv = get_random_value(random_value, sizeof(random_value));
    if (rv != 0) {
      ERR1("get_random_value() failed: %s", get_error());
		if (!configuration->quiet){
			pam_syslog(pamh, LOG_ERR, "get_random_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2338: Getting random value failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* sign random value */
    signature = NULL;
    rv = sign_value(ph, chosen_cert, random_value, sizeof(random_value),
		    &signature, &signature_length);
    if (rv != 0) {
      ERR1("sign_value() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "sign_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2340: Signing failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* verify the signature */
    DBG("verifying signature...");
    rv = verify_signature((X509 *)get_X509_certificate(chosen_cert),
             random_value, sizeof(random_value), signature, signature_length);
    if (signature != NULL) {
      free(signature);
    }
    if (rv != 0) {
      close_pkcs11_session(ph);
      release_pkcs11_module(ph);
      ERR1("verify_signature() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "verify_signature() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2342: Verifying signature failed"));
			sleep(configuration->err_display_time);
		}
      return PAM_AUTH_ERR;
    }

  } else {
      DBG("Skipping signature check");
  }

  /*
   * fill in the environment variables.
   */
  snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_TOKEN_NAME=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_TOKEN_NAME=")),
	   get_slot_tokenlabel(ph));
  rv = pam_putenv(pamh, env_temp);

  if (rv != PAM_SUCCESS) {
    ERR1("could not put token name in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put token name in environment: %s",
           pam_strerror(pamh, rv));
  }

  issuer = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_ISSUER,
                     ALGORITHM_NULL);
  if (issuer) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_ISSUER=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_ISSUER=")),
	   issuer[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate issuer.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate issuer.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert issuer in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert issuer in environment: %s",
           pam_strerror(pamh, rv));
  }

  serial = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_SERIAL,
                     ALGORITHM_NULL);
  if (serial) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_SERIAL=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_SERIAL=")),
	   serial[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate serial number.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate serial number.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert serial in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert serial in environment: %s",
           pam_strerror(pamh, rv));
  }

  /* unload mapper modules */
  unload_mappers();

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("close_pkcs11_session() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "close_pkcs11_module() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, ("Error 2344: Closing PKCS#11 session failed"));
			sleep(configuration->err_display_time);
		}
    return pkcs11_pam_fail;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("authentication succeeded");
  return PAM_SUCCESS;

    /* quick and dirty fail exit point */
    memset(password, 0, strlen(password));
    free(password); /* erase and free in-memory password data */

auth_failed_nopw:
    unload_mappers();
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
}
Example #16
0
int main(int argc, char ** argv)
{
	int listen_fd, epfd;
	int epoll_events_count;
	struct epoll_event ev, events[EPOLL_EVENTS_MAX];
	struct sockaddr_in clientaddr;
	socklen_t addrlen;
	int i, serv_port;
	SAK_threadpool_t * tp_handler = NULL;

#if DEBUG
	clock_t tstart;
#endif

	if(argc != 2)
	{
		perror("usage: ./lotus <port>");
		exit(-1);
	}

	serv_port = atoi(argv[1]);
	
	bzero(&clientaddr, sizeof(clientaddr));
	addrlen = sizeof(struct sockaddr_in);

	/*********************** thread pool ***************************/
	tp_handler = threadpool_create(THREADPOOL_THREADS);
	assert(tp_handler != NULL);
	printf("thread pool is created\n");

	/************************** socket *****************************/
	/* make server socket */
	ERR2(listen_fd, make_server_socket(serv_port));
	printf("web server socket is made\n");

	/**************************** epoll ****************************/
	/* create epoll */
	ERR2(epfd, epoll_create(EPOLL_SIZE));
	ev.data.fd = listen_fd;
	ev.events = EPOLLIN|EPOLLET;

	ERR(set_nonblock(listen_fd));
	
	/* add listen_fd to epoll */
	ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, listen_fd, &ev));
	printf("epoll module is created\n");

	
	/* ignore pipe broken signal */	
	signal(SIGPIPE, SIG_IGN);

	/************************* main ********************************/
	for(;;)
	{
		/* wait for changes of fd set */
		ERR2(epoll_events_count, epoll_wait(epfd, events, EPOLL_EVENTS_MAX, EPOLL_TIMEOUT));

#if DEBUG
		tstart = clock();
#endif
		for(i = 0; i < epoll_events_count; i++)
		{

#if DEBUG
			printf("events[%d].data.fd == %d\n", i, events[i].data.fd);
#endif
			if((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN)))
			{
				fprintf(stderr, "ERROR: epoll error\n");
				close(events[i].data.fd);
				continue;
			}
			else if(events[i].data.fd == listen_fd)
			{
#if DEBUG
				printf("Is listen_fd = %d\n", listen_fd);
#endif
				/* a new connection is coming, we accept it 
				   and add the new connection fd to epoll set  */
				while(1)
				{
					int connect_fd;
					char clientaddr_buff[20] = {0};
					connect_fd = accept(listen_fd, (struct sockaddr *)&clientaddr, &addrlen);

					if(connect_fd == -1)
					{
						if((errno == EAGAIN) || (errno == EWOULDBLOCK))
						{
							/* We have process all incoming connection */
							break;
						}
						else
						{
							perror("accept");
							break;
						}
					}
					inet_ntop(AF_INET, &clientaddr.sin_addr, clientaddr_buff, sizeof(clientaddr_buff)), 
					printf("Client [%s : %d] is connected\n", clientaddr_buff, ntohs(clientaddr.sin_port));

					ERR(set_nonblock(connect_fd));
					ev.data.fd = connect_fd;

#if DEBUG
					printf("Get and put connect_fd = %d into epoll\n", connect_fd);
#endif
					ev.events = EPOLLIN|EPOLLET;
					ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, connect_fd, &ev));
				}
				continue;
			}
			else
			{
				/* Can read */

				/************************************************/
				/*  Put the task into thread pool's work queue  */             
				/************************************************/
#if DEBUG
				printf("Is connect_fd = %d\n", events[i].data.fd);
#endif
				threadpool_put(tp_handler, process_request, (void *)events[i].data.fd);
				request_count ++;
				printf("Has handle %d requests\n", request_count);
				//ERR(epoll_ctl(epfd, EPOLL_CTL_DEL, ev.data.fd, &ev));
			}

		}
#if DEBUG
		printf("Statistics: %d events handled at %2.f seconds(s)\n", epoll_events_count, (double)(clock() - tstart)/CLOCKS_PER_SEC);
#endif
	}
	
	close(listen_fd);
	close(epfd);
	threadpool_destroy(tp_handler);
	return 0;
}
Example #17
0
static int get_translated_line1(InputSource s)
{
    unsigned int c;		/* can't use Char, it might be >0x10000 */
    unsigned char *inbuf = s->inbuf;
    int nextin = s->nextin, insize = s->insize;
    int startin = s->nextin;
    Char *outbuf = s->line;
    int outsize = s->line_alloc;
    int nextout = 0;
    int remaining = 0;
    int ignore_linefeed = s->line_end_was_cr;

#if CHAR_SIZE == 16

    int *to_unicode = 0;	/* initialize to shut gcc up */
    CharacterEncoding enc = s->entity->encoding;
    int more, i;
    s->complicated_utf8_line = 0;

    if(enc >= CE_ISO_8859_2 && enc <= CE_ISO_8859_9)
	to_unicode = iso_to_unicode[enc - CE_ISO_8859_2];

#endif

    s->line_end_was_cr = 0;
    s->bytes_before_current_line = s->bytes_consumed;

    while(1)
    {
	/* There are never more characters than bytes in the input */
	if(outsize < nextout + (insize - nextin))
	{
	    outsize = nextout + (insize - nextin);
	    outbuf = Realloc(outbuf, outsize * sizeof(Char));
	}

	while(nextin < insize)
	{
#if CHAR_SIZE == 8
	    c = inbuf[nextin++];
#else
	    switch(enc)
	    {
	    case CE_ISO_10646_UCS_2B:
	    case CE_UTF_16B:
		if(nextin+2 > insize)
		    goto more_bytes;
		c = (inbuf[nextin] << 8) + inbuf[nextin+1];
		nextin += 2;
		break;
	    case CE_ISO_10646_UCS_2L:
	    case CE_UTF_16L:
		if(nextin+2 > insize)
		    goto more_bytes;
		c = (inbuf[nextin+1] << 8) + inbuf[nextin];
		nextin += 2;
		break;
	    case CE_ISO_8859_1:
	    case CE_unspecified_ascii_superset:
		c = inbuf[nextin++];
		break;
	    case CE_ISO_8859_2:
	    case CE_ISO_8859_3:
	    case CE_ISO_8859_4:
	    case CE_ISO_8859_5:
	    case CE_ISO_8859_6:
	    case CE_ISO_8859_7:
	    case CE_ISO_8859_8:
	    case CE_ISO_8859_9:
		c = to_unicode[inbuf[nextin++]];
		if(c == (unsigned int)-1)
		  ERR3("Illegal %s character <0x%x> "
			    "at file offset %d\n",
			    CharacterEncodingName[enc], inbuf[nextin-1],
			    s->bytes_consumed + nextin - 1 - startin);
		break;
	    case CE_UTF_8:
		c = inbuf[nextin++];
		if(c <= 0x7f)
		    break;
		if(c <= 0xc0 || c >= 0xfe)
		{
		  ERR2("Illegal UTF-8 start byte <0x%x> "
			    "at file offset %d\n",
			    c, s->bytes_consumed + nextin - 1 - startin);
		    return -1;
		}
		if(c <= 0xdf)
		{
		    c &= 0x1f;
		    more = 1;
		}
		else if(c <= 0xef)
		{
		    c &= 0x0f;
		    more = 2;
		}
		else if(c <= 0xf7)
		{
		    c &= 0x07;
		    more = 3;
		}
		else if(c <= 0xfb)
		{
		    c &= 0x03;
		    more = 4;
		}
		else
		{
		    c &= 0x01;
		    more = 5;
		}
		if(nextin+more > insize)
		{
		    nextin--;
		    goto more_bytes;
		}
		s->complicated_utf8_line = 1;
		for(i=0; i<more; i++)
		    c = (c << 6) + (inbuf[nextin++] & 0x3f);
		break;
	    default:
	      ERR("read from entity with unsupported encoding!\n");
		return -1;
	    }

	    if(c > 0x110000 || (c < 0x10000 && !is_xml_legal(c)))
		if(!(enc == CE_UTF_16L || enc == CE_UTF_16B) ||
		   c < 0xd800 || c > 0xdfff)
		    /* We treat the surrogates as legal because we didn't
		       combine them when translating from UTF-16.  XXX */
		{
		  ERR2("Error: illegal character <0x%x> "
			    "immediately before file offset %d\n",
			    c, s->bytes_consumed + nextin - startin);
		    return -1;
		}
#endif
	    if(c == '\n' && ignore_linefeed)
	    {
		/* Ignore lf at start of line if last line ended with cr */
		ignore_linefeed = 0;
		s->bytes_before_current_line += (nextin - startin);
	    }		
	    else
	    {
		ignore_linefeed = 0;
		if(c == '\r')
		{
		    s->line_end_was_cr = 1;
		    c = '\n';
		}

#if CHAR_SIZE == 16
		if(c >= 0x10000)
		{
		    /* Use surrogates */
		    outbuf[nextout++] = ((c - 0x10000) >> 10) + 0xd800;
		    outbuf[nextout++] = ((c - 0x10000) & 0x3ff) + 0xdc00;
		}
		else
		    outbuf[nextout++] = c;
#else
		outbuf[nextout++] = c;
#endif

		if(c == '\n')
		{
		    s->nextin = nextin;
		    s->insize = insize;
		    s->bytes_consumed += (nextin - startin);
		    s->line = outbuf;
		    s->line_alloc = outsize;
		    s->line_length = nextout;
		    return 0;
		}
	    }
	}
Example #18
0
bor_qhull_mesh3_t *borQDelaunayMesh3(bor_qdelaunay_t *q, const bor_pc_t *pc)
{
    int pipe_points[2];
    int pipe_result[2];
    int pid;
    bor_qhull_mesh3_t *mesh;

    // open pipes for communication between qdelaunay program and this
    // program
    if (pipe(pipe_points) != 0
            || pipe(pipe_result) != 0){
        ERR2("Can't open pipes.\n");
        return NULL;
    }

    // fork process - child process will run qdelaunay
    pid = fork();
    if (pid == 0){
        // child process

        // close write end of points pipe and read end of result pipe
        close(pipe_points[1]);
        close(pipe_result[0]);

        // duplicate read end of pipe_points to stdin
        if (dup2(pipe_points[0], 0) != 0){
            ERR2("Can't connect pipe to stdin!");
            exit(-1);
        }

        // and duplicate write end of pipe_result to stdout
        if (dup2(pipe_result[1], 1) != 1){
            perror("");
            ERR2("Can't connect pipe to stdout!");
            exit(-1);
        }

        execl(q->bin_path, q->bin_path, "o", NULL);

        perror("");
        ERR("execl(\"%s\", \"%s\", \"o\") failed!", q->bin_path, q->bin_path);
        exit(-1);

    }else if (pid < 0){
        ERR2("Fork failed!\n");
        close(pipe_points[0]);
        close(pipe_points[1]);
        close(pipe_result[0]);
        close(pipe_result[1]);
        return NULL;
    }

    // parent process

    // close read end of pipe_points
    close(pipe_points[0]);
    // and write end of pipe_result
    close(pipe_result[1]);

    // write points on qdelaunay stdin
    if (writePC33((bor_pc_t *)pc, pipe_points[1]) != 0){
        ERR2("Can't open write end of pipe using stdio.");
        close(pipe_points[1]);
    }

    // read result from qdelaunay
    mesh = qdelaunayToMesh3(pipe_result[0]);
    if (!mesh){
        ERR2("Can't open read end of pipe using stdio.");
        close(pipe_result[0]);
    }

    // wait for child process
    waitpid(pid, NULL, 0);

    return mesh;
}
Example #19
0
int main(void)
{

    for (int flags = 0; flags < 4; flags++) {
        int64_t start = flow_get_high_precision_ticks();
        for (int i = 2; i < 8; i++) {
            flow_c * c = flow_context_create();

            if ((flags & 2) == 0) {
                flow_context_set_floatspace(c, flow_working_floatspace_as_is, 0, 0, 0);
            }

            size_t bytes_count = 0;
            uint8_t * bytes = get_bytes_cached(
                c, &bytes_count, "http://s3-us-west-2.amazonaws.com/imageflow-resources/test_inputs/u6.jpg");

            struct flow_graph * g = flow_graph_create(c, 10, 10, 200, 2.0);
            ERR2(c);

            int32_t last, input_placeholder = 0;

            struct flow_job * job = flow_job_create(c);
            ERR2(c);
            // flow_job_configure_recording(c, job, true, true, true, true, true);

            struct flow_io * input
                = flow_io_create_from_memory(c, flow_io_mode_read_seekable, bytes, bytes_count, job, NULL);
            flow_job_add_io(c, job, input, input_placeholder, FLOW_INPUT);

            int original_width, original_height;
            if (!get_image_dimensions(c, bytes, bytes_count, &original_width, &original_height))
                ERR2(c);

            int min_factor = 3;

            int32_t target_w = original_width / i;
            int32_t target_h = (int32_t)ceil((float)target_w / (float)original_width * (float)original_height);

            if (!flow_job_decoder_set_downscale_hints_by_placeholder_id(
                    c, job, input_placeholder, (target_w - 1) * min_factor, (target_h - 1) * min_factor,
                    (target_w - 1) * min_factor, (target_h - 1) * min_factor, (flags & 2) > 0, (flags & 2) > 0)) {
                ERR2(c);
            }

            last = flow_node_create_decoder(c, &g, -1, input_placeholder);
            last = flow_node_create_scale(c, &g, last, target_w, target_h, (flow_interpolation_filter_Robidoux),
                                          (flow_interpolation_filter_Robidoux), flags, 0);

            struct flow_bitmap_bgra * b;
            last = flow_node_create_bitmap_bgra_reference(c, &g, last, &b);

            if (!flow_job_execute(c, job, &g)) {
                ERR2(c);
            }

            // flow_graph_print_to_dot(c, g, stdout, "");
            flow_job_destroy(c, job);

            flow_context_destroy(c);
        }
        int64_t end = flow_get_high_precision_ticks();
        int64_t ms = (end - start) * 1000 / flow_get_profiler_ticks_per_second();
        fprintf(stdout, "With flags=%d, took %dms\n", flags, (int32_t)ms);
        fflush(stdout);
        // code
    }
    return 0; // Zero indicates success, while any
    // Non-Zero value indicates a failure/error

    /*  Before changing idct_fast
     *  With flags=0, took 839ms: srgb, standard
        With flags=1, took 743ms: srgb, reducev
        With flags=2, took 3778ms: linear, standard
        With flags=3, took 1703ms: srgb, reducev


        Using fastpow in linear_to_srgb

        With flags=0, took 819ms
        With flags=1, took 738ms
        With flags=2, took 1588ms
        With flags=3, took 1062ms



     */
}
Example #20
0
int main(int argc, char **argv)
{
	FILE *fin  = NULL;
	FILE *fout = NULL;
	char header[8];
	uint8_t *image_data = NULL;
	png_bytep *row_pointers = NULL;
	int i;

	if (argc < 3) ERR("too few arguments")

	if ((fin = fopen(argv[1], "rb")) == NULL) ERR("cannot open man, lame!");

	printf("%s opened\n", argv[1]);

	fread(header, 1, 8, fin);
	if (png_check_sig(header, 8) == 0) ERR("not a valid .png image")

	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png_ptr) ERR("sdf");

	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr) {
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		ERR2("fssdfs");
	}

	if (setjmp(png_ptr->jmpbuf)) {
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        return 0;
    }

	png_init_io(png_ptr, fin);
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);
	printf("width    : %d\n", info_ptr->width);
	printf("height   : %d\n", info_ptr->height);
	printf("bpp      : %d\n", info_ptr->bit_depth);
	printf("palette  : %d entries\n", info_ptr->num_palette);
	printf("rowbytes : %d\n", info_ptr->rowbytes);
/*	fclose(fin);
	return 0;

	png_infop end_info = png_create_info_struct(png_ptr);
	if (!end_info) {
		png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
		ERR2("fjsh");
	}
*/
	// optional call to update palette with transformations
//	png_start_read_image(png_ptr);

	// optional call to update the info structure
//	png_read_update_info(png_ptr, info_ptr);
	if ((image_data = (uint8_t*)malloc(info_ptr->rowbytes*info_ptr->height)) == NULL) {
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
		return 0;
	}

	row_pointers = (png_bytep*)malloc(sizeof(png_bytep)*info_ptr->height);
	for (i=0;  i<info_ptr->height; ++i) row_pointers[i] = image_data + i*info_ptr->rowbytes;

	// the easiest way to read the image
	png_read_image(png_ptr, row_pointers);

	// void write_binimg(char *fname, uint8_t *data, png_color *pal_data, int pal_size, int width, int height, int bpp)
	char filename[256];
	strcpy(filename, argv[2]);
/*	write_binimg(strcat(filename, ".raw"), image_data, info_ptr->palette, info_ptr->num_palette,
		info_ptr->width, info_ptr->height, info_ptr->bit_depth);
*/
	write_2c(argv[2], image_data, info_ptr->palette, info_ptr->num_palette,
		info_ptr->width, info_ptr->height, info_ptr->bit_depth);

	// clean up after the read, and free any memory allocated
	png_read_destroy(png_ptr, info_ptr, (png_infop)0);
//	png_read_end(png_ptr, NULL);

i_am_done:
	if (image_data != NULL) free(image_data);
	if (row_pointers != NULL) free(row_pointers);
	if (fin != NULL) fclose(fin);
	if (fout != NULL) fclose(fout);

	return 0;
}
Example #21
0
static PF_Err
SmartRender(
	PF_InData				*in_data,
	PF_OutData				*out_data,
	PF_SmartRenderExtra		*extra)
{
	PF_Err				err		= PF_Err_NONE,
						err2	= PF_Err_NONE;
	
	PF_EffectWorld		*input_worldP	= NULL, 
						*output_worldP  = NULL;
	PF_WorldSuite2		*wsP			= NULL;
	PF_PixelFormat		format			= PF_PixelFormat_INVALID;
	PF_Point			origin			= {0,0};
	A_u_short			iSu				= 0;
	PF_Rect				current_rectR	= {0,0,0,0};
	A_long				box_acrossL		= 0,
						box_downL		= 0;

	
	AEGP_SuiteHandler suites(in_data->pica_basicP);
	
	CG_ArbData		*arbP			= NULL; 
	PF_PixelFloat	*current_colorP = NULL;

	PF_ParamDef arb_param;
	AEFX_CLR_STRUCT(arb_param);
	
	ERR(PF_CHECKOUT_PARAM(	in_data, 
							CG_GRID_UI, 
							in_data->current_time, 
							in_data->time_step, 
							in_data->time_scale, 
							&arb_param));
	
	if (!err){
		arbP = reinterpret_cast<CG_ArbData*>(*arb_param.u.arb_d.value);
		if (arbP){
			current_colorP = reinterpret_cast<PF_PixelFloat*>(arbP);
		}
	}
	ERR((extra->cb->checkout_layer_pixels(	in_data->effect_ref, CG_INPUT, &input_worldP)));
	
	ERR(extra->cb->checkout_output(	in_data->effect_ref, &output_worldP));
	
	if (!err){
		for(iSu = 0; !err && iSu < BOXES_PER_GRID; ++iSu){
			if(box_acrossL == BOXES_ACROSS)	{
				box_downL++;
				box_acrossL = 0;
			}
			ColorGrid_Get_Box_In_Grid(	&origin,
										in_data->width * in_data->downsample_x.num / in_data->downsample_x.den,
										in_data->height * in_data->downsample_y.num / in_data->downsample_y.den,
										box_acrossL,
										box_downL,
										&current_rectR);

			if (!err && output_worldP){
				ERR(AEFX_AcquireSuite(	in_data, 
										out_data, 
										kPFWorldSuite, 
										kPFWorldSuiteVersion2, 
										"Couldn't load suite.",
										(void**)&wsP));
				
				ERR(wsP->PF_GetPixelFormat(input_worldP, &format));
				
				origin.h = (A_short)(in_data->output_origin_x);
				origin.v = (A_short)(in_data->output_origin_y);
				
				if (!err){
					switch (format) {
						
						case PF_PixelFormat_ARGB128:
							
							ERR(suites.IterateFloatSuite1()->iterate_origin(in_data,
																			0,
																			output_worldP->height,
																			input_worldP,
																			&current_rectR,
																			&origin,
																			reinterpret_cast<void*>(current_colorP),
																			ColorGrid_ColorizePixelFloat,
																			output_worldP));
							break;
							
						case PF_PixelFormat_ARGB64:
							
							PF_Pixel16 temp16;
							
							temp16.red		= static_cast<A_u_short>(current_colorP->red	* PF_MAX_CHAN16);
							temp16.green	= static_cast<A_u_short>(current_colorP->green * PF_MAX_CHAN16);
							temp16.blue		= static_cast<A_u_short>(current_colorP->blue	* PF_MAX_CHAN16);
							temp16.alpha	= static_cast<A_u_short>(current_colorP->red	* PF_MAX_CHAN16);
							
							ERR(suites.Iterate16Suite1()->iterate_origin(	in_data,
																			0,
																			output_worldP->height,
																			input_worldP,
																			&current_rectR,
																			&origin,
																			reinterpret_cast<void*>(&temp16),
																			ColorGrid_ColorizePixel16,
																			output_worldP));
							break;
							
						case PF_PixelFormat_ARGB32:
							
							PF_Pixel8 temp8;
							
							temp8.red		= static_cast<A_u_char>(current_colorP->red		* PF_MAX_CHAN8);
							temp8.green		= static_cast<A_u_char>(current_colorP->green	* PF_MAX_CHAN8);
							temp8.blue		= static_cast<A_u_char>(current_colorP->blue	* PF_MAX_CHAN8);
							
							ERR(suites.Iterate8Suite1()->iterate_origin(	in_data,
																			0,
																			output_worldP->height,
																			input_worldP,
																			&current_rectR,
																			&origin,
																			reinterpret_cast<void*>(&temp8),
																			ColorGrid_ColorizePixel8,
																			output_worldP));
							break;
							
						default:
							err = PF_Err_BAD_CALLBACK_PARAM;
							break;
					}
				}
			}
			current_colorP++;
			box_acrossL++;
		}
	}
	ERR2(AEFX_ReleaseSuite(	in_data,
							out_data,
							kPFWorldSuite, 
							kPFWorldSuiteVersion2, 
							"Couldn't release suite."));
	ERR2(PF_CHECKIN_PARAM(in_data, &arb_param));
	ERR2(extra->cb->checkin_layer_pixels(in_data->effect_ref, CG_INPUT));
	return err;
}
Example #22
0
static A_Err
CommandHook(
	AEGP_GlobalRefcon	plugin_refconPV,		/* >> */
	AEGP_CommandRefcon	refconPV,				/* >> */
	AEGP_Command		command,				/* >> */
	AEGP_HookPriority	hook_priority,			/* >> */
	A_Boolean			already_handledB,		/* >> */
	A_Boolean			*handledPB)				/* << */
{
	A_Err 				err 					= A_Err_NONE, 
						err2 					= A_Err_NONE;

	AEGP_StreamType		stream_type				= AEGP_StreamType_NO_DATA;
	AEGP_StreamRefH		new_streamH				= NULL,
						text_streamH			= NULL;

	A_Time				timeT					= {0,1};
	AEGP_LTimeMode		time_mode				= AEGP_LTimeMode_LayerTime;
	AEGP_LayerH			layerH 					= NULL;
	AEGP_StreamValue	val;
	
	AEGP_SuiteHandler	suites(sP);

	if (command == S_Text_Twiddler_cmd) {
		try {
			ERR(suites.UtilitySuite3()->AEGP_StartUndoGroup(STR(StrID_Name)));
			AEFX_CLR_STRUCT(val);	// wash before first use.
			ERR(suites.LayerSuite5()->AEGP_GetActiveLayer(&layerH));			
			
			// 	How do we know there's only one text layer selected? Because
			//	our command wouldn't have been enabled if it weren't. -bbb 5/12/04
			
			ERR(suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefForLayer(S_my_id, layerH, &new_streamH));
			ERR(suites.StreamSuite2()->AEGP_GetNewLayerStream(	S_my_id, 
																layerH,
																AEGP_LayerStream_SOURCE_TEXT,
																&text_streamH));
			ERR(suites.StreamSuite2()->AEGP_GetStreamType(text_streamH, &stream_type));
			
			if (!err && (stream_type == AEGP_StreamType_TEXT_DOCUMENT)){
				ERR(suites.LayerSuite5()->AEGP_GetLayerCurrentTime(layerH, time_mode, &timeT));
				ERR(suites.StreamSuite2()->AEGP_GetNewStreamValue(	S_my_id,
																	text_streamH,
																	AEGP_LTimeMode_LayerTime,
																	&timeT,
																	TRUE,
																	&val));
																	
				//	Yes, Unicode looks funny. Use your favorite platform-specific
				//	routine to turn plain old char *'s into Unicode. Or just write hex!
				
				const A_u_short unicode[] = {0x0042, 0x0042, 0x0042};  // "BBB"

				A_long	lengthL = sizeof(unicode) / sizeof(A_u_short);
				
				ERR(suites.TextDocumentSuite1()->AEGP_SetText(val.val.text_documentH, unicode, lengthL));
				ERR(suites.StreamSuite2()->AEGP_SetStreamValue(S_my_id, text_streamH, &val));
				*handledPB = TRUE;
			}
			ERR2(suites.StreamSuite2()->AEGP_DisposeStreamValue(&val));
			if (new_streamH){
				ERR2(suites.StreamSuite2()->AEGP_DisposeStream(new_streamH));
			}
			if (text_streamH){
				ERR2(suites.StreamSuite2()->AEGP_DisposeStream(text_streamH));
			}
			ERR2(suites.UtilitySuite3()->AEGP_EndUndoGroup());
		} catch (A_Err &thrown_err){
			err = thrown_err;
		}
	}
	return err;		
}
Example #23
0
/*---< pnetcdf_write() >-----------------------------------------------------*/
int pnetcdf_write(char      *filename,     /* input file name */
                  int        save_in_new_file,  /* 0 or 1 */
                  int        numClusters,  /* no. clusters */
                  int        numObjs,      /* no. data objects */
                  int        numCoords,    /* no. coordinates (local) */
                  float    **clusters,     /* [numClusters][numCoords] centers*/
                  int       *membership,   /* [numObjs] */
                  int        totalNumObjs, /* total no. data objects */
                  MPI_Comm   comm,
                  int        verbose)
{
    int   rank, nproc, divd, rem;
    char  outFileName[1024];
    int        ncid, dimids[2], dim_num_obj, clusters_varid, membership_varid, retval;
    MPI_Offset start, count;

    MPI_Comm_rank(comm, &rank);
    MPI_Comm_size(comm, &nproc);

    /* output: the coordinates of the cluster centres ----------------------*/
    /* only proc 0 matters this, because clusters[] are the same across all proc */

    /* to save the results in a new netCDF file */
    if (save_in_new_file) {
        if (strcasecmp(filename+strlen(filename)-3, ".nc") == 0) {
            strcpy(outFileName, filename);
            outFileName[strlen(filename)-3] = '\0';
            strcat(outFileName, ".cluster_centres.nc");
        }
        else
            sprintf(outFileName, "%s.cluster_centres.nc", filename);

        if (rank == 0 && verbose) {
            printf("Writing coordinates of K=%d cluster centers to file \"%s\"\n",
                   numClusters, outFileName);

            printf("Writing membership of N=%d data objects to file \"%s\"\n",
                   totalNumObjs, outFileName);
        }

        /* Create the file. The NC_CLOBBER parameter tells netCDF to
         * overwrite this file, if it already exists.*/
        if ((retval = ncmpi_create(comm, outFileName, NC_CLOBBER | NC_64BIT_OFFSET, MPI_INFO_NULL, &ncid)))
            ERR2(retval);

        /* Define the dimensions. NetCDF will hand back an ID for each. */
        if ((retval = ncmpi_def_dim(ncid, "num_clusters", numClusters, &dimids[0])))
            ERR2(retval);

        if ((retval = ncmpi_def_dim(ncid, "num_coordinates", numCoords, &dimids[1])))
            ERR2(retval);

        if ((retval = ncmpi_def_dim(ncid, "num_elements", totalNumObjs, &dim_num_obj)))
            ERR2(retval);

        /* Define the clusters variable. The type of the variable in this case is
         * NC_FLOAT (4-byte float). */
        if ((retval = ncmpi_def_var(ncid, "clusters", NC_FLOAT, 2, dimids, &clusters_varid)))
            ERR2(retval);

        /* Define the membership variable. The type of the variable in this case is
         * NC_INT (4-byte integer). */
        if ((retval = ncmpi_def_var(ncid, "membership", NC_INT, 1, &dim_num_obj, &membership_varid)))
            ERR2(retval);

        /* End define mode. This tells netCDF we are done defining
         * metadata. */
        if ((retval = ncmpi_enddef(ncid)))
            ERR2(retval);
    }
    else { /* add new variables into existing netCDF file */
    }

    /* write cluster centers */
    if ((retval = ncmpi_put_var_float_all(ncid, clusters_varid, *clusters)))
        ERR2(retval);

    /* write membership variable */
    divd  = totalNumObjs / nproc;
    rem   = totalNumObjs % nproc;
    start = (rank < rem) ? rank*(divd+1) : rank*divd + rem;
    count = numObjs;
    if (_debug) printf("%2d: start=%lld count=%lld\n",rank,start,count);

    if ((retval = ncmpi_put_vara_int_all(ncid, membership_varid, &start, &count, membership)))
        ERR2(retval);

   /* Close the file. This frees up any internal netCDF resources
    * associated with the file, and flushes any buffers. */
   if ((retval = ncmpi_close(ncid)))
      ERR2(retval);

    return 1;
}
Example #24
0
static A_Err
CheckForPaintStreams(
	AEGP_LayerH			layerH,						/* >> */
	AEGP_StreamRefH		*stroke_group_streamPH)		/* << */
{
	A_Err 				err 						= A_Err_NONE, 
						err2 						= A_Err_NONE;

	A_Boolean			paint_foundB				= FALSE;
	
	A_long				num_strokesL			 	= 0;

	AEGP_StreamRefH		layer_base_streamH			= NULL,
						effects_streamH				= NULL,
						paint_streamH				= NULL;

	AEGP_StreamGroupingType	group_type				= AEGP_StreamGroupingType_NONE;

	AEGP_SuiteHandler	suites(sP);
	AEGP_ErrReportState	err_state;

	if (layerH){
		ERR(suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefForLayer(	S_my_id, layerH, &layer_base_streamH));
		ERR(suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefByMatchname(	S_my_id,
																			layer_base_streamH,
																			"ADBE Effect Parade", 
																			&effects_streamH));
		ERR(suites.DynamicStreamSuite2()->AEGP_GetStreamGroupingType(effects_streamH, &group_type));

		if (group_type == AEGP_StreamGroupingType_INDEXED_GROUP){
			ERR(suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefByIndex(	S_my_id,
																			effects_streamH,
																			0, 
																			&paint_streamH));

			//	I'm quieting errors here, as AEGP_GetNewStreamRefByMatchname
			//	will complain if there aren't any paint strokes. 
			ERR(suites.UtilitySuite3()->AEGP_StartQuietErrors(&err_state));
			//	We don't check for errors, since it is not a problem if there are no paint strokes (thanks jwfearn)
			suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefByMatchname(	S_my_id,
																			paint_streamH,
																			"ADBE Paint Group", 
																			stroke_group_streamPH);
			ERR(suites.UtilitySuite3()->AEGP_EndQuietErrors(false, &err_state));

			if (*stroke_group_streamPH){
				ERR(suites.DynamicStreamSuite2()->AEGP_GetNumStreamsInGroup(*stroke_group_streamPH, &num_strokesL));
				if (!err && num_strokesL){
					paint_foundB = TRUE;
				}
			}
		}
	}
	if (layer_base_streamH){
		ERR2(suites.StreamSuite2()->AEGP_DisposeStream(layer_base_streamH));
	}
	if (effects_streamH){
		ERR2(suites.StreamSuite2()->AEGP_DisposeStream(effects_streamH));
	}
	if (paint_streamH){
		ERR2(suites.StreamSuite2()->AEGP_DisposeStream(paint_streamH));
	}	
	return err;
}		
Example #25
0
/* write */
static void fifo_write(ubx_block_t *i, ubx_data_t* msg)
{
	int ret;
	long len, empty, len2=0;
	struct fifo_block_info *bbi;

	bbi = (struct fifo_block_info*) i->private_data;

	if((ret=pthread_mutex_lock(&bbi->mutex))!=0) {
		ERR2(ret, "failed to lock mutex");
		goto out;
	}

	len = data_size(msg);

	if (len > bbi->size) {
		ERR("can't store %ld bytes of data in a %ld size buffer", len, bbi->size);
		goto out_unlock;
	}

	/* remember type, this should better happen in preconnect-hook. */
	if(bbi->type==NULL) {
		DBG("SETTING type to msg->type = %p, %s", msg->type, msg->type->name);
		bbi->type=msg->type;
	}

	/* enough space?
	 * TODO: continue here:
	 *  - add an overrun policy: 'drop' or 'overwrite'
	 */
	empty = empty_space(bbi);

	if(empty < len) {
		bbi->overruns++;

		if(bbi->overrun_policy==DROP_NEW) {
			DBG("fifo overrun (#%ld), dropping new data.", bbi->overruns);
			goto out_unlock;
		} else if(bbi->overrun_policy==DROP_OLD) {
			/* fake a read of len and deal with wrapping */
			bbi->rdptr+=len;
			if(bbi->rdptr > bbi->buff+bbi->size)
				bbi->rdptr-=bbi->size;
			DBG("fifo overrun (#%ld), dropping old data.", bbi->overruns);
		} else {
			ERR("unknown overrun_policy 0x%x", bbi->overrun_policy);
			goto out_unlock;
		}
	}

	/* once we get here, there is enough free space.
	 * two possible cases:
	 *    1. continous free space available for write of len
	 *    2. non-continous, need to wrap around to write chunk 2.
	 */

	/* compute length of chunk 2 write */
	if(bbi->wrptr > bbi->rdptr) {
		len2 = len - (bbi->buff + bbi->size - bbi->wrptr);
		len2 = (len2>0) ? len2 : 0;
		len = (len2>0) ? len-len2 : len;
	}

	DBG("empty=%ld, len=%ld, len2=%ld\n",empty,len,len2);

	/* chunk 1 */
	memcpy(bbi->wrptr, msg->data, len);
	bbi->wrptr = (bbi->wrptr+len >= bbi->buff+bbi->size) ? bbi->buff : &bbi->wrptr[len];
	

	/* chunk 2 ?*/
	if(len2 > 0) {
		memcpy(bbi->buff, &(((uint8_t*) msg->data)[len]), len2);
		bbi->wrptr=&bbi->buff[len2];
	}



 out_unlock:
	pthread_mutex_unlock(&bbi->mutex);
 out:
	return;
}
Example #26
0
static A_Err
CommandHook(
	AEGP_GlobalRefcon	plugin_refconPV,		/* >> */
	AEGP_CommandRefcon	refconPV,				/* >> */
	AEGP_Command		command,				/* >> */
	AEGP_HookPriority	hook_priority,			/* >> */
	A_Boolean			already_handledB,		/* >> */
	A_Boolean			*handledPB)				/* << */
{
	A_Err 				err 				= A_Err_NONE, 
						err2 				= A_Err_NONE;

	A_long				num_strokesL	 	= 0,
						new_indexL			= 0;
	
	A_char				nameAC[AEGP_MAX_STREAM_MATCH_NAME_SIZE]  = {'\0'};

	AEGP_LayerH 		layerH						= NULL;

	AEGP_StreamRefH		stroke_group_streamH		= NULL,
						stroke_streamH				= NULL;
	

	AEGP_SuiteHandler	suites(sP);
	
	if (command == S_Streamie_cmd) {
		try {
			ERR(suites.UtilitySuite3()->AEGP_StartUndoGroup(STR(StrID_Name)));
			ERR(suites.LayerSuite5()->AEGP_GetActiveLayer(&layerH));
			if (layerH){
				ERR(CheckForPaintStreams(layerH, &stroke_group_streamH));
				if (stroke_group_streamH){
					ERR(suites.DynamicStreamSuite2()->AEGP_GetNumStreamsInGroup(stroke_group_streamH, &num_strokesL));
					if (!err && num_strokesL){
						--num_strokesL;	// the last stream is "paint on transparency", which we don't want -bbb 
						for (A_long iL = 0; !err && iL < num_strokesL; ++iL){
							ERR(suites.DynamicStreamSuite2()->AEGP_GetNewStreamRefByIndex(	S_my_id,
																							stroke_group_streamH,
																							iL, 
																							&stroke_streamH));

							ERR(suites.StreamSuite2()->AEGP_GetStreamName(stroke_streamH, TRUE, nameAC)); // just for fun. 
							ERR(suites.DynamicStreamSuite2()->AEGP_ReorderStream(stroke_streamH, (num_strokesL - iL)));
							if (iL == 2){ // just picking one at random
								ERR(suites.DynamicStreamSuite2()->AEGP_SetStreamName(stroke_streamH, STR(StrID_ChangedName)));
							}
							if (iL == 4){ // just picking another one
								ERR(suites.DynamicStreamSuite2()->AEGP_DuplicateStream(S_my_id, stroke_streamH, &new_indexL));
							}
							if (iL == 3){ //...and another one
								ERR(suites.DynamicStreamSuite2()->AEGP_DeleteStream(stroke_streamH));
							}
						} 
					}		
				}
			}
			if (stroke_streamH){
				ERR2(suites.StreamSuite2()->AEGP_DisposeStream(stroke_streamH));
			}
			if (stroke_group_streamH){
				ERR2(suites.StreamSuite2()->AEGP_DisposeStream(stroke_group_streamH));
			}	
			*handledPB = TRUE;
			ERR2(suites.UtilitySuite3()->AEGP_EndUndoGroup());									
		} catch (A_Err &thrown_err){
			err = thrown_err;
		}	
		if (err) { // not !err, err!
			ERR2(suites.UtilitySuite3()->AEGP_ReportInfo(S_my_id, STR(StrID_Troubles)));
		}
	}
	return err;
}
Example #27
0
int main(int argc, const char **argv) {
  int i, rv;
  pkcs11_handle_t *ph;
  struct configuration_st *configuration;
  unsigned int slot_num = 0;
  cert_object_t **certs;
  int cert_count;

  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc - 1, argv + 1);
  if (!configuration ) {
	ERR("Error setting configuration parameters");
	return 1;
  }

  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return 1;
  }

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    DBG1("crypto_init() failed: %s", get_error());
    return 1;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    ERR2("load_pkcs11_module(%s) failed: %s", configuration->pkcs11_modulepath,
      get_error());
    return 1;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG1("init_pkcs11_module() failed: %s", get_error());
    return 1;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel(ph, configuration->slot_description, &slot_num);
  } else {
    rv = find_slot_by_number(ph, configuration->slot_num, &slot_num);
  }

  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG("no token available");
    return 1;
  }

  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("open_pkcs11_session() failed: %s", get_error());
    return 1;
  }

  /* not really needed, but.... */
  rv = pkcs11_pass_login(ph,configuration->nullok);
  if (rv != 0) {
    ERR1("pkcs11_pass_login() failed: %s", get_error());
    return 2;
  }

  /* get certificate list (cert space is owned by ph) */
  certs = get_certificate_list(ph, &cert_count);
  if (certs == NULL) {
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    ERR1("get_certificates() failed: %s", get_error());
    return 3;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find valid certificates and look for contents */
  DBG1("Found '%d' certificate(s)", cert_count);
  for (i = 0; i < cert_count; i++) {
    X509 *x509 = get_X509_certificate(certs[i]);
    if (x509 != NULL) {
      DBG1("verifying the certificate #%d", i + 1);
      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509, &configuration->policy);
      if (rv < 0) {
        close_pkcs11_session(ph);
        release_pkcs11_module(ph);
	unload_mappers();
        ERR1("verify_certificate() failed: %s", get_error());
        return 1;
      } else if (rv != 1) {
        ERR1("verify_certificate() failed: %s", get_error());
        continue;
      }

      DBG1("Inspecting certificate #%d",i+1);
      inspect_certificate(x509);
    }
  }

  /* unload mappers */
  unload_mappers();

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("close_pkcs11_session() failed: %s", get_error());
    return 1;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("Process completed");
  return 0;
}
Example #28
0
static PF_Err 
Render(	
	PF_InData		*in_data,
	PF_OutData		*out_data,
	PF_ParamDef		*params[],
	PF_LayerDef		*output )
{
	PF_Err				err 			= PF_Err_NONE,
						err2 			= PF_Err_NONE;
	int32_t				num_channelsL 	= 0;
	PF_Rect				halfsies		= {0,0,0,0};
	PF_ParamDef			checkout; 
	PF_ChannelSuite1	*csP			= NULL;
	PF_ChannelDesc		desc;
	PF_ChannelRef		ref;
	PF_ChannelChunk		chunk;
	PF_Boolean			found_depthPB;
	
	AEFX_CLR_STRUCT(checkout);
	
	// Premiere Pro/Elements does not support this suite
	if (in_data->appl_id != 'PrMr')
	{
		ERR(AEFX_AcquireSuite(	in_data, 
									out_data, 
									kPFChannelSuite1, 
									kPFChannelSuiteVersion1, 
									"Couldn't load suite.",
									(void**)&csP));
								
		ERR(csP->PF_GetLayerChannelCount(	in_data->effect_ref, 
											 0, 
											 &num_channelsL));
												 

		if(num_channelsL) {
			ERR(csP->PF_GetLayerChannelTypedRefAndDesc(	in_data->effect_ref,
														0,	
														PF_ChannelType_DEPTH,		
														&found_depthPB,		
														&ref,	
														&desc)); 

			ERR(csP->PF_CheckoutLayerChannel(	in_data->effect_ref,
												&ref,
												in_data->current_time,
												in_data->time_step,			
												in_data->time_scale,			
												desc.data_type,			
												&chunk));
												
			// do interesting 3d stuff here;
			
			ERR(csP->PF_CheckinLayerChannel(in_data->effect_ref,
											&ref,
											&chunk));
		}

		ERR2(AEFX_ReleaseSuite(	in_data, 
								out_data, 
								kPFChannelSuite1, 
								kPFChannelSuiteVersion1,
								"Couldn't release suite."));
	}

	// set the checked-out rect to be the top half of the layer 
	
	halfsies.top	= halfsies.left	= 0;
	halfsies.right	= (short)output->width;
	halfsies.bottom	= (short)(output->height / 2);
	
	ERR(PF_CHECKOUT_PARAM(	in_data, 
							CHECK_LAYER,
							(in_data->current_time + params[CHECK_FRAME]->u.sd.value * in_data->time_step), 
							in_data->time_step,
							in_data->time_scale, 
							&checkout));
							
	if (!err) {
		if (checkout.u.ld.data)  {
			ERR(PF_COPY(&checkout.u.ld, 
						output, 
						NULL, 
						&halfsies));
		}  else  {
			// no layer? Zero-alpha black.
			ERR(PF_FILL(NULL, &halfsies, output));		
		}
	
		if (!err)  {
			halfsies.top		= halfsies.bottom;				//reset rect, copy.
			halfsies.bottom 	= (short)output->height;

			ERR(PF_COPY(&params[CHECK_INPUT]->u.ld, 
						output, 
						NULL, 
						&halfsies));
		}
	}

	ERR2(PF_CHECKIN_PARAM(in_data, &checkout));		// ALWAYS check in,
													// even if invalid param.
	return err;
}
Example #29
0
static PF_Err 
Render (
	PF_InData		*in_data,
	PF_OutData		*out_data,
	PF_ParamDef		*params[],
	PF_LayerDef		*output )
{
	AEGP_SuiteHandler	suites(in_data->pica_basicP);

	PF_Err				err		= 	PF_Err_NONE,	
						err2	=	PF_Err_NONE;	
						
	PF_Pixel16			bigpix	=	{0,0,0,0};

	A_long				widthL	=	output->width,
						heightL	=	output->height;
	
	PF_NewWorldFlags	flags	=	PF_NewWorldFlag_CLEAR_PIXELS;
	
	PF_EffectWorld		color_world;
	
	PF_Boolean			deepB			=	PF_WORLD_IS_DEEP(output),
						two_sourcesB	=	FALSE;
	
	PF_ParamDef			temp_param;
	
	AEFX_CLR_STRUCT(temp_param);	
	AEFX_CLR_STRUCT(color_world);	
	
	/*	We're going to blend the input with the color. If 
		the user has picked an additional layer, we'll blend 
		it in too, giving it a 'special' look along the way.	
	*/
	
	if (PF_Quality_HI == in_data->quality) {
		ERR(suites.WorldTransformSuite1()->copy_hq(	in_data->effect_ref,
													&params[XFORM_INPUT]->u.ld,
													output,
													&params[XFORM_INPUT]->u.ld.extent_hint,
													&output->extent_hint));
	} else {
		ERR(suites.WorldTransformSuite1()->copy(	in_data->effect_ref,
													&params[XFORM_INPUT]->u.ld,
													output,
													&params[XFORM_INPUT]->u.ld.extent_hint,
													&output->extent_hint));
	}	
	
	ERR(PF_ABORT(in_data));

	/*	Make an offscreen world. If the user has selected an
		extra input layer, we'll size to that (so we can use
		the blend callback, which requires input PF_Worlds of 
		the same dimensions), of the appropriate pixel depth.	
	*/
	
	if (deepB) {
		flags	|=	PF_NewWorldFlag_DEEP_PIXELS;
	}
	
	ERR(PF_CHECKOUT_PARAM(	in_data,
							XFORM_LAYER,
							in_data->current_time,
							in_data->time_step,
							in_data->time_scale,
							&temp_param));
	ERR(PF_ABORT(in_data));
	
	if (!err) {
		if (temp_param.u.ld.data) {
			two_sourcesB	=	TRUE;
			widthL			=	temp_param.u.ld.width;
			heightL			=	temp_param.u.ld.height;		
		} else {
			widthL	=	output->width;
			heightL	=	output->height;
		}

		ERR(suites.WorldSuite1()->new_world(	in_data->effect_ref,
												widthL,
												heightL,
												flags,
												&color_world));

		ERR(PF_ABORT(in_data));
	
		if (deepB) {
			ERR(Copy8BitPixelTo16BitPixel(&params[XFORM_COLOR]->u.cd.value, &bigpix));

			ERR(suites.FillMatteSuite2()->fill16(in_data->effect_ref,
												&bigpix,
												NULL,
												&color_world));
		} else {
			ERR(suites.FillMatteSuite2()->fill(	in_data->effect_ref,
												&params[XFORM_COLOR]->u.cd.value,
												NULL,
												&color_world));
		}

		ERR(PF_ABORT(in_data));


		if (two_sourcesB) {

			ERR(suites.WorldTransformSuite1()->blend(in_data->effect_ref,
													&temp_param.u.ld,
													&color_world,
													params[XFORM_LAYERBLEND]->u.fd.value,
													&color_world));
		} else 	{
			ERR(suites.WorldTransformSuite1()->blend(in_data->effect_ref,
													&params[XFORM_INPUT]->u.ld,
													&color_world,
													params[XFORM_COLORBLEND]->u.fd.value,
													output));
		}

		ERR(PF_ABORT(in_data));

		if (!err) {		

			//	Blend the color layer () with the output	

			PF_CompositeMode	mode;
			
			AEFX_CLR_STRUCT(mode);
			
			mode.xfer		=	PF_Xfer_DIFFERENCE;
			mode.opacity	=	static_cast<A_u_char>(FIX2INT_ROUND(params[XFORM_LAYERBLEND]->u.fd.value / PF_MAX_CHAN8));
			mode.rgb_only	=	TRUE;

			PF_FpLong			opacityF	= FIX_2_FLOAT(params[XFORM_LAYERBLEND]->u.fd.value);

			mode.opacity	= static_cast<A_u_char>((opacityF 	* PF_MAX_CHAN8) 	+ 0.5);
			mode.opacitySu	= static_cast<A_u_short>((opacityF 	* PF_MAX_CHAN16) 	+ 0.5);

				if (mode.opacitySu 	> PF_MAX_CHAN16) {
				mode.opacitySu 	= PF_MAX_CHAN16;
			}

			ERR(suites.WorldTransformSuite1()->transfer_rect(in_data->effect_ref,
															in_data->quality,
															PF_MF_Alpha_STRAIGHT,
															in_data->field,
															&color_world.extent_hint,
															&color_world,
															&mode,
															NULL,
															(A_long)suites.ANSICallbacksSuite1()->fabs(output->extent_hint.right 	- color_world.extent_hint.right ) / 2,
															(A_long)suites.ANSICallbacksSuite1()->fabs(output->extent_hint.bottom - color_world.extent_hint.bottom ) / 2,
															output));
		}
	}		
	
	ERR(PF_ABORT(in_data));
	ERR2(suites.WorldSuite1()->dispose_world(in_data->effect_ref, &color_world));
	ERR2(PF_CHECKIN_PARAM(in_data, &temp_param));
													
	return err;
	
}