Exemplo n.º 1
0
void InitScanner(string line)
	{
	buffer = line;
	buflen = StringLength(buffer);
	cpos = 0;
	}
Exemplo n.º 2
0
void BuildFileFullPath(State *state, char *fileName, char *dest, int destSize)
{
	CatStrings(state->DLLFilePath, state->OnePastLastSlash - state->DLLFilePath, fileName, StringLength(fileName), dest, destSize);
}
Exemplo n.º 3
0
static int
p_substring(value val1, type tag1, value val2, type tag2, value valp, type tagp)
{
	char	*p1, *p2;
	word	length1, length2;
	word	i, j;

        /* string1 and string2 must be strings; posn an integer/variable. */ 

	Check_Output_Integer(tagp);
        Check_Output_String(tag1);
        Check_String(tag2);
	Error_If_Ref(tag1);

	length1 = StringLength(val1);
	length2 = StringLength(val2);

	if (!IsRef(tagp))
	{
		if (valp.nint <= 0 || valp.nint > length1 + 1)
		{
		    Bip_Error(RANGE_ERROR);
		}
		if (valp.nint > length1 - length2 + 1)
		{
		    Fail_;	/* string 2 is too long to match */
		}

		p1 = StringStart(val1) + valp.nint - 1;
		p2 = StringStart(val2);
		for(j = 0; j < length2; ++j)
		{
		    if (p1[j] != p2[j])
		    {
			Fail_;
		    }
		}
		Succeed_;
	}
	else
	{
		p1 = StringStart(val1);
		p2 = StringStart(val2);
		for (i = 1; i <= length1 - length2 + 1; i++)
		{
			/*
	         	 * search through p (i.e. string1) 'length2' characters
		 	 * at a time for val2.str (i.e. string2), till the end
		 	 * of string1. 
			 */ 
			for(j = 0; j < length2; ++j)
			{
			    if (p1[j] != p2[j])
				break;
			}
			if (j == length2)
			{
			    Return_Unify_Integer(valp, tagp, i);
			}
			p1++;
		}
		/* if not found, fail. */	
		Fail_;
	}	
}
Exemplo n.º 4
0
gcc_pure
static inline bool
StringStartsWith(const TCHAR *haystack, const TCHAR *needle)
{
  return memcmp(haystack, needle, StringLength(needle) * sizeof(needle[0])) == 0;
}
Exemplo n.º 5
0
Arquivo: z29.c Projeto: thektulu/lout
OBJECT InsertSym(FULL_CHAR *str, unsigned char xtype, FILE_POS *xfpos,
unsigned char xprecedence, BOOLEAN xindefinite, BOOLEAN xrecursive,
unsigned xpredefined, OBJECT xenclosing, OBJECT xbody)
{ register int sum, rlen;
  register unsigned char *x;
  OBJECT p, q, s, tmp, link, entry, plink;  int len;

  debug3(DST, DD, "InsertSym( %s, %s, in %s )",
	Image(xtype), str, SymName(xenclosing));
  if( !LexLegalName(str) )
    Error(29, 3, "invalid symbol name %s", WARN, xfpos, str);

  New(s, xtype);
  FposCopy(fpos(s), *xfpos);
  has_body(s)          = FALSE;
  filter(s)            = nilobj;
  use_invocation(s)    = nilobj;
  imports(s)           = nilobj;
  imports_encl(s)      = FALSE;
  right_assoc(s)       = TRUE;
  precedence(s)        = xprecedence;
  indefinite(s)        = xindefinite;
  recursive(s)         = xrecursive;
  predefined(s)        = xpredefined;
  enclosing(s)         = xenclosing;
  sym_body(s)          = xbody;
  base_uses(s)         = nilobj;
  uses(s)              = nilobj;
  marker(s)            = nilobj;
  cross_sym(s)         = nilobj;
  is_extern_target(s)  = FALSE;
  uses_extern_target(s)= FALSE;
  visible(s)           = FALSE;
  uses_galley(s)       = FALSE;
  horiz_galley(s)      = ROWM;
  has_compulsory(s)    = 0;
  is_compulsory(s)     = FALSE;

  uses_count(s)  = 0;
  dirty(s)       = FALSE;
  if( enclosing(s) != nilobj && type(enclosing(s)) == NPAR )
    dirty(s) = dirty(enclosing(s)) = TRUE;

  has_par(s)     = FALSE;
  has_lpar(s)    = FALSE;
  has_rpar(s)    = FALSE;
  if( is_par(type(s)) )  has_par(enclosing(s))  = TRUE;
  if( type(s) == LPAR )  has_lpar(enclosing(s)) = TRUE;
  if( type(s) == RPAR )  has_rpar(enclosing(s)) = TRUE;

  /* assign a code letter between a and z to any NPAR symbol */
  if( type(s) == NPAR )
  { if( LastDown(enclosing(s)) != enclosing(s) )
    { Child(tmp, LastDown(enclosing(s)));
      if( type(tmp) == NPAR )
      { if( npar_code(tmp) == 'z' || npar_code(tmp) == ' ' )
	  npar_code(s) = ' ';
	else
	  npar_code(s) = npar_code(tmp)+1;
      }
      else
	npar_code(s) = 'a';
    }
    else npar_code(s) = 'a';
  }

  has_target(s)  = FALSE;
  force_target(s) = FALSE;
  if( !StringEqual(str, KW_TARGET) ) is_target(s) = FALSE;
  else
  { is_target(s) = has_target(enclosing(s)) = TRUE;

    /* if @Target is found after @Key, take note of external target */
    if( has_key(enclosing(s)) && xbody != nilobj && is_cross(type(xbody)) )
    { if( LastDown(xbody) != Down(xbody) )
      { OBJECT sym;
	Child(sym, Down(xbody));
	if( type(sym) == CLOSURE )
	{ is_extern_target(actual(sym)) = TRUE;
	  uses_extern_target(actual(sym)) = TRUE;
	}
      }
    }
  }

  has_tag(s) = is_tag(s) = FALSE;
  has_key(s) = is_key(s) = FALSE;
  has_optimize(s) = is_optimize(s) = FALSE;
  has_merge(s) = is_merge(s) = FALSE;
  has_enclose(s) = is_enclose(s) = FALSE;
  if( enclosing(s) != nilobj && type(enclosing(s)) == LOCAL )
  {
    if( StringEqual(str, KW_TAG) )
      is_tag(s) = has_tag(enclosing(s)) = dirty(enclosing(s)) = TRUE;

    if( StringEqual(str, KW_OPTIMIZE) )
      is_optimize(s) = has_optimize(enclosing(s)) = TRUE;

    if( StringEqual(str, KW_KEY) )
    { is_key(s) = has_key(enclosing(s)) = dirty(enclosing(s)) = TRUE;

      /* if @Key is found after @Target, take note of external target */
      for( link=Down(enclosing(s));  link!=enclosing(s);  link=NextDown(link) )
      { Child(p, link);
	if( is_target(p) && sym_body(p)!=nilobj && is_cross(type(sym_body(p))) )
	{ OBJECT sym;
	  Child(sym, Down(sym_body(p)));
	  if( type(sym) == CLOSURE )
	  { is_extern_target(actual(sym)) = TRUE;
	    uses_extern_target(actual(sym)) = TRUE;
	  }
	}
      }
    } 

    if( StringEqual(str, KW_MERGE) )
      is_merge(s) = has_merge(enclosing(s)) = TRUE;

    if( StringEqual(str, KW_ENCLOSE) )
      is_enclose(s) = has_enclose(enclosing(s)) = TRUE;
  }

  if( StringEqual(str, KW_FILTER) )
  { if( type(s) != LOCAL || enclosing(s) == StartSym )
      Error(29, 4, "%s must be a local definition", WARN, &fpos(s), str);
    else if( !has_rpar(enclosing(s)) )
      Error(29, 14, "%s must lie within a symbol with a right parameter",
	WARN, &fpos(s), KW_FILTER);
    else
    { filter(enclosing(s)) = s;
      precedence(enclosing(s)) = FILTER_PREC;
    }
  }

  if( type(s) == RPAR && has_body(enclosing(s)) &&
    (is_tag(s) || is_key(s) || is_optimize(s)) )
    Error(29, 5, "a body parameter may not be named %s", WARN, &fpos(s), str);

  if( type(s) == RPAR && has_target(enclosing(s)) &&
    (is_tag(s) || is_key(s) || is_optimize(s)) )
    Error(29, 6, "the right parameter of a galley may not be called %s",
      WARN, &fpos(s), str);

  len = StringLength(str);
  hash(str, len, sum);

  ifdebug(DST, D, sym_spread[sum]++;  sym_count++);
  entry = (OBJECT) &symtab[sum];
  for( plink = Down(entry);  plink != entry;  plink = NextDown(plink) )
  { Child(p, plink);
    if( length(p) == len && StringEqual(str, string(p)) )
    { for( link = Down(p);  link != p;  link = NextDown(link) )
      {	Child(q, link);
	if( enclosing(s) == enclosing(q) )
	{ Error(29, 7, "symbol %s previously defined at%s",
	    WARN, &fpos(s), str, EchoFilePos(&fpos(q)) );
	  if( AltErrorFormat )
	  {
	    Error(29, 13, "symbol %s previously defined here",
	      WARN, &fpos(q), str);
	  }
	  break;
	}
      }
      goto wrapup;
    }
  }

  /* need a new OBJECT as well as s */
  NewWord(p, WORD, len, xfpos);
  length(p) = len;
  StringCopy(string(p), str);
  Link(entry, p);

 wrapup:
  Link(p, s);
  if( enclosing(s) != nilobj ) Link(enclosing(s), s);
  debug2(DST, DD, "InsertSym Link(%s, %s) and returning.",
		SymName(enclosing(s)), SymName(s));
  return s;
} /* end InsertSym */
Exemplo n.º 6
0
 void SetASCII(const char *src) {
   SetASCII(src, src + StringLength(src));
 }
Exemplo n.º 7
0
 size_type length() const {
   return StringLength(data);
 }
Exemplo n.º 8
0
Arquivo: z05.c Projeto: thektulu/lout
void ReadDefinitions(OBJECT *token, OBJECT encl, unsigned char res_type)
{ OBJECT t, res, res_target, export_list, import_list, link, y, z;
  OBJECT curr_encl;  BOOLEAN compulsory_par, has_import_encl;
  t = *token;

  while( res_type==LOCAL || is_string(t, KW_NAMED) || is_string(t, KW_IMPORT) )
  {
    curr_encl = encl;

    if( is_string(t, KW_LANGDEF) )
    { ReadLangDef(encl);
      t = LexGetToken();
      continue;  /* next definition */
    }
    else if( type(t) == PREPEND || type(t) == SYS_PREPEND )
    { ReadPrependDef(type(t), encl);
      Dispose(t);
      t = LexGetToken();
      continue;  /* next definition */
    }
    else if( type(t) == INCG_REPEATED || type(t) == SINCG_REPEATED )
    { ReadIncGRepeatedDef(type(t), encl);
      Dispose(t);
      t = LexGetToken();
      continue;  /* next definition */
    }
    else if( type(t) == DATABASE || type(t) == SYS_DATABASE )
    { ReadDatabaseDef(type(t), encl);
      Dispose(t);
      t = LexGetToken();
      continue;  /* next definition */
    }

    if( !is_string(t, KW_DEF)    && !is_string(t, KW_MACRO)  &&
	!is_string(t, KW_NAMED)  && !is_string(t, KW_IMPORT) &&
        !is_string(t, KW_EXTEND) && !is_string(t, KW_EXPORT) )
      break;

    /* get import or extend list and change scope appropriately */
    BodyParNotAllowed();
    New(import_list, ACAT);
    has_import_encl = FALSE;
    if( is_string(t, KW_IMPORT) )
    { Dispose(t);
      t = LexGetToken();
      while( type(t) == CLOSURE ||
	       (type(t)==WORD && !is_string(t,KW_EXPORT) && !is_string(t,KW_DEF)
	       && !is_string(t, KW_MACRO) && !is_string(t, KW_NAMED)) )
      {	if( type(t) == CLOSURE )
	{ if( type(actual(t)) == LOCAL )
	  {
	    /* *** letting this through now
	    if( res_type == NPAR && has_par(actual(t)) )
	    {
	      Error(5, 46, "named parameter import %s has parameters",
		WARN, &fpos(t), SymName(actual(t)));
	    }
	    else
	    {
	    *** */
	      PushScope(actual(t), FALSE, TRUE);
	      if( actual(t) == encl )  has_import_encl = TRUE;
	      Link(import_list, t);
	    /* ***
	    }
	    *** */
	  }
	  else
	  { Error(5, 26, "import name expected here", WARN, &fpos(t));
	    Dispose(t);
	  }
	}
	else
	{ Error(5, 27, "import %s not in scope", WARN, &fpos(t), string(t));
	  Dispose(t);
	}
	t = LexGetToken();
      }
    }
    else if( is_string(t, KW_EXTEND) )
    { Dispose(t);
      t = LexGetToken();
      while( type(t) == CLOSURE ||
	       (type(t)==WORD && !is_string(t,KW_EXPORT) && !is_string(t,KW_DEF)
	       && !is_string(t, KW_MACRO)) )
      {	if( type(t) == CLOSURE )
	{ if( imports(actual(t)) != nilobj )
	  { Error(5, 48, "%s has %s clause, so cannot be extended",
	      WARN, &fpos(t), SymName(actual(t)), KW_IMPORT);
	  }
	  else if( type(actual(t)) == LOCAL )
	  { PushScope(actual(t), FALSE, FALSE);
	    curr_encl = actual(t);
            debug1(DRD, D, "  curr_encl = %s", SymName(curr_encl));
	    Link(import_list, t);
	  }
	  else
	  { Error(5, 28, "%s symbol name expected here",
	      WARN, &fpos(t), KW_EXTEND);
	    Dispose(t);
	  }
	}
	else
	{ Error(5, 29, "extend symbol %s not in scope", WARN,&fpos(t),string(t));
	  Dispose(t);
	}
	t = LexGetToken();
      }
    }

    /* get export list and store for setting visible flags below */
    New(export_list, ACAT);
    if( is_string(t, KW_EXPORT) )
    { Dispose(t);
      SuppressScope();
      t = LexGetToken();
      while( is_word(type(t)) && !is_string(t, KW_DEF) && !is_string(t, KW_IMPORT)
	&& !is_string(t, KW_MACRO) && !is_string(t, KW_EXTEND) )
      { Link(export_list, t);
	t = LexGetToken();
      }
      UnSuppressScope();
    }


    if( res_type == LOCAL && !is_string(t, KW_DEF) && !is_string(t, KW_MACRO) )
    { Error(5, 30, "keyword %s or %s expected here", WARN, &fpos(t),
	KW_DEF, KW_MACRO);
      break;
    }
    if( res_type == NPAR && !is_string(t, KW_NAMED) )
    { Error(5, 31, "keyword %s expected here", WARN, &fpos(t), KW_NAMED);
      break;
    }

    if( is_string(t, KW_MACRO) )
    { if( Down(export_list) != export_list )
	Error(5, 32, "ignoring export list of macro", WARN, &fpos(t));
      res = ReadMacro(&t, curr_encl, encl);
    }
    else
    {
      SuppressScope();  Dispose(t);  t = LexGetToken();

      /* check for compulsory keyword */
      if( res_type == NPAR && is_string(t, KW_COMPULSORY) )
      { compulsory_par = TRUE;
	Dispose(t);  t = LexGetToken();
      }
      else compulsory_par = FALSE;

      /* find name of symbol and insert it */
      if( !is_word(type(t)) )
      { Error(5, 33, "symbol name expected here", WARN, &fpos(t));
	debug1(ANY, D, "offending type is %s", Image(type(t)));
	UnSuppressScope();
	*token = t;
	return;
      }
      res = InsertSym(string(t), res_type, &fpos(t), DEFAULT_PREC,
		FALSE, FALSE, 0, curr_encl, nilobj);
      if( curr_encl != encl )  visible(res) = TRUE;
      if( has_import_encl )
      {
	imports_encl(res) = TRUE;
	debug1(DCE, D, "  setting import_encl(%s) to TRUE", SymName(res));
      }
      if( compulsory_par )
      { has_compulsory(encl)++;
	is_compulsory(res) = TRUE;
      }
      Dispose(t);  t = LexGetToken();

      /* find alternative names for this symbol */
      while( is_word(type(t)) && !is_string(t, KW_NAMED) &&
	!is_string(t, KW_IMPORT) &&
	!is_string(t, KW_FORCE) && !is_string(t, KW_INTO) &&
	!is_string(t, KW_HORIZ) && !is_string(t, KW_PRECEDENCE) &&
	!is_string(t, KW_ASSOC) && !is_string(t, KW_LEFT) &&
	!is_string(t, KW_RIGHT) && !is_string(t, KW_BODY) &&
	!is_string(t, KW_LBR) && !is_string(t, KW_BEGIN) )
      {
	InsertAlternativeName(string(t), res, &fpos(t));
	Dispose(t);  t = LexGetToken();
      }

      /* find force, if any */
      if( is_string(t, KW_FORCE) )
      {	force_target(res) = TRUE;
	Dispose(t);  t = LexGetToken();
	if( !is_string(t, KW_INTO) && !is_string(t, KW_HORIZ) )
	   Error(5, 34, "%s expected here", WARN, &fpos(t), KW_INTO);
      }
	
      /* find horizontally, if any */
      if( is_string(t, KW_HORIZ) )
      { horiz_galley(res) = COLM;
	Dispose(t);  t = LexGetToken();
	/* *** want to allow KW_HORIZ with @Target form now
	if( !is_string(t, KW_INTO) )
	  Error(5, 35, "%s expected here", WARN, &fpos(t), KW_INTO);
	*** */
      }

      /* find into clause, if any */
      res_target = nilobj;
      if( is_string(t, KW_INTO) )
      { UnSuppressScope();
	Dispose(t);  t = LexGetToken();
	if( type(t) != LBR )
	{ Error(5, 36, "%s expected here", WARN, &fpos(t), KW_LBR);
	  debug1(ANY, D, "offending type is %s", Image(type(t)));
	  UnSuppressScope();
	  *token = t;
	  return;
	}
	res_target = Parse(&t, curr_encl, FALSE, FALSE);
	SuppressScope();
	if( t == nilobj )  t = LexGetToken();
      }

      /* find precedence clause, if any */
      if( is_string(t, KW_PRECEDENCE) )
      {	int prec = 0;
	UnSuppressScope();
	Dispose(t);
	t = LexGetToken();
	while( type(t) == WORD && decimaldigit(string(t)[0]) )
	{
	  prec = prec * 10 + digitchartonum(string(t)[0]);
	  Dispose(t);  t = LexGetToken();
	}
	SuppressScope();

	if( prec < MIN_PREC )
	{ Error(5, 37, "precedence is too low (%d substituted)",
	    WARN, &fpos(t), MIN_PREC);
	  prec = MIN_PREC;
	}
	else if( prec > MAX_PREC )
	{ Error(5, 38, "precedence is too high (%d substituted)",
	    WARN, &fpos(t), MAX_PREC);
	  prec = MAX_PREC;
	}
	precedence(res) = prec;
      }

      /* find associativity clause, if any */
      if( is_string(t, KW_ASSOC) )
      {
	UnSuppressScope();
	Dispose(t);  t = LexGetToken();
	if( is_string(t, KW_LEFT) )  right_assoc(res) = FALSE;
	else if( !is_string(t, KW_RIGHT) )
	  Error(5, 39, "associativity altered to %s", WARN, &fpos(t), KW_RIGHT);
	SuppressScope();
	Dispose(t);  t = LexGetToken();
      }

      /* find left parameter, if any */
      if( is_string(t, KW_LEFT) )
      {	Dispose(t);  t = LexGetToken();
	if( type(t) != WORD )
	{ Error(5, 40, "cannot find %s parameter name", WARN, &fpos(t), KW_LEFT);
	  debug1(ANY, D, "offending type is %s", Image(type(t)));
	  UnSuppressScope();
	  *token = t;
	  return;
	}
	InsertSym(string(t), LPAR, &fpos(t), DEFAULT_PREC, 
	  FALSE, FALSE, 0, res, nilobj);
	Dispose(t);  t = LexGetToken();
      }

      /* find named parameters, if any */
      UnSuppressScope();
      ReadDefinitions(&t, res, NPAR);

      /* find right or body parameter, if any */
      if( is_string(t, KW_RIGHT) || is_string(t, KW_BODY) )
      {	has_body(res) = is_string(t, KW_BODY);
	SuppressScope();
	Dispose(t);  t = LexGetToken();
	if( type(t) != WORD )
	{ Error(5, 41, "cannot find %s parameter name", WARN,&fpos(t),KW_RIGHT);
	  debug1(ANY, D, "offending type is %s", Image(type(t)));
	  UnSuppressScope();
	  *token = t;
	  return;
	}
	InsertSym(string(t), RPAR, &fpos(t), DEFAULT_PREC,
	  FALSE, FALSE, 0, res, nilobj);
	UnSuppressScope();
	Dispose(t);  t = LexGetToken();
      }

      /* read local definitions and body */
      if( res_target != nilobj )
	InsertSym(KW_TARGET, LOCAL, &fpos(res_target), DEFAULT_PREC,
			FALSE, FALSE, 0, res, res_target);
      if( type(t) == WORD && StringEqual(string(t), KW_LBR) )
      {	z = NewToken(LBR, &fpos(t), 0, 0, LBR_PREC, StartSym);
	Dispose(t);
	t = z;
      }
      else if( type(t) == WORD && StringEqual(string(t), KW_BEGIN) )
      {	z = NewToken(BEGIN, &fpos(t), 0, 0, BEGIN_PREC, StartSym);
	Dispose(t);
	t = z;
      }
      else if( type(t) != LBR && type(t) != BEGIN )
	Error(5, 42, "opening left brace or @Begin of %s expected",
	  FATAL, &fpos(t), SymName(res));
      if( type(t) == BEGIN )  actual(t) = res;
      PushScope(res, FALSE, FALSE);
      BodyParAllowed();
      sym_body(res) = Parse(&t, res, TRUE, FALSE);

      /* set visible flag of the exported symbols */
      for( link=Down(export_list);  link != export_list;  link=NextDown(link) )
      {	Child(y, link);
	z = SearchSym(string(y), StringLength(string(y)));
	if( z == nilobj || enclosing(z) != res )
	  Error(5, 43, "exported symbol %s is not defined in %s",
	    WARN, &fpos(y), string(y), SymName(res));
	else if( has_body(res) && type(z) == RPAR )
	  Error(5, 44, "body parameter %s may not be exported",
	    WARN, &fpos(y), string(y));
	else if( visible(z) )
	  Error(5, 45, "symbol %s exported twice", WARN, &fpos(y), string(y));
	else visible(z) = TRUE;
      }
      DisposeObject(export_list);

      /* pop scope of res */
      PopScope();
    }

    /* pop import scopes and store imports in sym tab */
    for( link=Down(import_list);  link != import_list;  link=NextDown(link) )
    {
      PopScope();
    }
    if( Down(import_list) == import_list || curr_encl != encl )
    { DisposeObject(import_list);
      import_list = nilobj;
    }
    else
    {
      imports(res) = import_list;
    }

    BodyParAllowed();
    if( t == nilobj ) t = LexGetToken();

  } /* end while */

  *token = t;
  return;
} /* end ReadDefinitions */
Exemplo n.º 9
0
EventStringId EventInternString(const char *label)
{
  AVER(label != NULL);
  return EventInternGenString(StringLength(label), label);
}
Exemplo n.º 10
0
static int _zuluCryptCheckSYSifDeviceIsSystem( const char * device )
{
	/*
	 * UDEV_SUPPORT is set at configure time by "-DUDEVSUPPORT=true" option,the option being absent equals "-DUDEVSUPPORT=false"
	 * To set the option, configure with "-DUDEVSUPPORT=true"
	 */
#if UDEV_SUPPORT
	/*
	 * udev support is enabled
	 */
	int r ;
	size_t e ;
	ssize_t k ;
	string_t xt ;
	string_t st ;
	char dev[ PATH_MAX + 1 ] ;

	const char * path ;

	if( StringPrefixNotEqual( device,"/dev/" ) ){
		/*
		 * udev doesnt work with path to image files so return early
		 */
		return 0 ;
	}

	if( StringPrefixEqual( device,"/dev/loop" ) ){
		/*
		 * udev thinks all loop devices are system devices and we disagree and hence we return early
		 */
		return 0 ;
	}

	path = realpath( device,dev ) ;

	if( path != NULL ){
		st = String( path ) ;
	}else{
		st = String( device ) ;
	}

	if( StringStartsWithAtLeastOne( st,"/dev/sd","/dev/hd",NULL ) ){
		/*
		 * this path will convert something like: "/dev/sdc12" to "/dev/sdc"
		 */
		StringRemoveDigits( st ) ;
	}else if( StringStartsWith( st,"/dev/mmc" ) ){
		/*
		 * device path will be something like "/dev/mmcblk0p2" and what we want to do
		 * is cut off the string from p to end iwth "/dev/mmcblk0"
		 */
		k = StringIndexOfChar( st,0,'p' ) ;
		if( k != -1 ){
			e = StringLength( st ) - ( size_t )k ;
			StringRemoveRight( st,e ) ;
		}
	}

	StringReplaceString( st,"/dev/","/sys/block/" ) ;
	path = StringAppend( st,"/removable" ) ;

	/*
	 * path will be something like "/sys/block/sda/removable"
	 */
	xt = StringGetFromVirtualFile( path ) ;
	StringDelete( &st ) ;
	if( xt == StringVoid ){
		return 0 ;
	}else{
		r = StringEqual( xt,"0\n" ) ;
		StringDelete( &xt ) ;
		return r ;
	}
#else
	if( device ){;}
	/*
	 * udev support is disabled
	 */
	return 0 ;
#endif
}
Exemplo n.º 11
0
static int crypt_opt( const struct_opts * opts,uid_t uid,int opt )
{
	string_t q = StringVoid ;
	string_t p = StringVoid ;

	int st ;

	const char * source	= opts->device ;
	const char * dest  	= opts->m_opts ;
	const char * passphrase = opts->key ;
	const char * type 	= opts->key_source ;

	return zuluExit( 16 ) ;

	if( dest == NULL ){

		return zuluExit( 9 ) ;
	}
	if( source == NULL ){

		return zuluExit( 14 ) ;
	}
	/*
	 * zuluCryptPathStartsWith() is defined in real_path.c
	 */
	if( zuluCryptPathStartsWith( dest,"/dev/" ) ){

		return zuluExit( 10 ) ;
	}
	if( zuluCryptPathStartsWith( source,"/dev/" ) ){

		return zuluExit( 15 ) ;
	}
	/*
	 * zuluCryptPathIsValid() is defined in ../lib/is_path_valid.c
	 */
	if( zuluCryptPathIsValid( dest ) ){

		return zuluExit( 5 ) ;
	}
	/*
	 * zuluCryptPathIsNotValid() is defined in ../lib/is_path_valid.c
	 */
	if( zuluCryptPathIsNotValid( source ) ){

		return zuluExit( 6 ) ;
	}

	/*
	 * below two functions are defined in path_access.c
	 */
	if( zuluCryptCanOpenPathForWriting( dest,uid ) == 1 ){

		return zuluExit( 10 ) ;
	}
	if( zuluCryptCanOpenPathForReading( source,uid ) == 1 ){

		return zuluExit( 15 ) ;
	}
	if( type == NULL ){

		printf( gettext( "Enter passphrase: " ) ) ;
		/*
		 * ZULUCRYPT_KEY_MAX_SIZE is set in ../constants.h
		 */
		switch( StringSilentlyGetFromTerminal_1( &p,ZULUCRYPT_KEY_MAX_SIZE ) ){

			case 1 : return zuluExit( 12 ) ;
			case 2 : return zuluExit( 13 ) ;
		}

		printf( gettext( "\nRe enter passphrase: " ) ) ;

		switch( StringSilentlyGetFromTerminal_1( &q,ZULUCRYPT_KEY_MAX_SIZE ) ){

			case 1 : StringClearDelete( &p ) ;
				 return zuluExit( 12 ) ;
			case 2 : StringClearDelete( &p ) ;
				 return zuluExit( 13 ) ;
		}

		printf( "\n" ) ;

		if( !StringEqualString( p,q ) ){

			StringClearDelete( &p ) ;
			StringClearDelete( &q ) ;

			return zuluExit( 8 ) ;
		}else{
			StringDelete( &q ) ;
		}
	}else{
		if( type == NULL ){

			return zuluExit( 9 ) ;
		}
		if( StringsAreEqual( type,"-p" ) ){

			p = String( passphrase ) ;

		}else if( StringsAreEqual( type,"-f" ) ){

			p = StringGetFromFile( passphrase ) ;

			if( p == NULL ){

				return zuluExit( 2 ) ;
			}
		}else{
			return zuluExit( 3 ) ;
		}
	}

	if( opt == ENCRYPT ){
		/*
		 * zuluCryptEncryptFile() is defined in ./crypt_file.c
		 */
		st = zuluCryptEncryptFile( source,dest,StringContent( p ),StringLength( p ) ) ;
	}else{
		/*
		 * zuluCryptDecryptFile() is defined in ./crypt_file.c
		 */
		st = zuluCryptDecryptFile( source,dest,StringContent( p ),StringLength( p ) ) ;
	}

	StringClearDelete( &p ) ;

	switch( st ){

		case 1 : return zuluExit( 4 ) ;
		case 2 : return zuluExit( 11 ) ;
	}

	_ignore_result( chmod( dest,S_IRUSR | S_IWUSR ) ) ;
	_ignore_result( chown( dest,uid,uid ) ) ;

	if( opt == 1 ){

		return zuluExit( 1 ) ;
	}else{
		return zuluExit( 0 ) ;
	}
}
Exemplo n.º 12
0
LINE *ReadLines(FILE *fp, FULL_CHAR *fname, FULL_CHAR *first_line, int *len)
{
    char *buff;				/* the current input line buffer     */
    char *buff_top;			/* first spot off end of buffer      */
    char *bp;				/* first free spot in buff           */

    LINE *lines;				/* the array of pointers to lines    */
    int  lines_length;			/* the length of the lines array     */
    LINE *lines_top;			/* first spot off end of lines       */
    LINE *lp;				/* first free spot in lines          */

    char *p, *q;
    int ch;
    debug1(DEX, D, "ReadLines(-, %s, -)", fname);

    /* initialize buff to be empty with size BUFF_SIZE */
    buff = malloc(BUFF_SIZE * sizeof(char));
    if( buff == NULL )
        Error(45, 1, "run out of memory when reading index file %s",
              FATAL, no_fpos, fname);
    buff_top = buff + BUFF_SIZE;
    bp = buff;

    /* initialize the lines buffer to be the first line  */
    lines_length = LINES_GUESS;
    lines = malloc(lines_length * sizeof(LINE *));
    lines_top = &lines[lines_length];
    lp = lines;

    /* add first_line to lines buffer if required */
    if( first_line != (FULL_CHAR *) null )
    {
        *lp = malloc((StringLength(first_line) + 1) * sizeof(char));
        StringCopy( (char *) *lp, first_line);
        lp++;
    }

    *lp++ = bp;
    while( (ch = getc(fp)) != EOF )
    {
        debug4(DEX, DD, "lines: [%d  %d(%d)  %d]",
               (int) lines, (int) (lp-1), (int) *(lp-1), (int) lines_top -1);
        debug3(DEX, DD, " buff: [%d   bp %d   %d]",
               (int) buff, (int) bp, (int) buff_top - 1);
        assert( (int) buff >= (int) lines_top ||
                (int) buff_top <= (int) lines,
                "ReadLines: lines and buff overlap!" );

        /* get new buffer and copy current line across if out of buff space */
        if( bp == buff_top )
        {
            debug0(DEX, D, "  getting new buff");
            buff = malloc(BUFF_SIZE * sizeof(char));
            if( buff == NULL )
                Error(45, 2, "run out of memory when reading index file %s",
                      FATAL, no_fpos, fname);
            buff_top = buff + BUFF_SIZE;
            for( p = buff, q = *(lp-1);  q != bp;  *p++ = *q++ );
            bp = p;
            *bp = '\0';
            debug1(DEX, D, "  copied into new buff: %s", buff);
            *(lp-1) = buff;
            if( bp == buff_top )
                Error(45, 3, "line too long when reading index file %s",
                      FATAL, no_fpos, fname);
        }

        /* if newline char, end this line and start the next */
        if( ch == '\n' )
        {
            *bp++ = '\0';
            debug1(DEX, D, "  finished line: %s", *(lp-1));

            /* if no room in lines for next line, double its size */
            if( lp == lines_top )
            {
                debug1(DEX, D, "  realloc(lines, %d)", 2 * lines_length);
                lines = realloc(lines, 2 * lines_length * sizeof(LINE *));
                if( lines == NULL )
                    Error(45, 4, "run out of memory when reading index file %s",
                          FATAL, no_fpos, fname);
                lp = &lines[lines_length];
                lines_length = 2 * lines_length;
                lines_top = &lines[lines_length];
            }

            *lp++ = bp;
        }
        else /* ordinary char with space available, so just add it */
        {
            *bp++ = ch;
        }
    }

    *len = (lp - lines - 1);
    debug1(DEX, D, "ReadLines returning (len = %d)", *len);
    return lines;

} /* end ReadLines */
Exemplo n.º 13
0
static bool IsVariableName(string token)
{
    if (StringEqual(token, "null")) return (TRUE);
    return (StringLength(token) == 1 && isalpha(token[0]));
}
Exemplo n.º 14
0
int zuluCryptEXEOpenVolume( const struct_opts * opts,const char * mapping_name,uid_t uid )
{
	int share                = opts->share ;
	int open_mount           = opts->open_mount ;
	const char * device      = opts->device ;
	const char * mount_point = opts->mount_point ;
	const char * m_opts      = opts->m_opts ;
	const char * source      = opts->key_source ;
	const char * pass        = opts->key ;
	const char * plugin_path = opts->plugin_path ;
	const char * fs_opts     = opts->fs_opts ;
	const char * offset      = opts->offset ;
	const char * const * tcrypt_keyfiles = opts->tcrypt_multiple_keyfiles ;
	/*
	 * Below is a form of memory management.All strings are collected in a stringlist object to easily delete them
	 * when the function returns.This allows for the function to have multiple exit points without risks of leaking
	 * memory from manually examining each exit point to make sure all strings are deleted or go with multiple goto
	 * code deleting blocks to take into account different exit points.
	 */
	stringList_t stl ;
	string_t * stringArray = StringListArray( &stl,6 ) ;
	string_t * passphrase  =  &stringArray[ 0 ] ;
	string_t * m_name      =  &stringArray[ 1 ] ;
	string_t * data        =  &stringArray[ 2 ] ;
	string_t * m_point     =  &stringArray[ 3 ] ;
	string_t * mapper      =  &stringArray[ 4 ] ;
	string_t * mapper_path =  &stringArray[ 5 ] ;

	const char * key = NULL ;
	const char * mapper_name ;
	const char * e ;

	size_t key_len = 0 ;
	int st = 0 ;

	stringList_t stz ;
	tvcrypt v_info ;

	unsigned long m_flags ;

	int tcrypt_keyfile  = 0 ;

	const char * uuid ;
	char * device_path ;

	/*
	 * open_struct_t is declared in ../lib/include.h
	 */
	open_struct_t volume ;

	struct stat statstr ;

	/*
	 * zuluCryptVolumeIsInSystemVolumeList() is defined in volumes.c
	 */
	if( zuluCryptVolumeIsInSystemVolumeList( device ) ){
		/*
		 * check permissions only if volume is explicity mentioned as system.
		 * This is an exception to avoid some udev bad behaviors on udev enabled build
		 */
		if( !zuluCryptUserIsAMemberOfAGroup( uid,"zulucrypt" ) ){
			return zuluExit( 22,device,mount_point,stl ) ;
		}
	}
	if( m_opts == NULL ){

		m_opts = "rw" ;
	}
	/*
	 * zuluCryptMountFlagsAreNotCorrect() is defined in ./mount_flags.c
	 */
	if( zuluCryptMountFlagsAreNotCorrect( m_opts,uid,&m_flags ) ){

		return zuluExit( 5,device,mount_point,stl ) ;
	}
	if( StringHasComponent( m_opts,"rw" ) ){
		/*
		 * zuluCryptSecurityDeviceIsWritable() is defined in path_access.c
		 */
		st = zuluCryptCanOpenPathForWriting( device,uid ) ;
	}else{
		/*
		 * zuluCryptSecurityDeviceIsReadable() is defined in path_access.c
		 */
		st = zuluCryptCanOpenPathForReading( device,uid ) ;
	}

	/*
	 * 1-permissions denied
	 * 2-invalid path
	 * 3-shenanigans
	 * 4-common error
	 */
	switch( st ){

		case 0 :  break ;
		case 1 :  return zuluExit( 6,device,mount_point,stl ) ;
		case 2 :  return zuluExit( 6,device,mount_point,stl ) ;
		case 3 :  return zuluExit( 6,device,mount_point,stl ) ;
		case 4 :  return zuluExit( 6,device,mount_point,stl ) ;
		default:  return zuluExit( 6,device,mount_point,stl ) ;
	}

	if( open_mount ){
		/*
		* zuluCryptCreateMountPoint() is defined in create_mount_point.c
		*/
		*m_point = zuluCryptCreateMountPoint( device,mount_point,m_opts,uid ) ;

		mount_point = StringContent( *m_point ) ;

		if( mount_point == NULL ){

			return zuluExit( 9,device,mount_point,stl ) ;
		}
	}else{
		if( uid != 0 ){

			return zuluExit( 7,device,mount_point,stl ) ;
		}
		if( mount_point != NULL ){

			return zuluExit( 8,device,mount_point,stl ) ;
		}
	}

	if( share ){
		/*
		 * zuluCryptBindSharedMountPointPathTaken() is defined in bind.c
		 */
		if( zuluCryptBindSharedMountPointPathTaken( *m_point ) ){

			return zuluExit_1( 10,opts,device,mount_point,stl ) ;
		}
	}

	/*
	 * zuluCryptCreateMapperName() is defined in ../lib/create_mapper_name.c
	 */
	*m_name = zuluCryptCreateMapperName( device,mapping_name,uid,ZULUCRYPTshortMapperPath ) ;

	*mapper = StringCopy( *m_name ) ;
	mapper_name = StringContent( *m_name ) ;

	*mapper_path = String( zuluCryptMapperPrefix() ) ;
	e = StringMultipleAppend( *mapper_path,"/",mapper_name,NULL ) ;

	if( stat( e,&statstr ) == 0 ){

		return zuluExit_1( 11,opts,device,mount_point,stl ) ;
	}

	if( plugin_path != NULL ){
		/*
		 * zuluCryptUUIDFromPath() is defined in path_access.c
		 */
		uuid = zuluCryptUUIDFromPath( device ) ;

		device_path = _device_path( device ) ;
		/*
		 * zuluCryptPluginManagerGetKeyFromModule is defined in ../pluginManager/zuluCryptPluginManager.c
		 */
		*passphrase = zuluCryptPluginManagerGetKeyFromModule( device_path,plugin_path,uuid,uid,opts,&st ) ;

		StringFree( device_path ) ;
		StringFree( uuid ) ;

		if( st != 0 || *passphrase == StringVoid ){

			return zuluExit_1( 12,opts,device,mount_point,stl ) ;
		}

		key_len = StringLength( *passphrase ) ;
		key = StringContent( *passphrase ) ;

		zuluCryptSecurityLockMemory_1( *passphrase ) ;

	}else if( source == NULL && tcrypt_keyfiles[ 0 ] == NULL ){

		printf( gettext( "Enter passphrase: " ) ) ;
		/*
		 * ZULUCRYPT_KEY_MAX_SIZE is set in ../constants.h
		 */
		switch( StringSilentlyGetFromTerminal_1( passphrase,ZULUCRYPT_KEY_MAX_SIZE ) ){

			case 1 : return zuluExit_1( 13,opts,device,mount_point,stl ) ;
			case 2 : return zuluExit_1( 14,opts,device,mount_point,stl ) ;
		}

		printf( "\n" ) ;
		key = StringContent( *passphrase ) ;
		key_len = StringLength( *passphrase ) ;

		zuluCryptSecurityLockMemory_1( *passphrase ) ;
	}else{
		if( source == NULL || pass == NULL ){

			if( tcrypt_keyfiles == NULL ){

				return zuluExit_1( 15,opts,device,mount_point,stl ) ;
			}
		}
		if( StringsAreEqual( source,"-p" ) ){

			key = pass ;
			key_len = StringSize( pass ) ;

		}else if( StringsAreEqual( source,"-f" ) ){

			if( StringHasNoComponent( pass,"/.zuluCrypt-socket" ) ){

				tcrypt_keyfile = 1 ;
			}
			/*
			 * function is defined at "path_access.c"
			 */
			switch( zuluCryptGetPassFromFile( pass,uid,data ) ){

				case 1 : return zuluExit_1( 16,opts,device,mount_point,stl ) ;
				case 2 : return zuluExit_1( 17,opts,device,mount_point,stl ) ;
				case 4 : return zuluExit_1( 18,opts,device,mount_point,stl ) ;
				case 5 : return zuluExit_1( 19,opts,device,mount_point,stl ) ;
			}
			key = StringContent( *data ) ;
			key_len = StringLength( *data ) ;

			zuluCryptSecurityLockMemory_1( *data ) ;
		}
	}

	memset( &volume,'\0',sizeof( open_struct_t ) ) ;

	if( key != NULL ){

		volume.key     = key ;
		volume.key_len = key_len ;
	}else{
		volume.key     = "" ;
		volume.key_len = 0 ;
	}

	volume.device      = device ;
	volume.offset      = offset ;
	volume.mapper_name = mapper_name ;
	volume.m_point     = mount_point ;
	volume.fs_opts     = fs_opts ;
	volume.uid         = uid ;
	volume.m_opts      = m_opts ;
	volume.m_flags     = m_flags ;

	/*
	 * zuluCryptTrueCryptVeraCryptVolumeInfo() is defined in this source file.
	 */
	zuluCryptTrueCryptVeraCryptVolumeInfo( opts->type,&v_info ) ;

	volume.iteration_count = v_info.iteration_count ;

	volume.veraCrypt_volume = StringAtLeastOneMatch( v_info.type,"vcrypt","veracrypt","vera",NULL ) ;

	StringDelete( &v_info.type ) ;

	plugin_path = plugin_path + StringLastIndexOfChar_1( plugin_path,'/' ) + 1 ;

	volume.luks_detached_header = StringHasComponent( plugin_path,"luks" ) ;

	volume.general_detached_header = StringHasComponent( plugin_path,"generic_header" ) ;

	if( tcrypt_keyfile ){

		volume.key_source = TCRYPT_KEYFILE ;
	}

	if( tcrypt_keyfiles[ 0 ] != NULL ){

		/*
		 * Here, we take a list of keyfiles supplied by the user and then copy them to a safe
		 * location at "/run/zuluCrypt" and then we pass these safe copies to cryptsetup.
		 *
		 * The idea is not to let cryptsetup, a privileged process handle user managed files.
		 */

		stz = zuluCryptCreateKeyFiles( tcrypt_keyfiles,0 ) ;

		volume.tcrypt_keyfiles_count = StringListSize( stz ) ;
		volume.tcrypt_keyfiles       = StringListStringArray_0( stz ) ;

		st = _open_volume( &volume ) ;

		zuluCryptDeleteKeyFiles( stz ) ;

		StringFree( volume.tcrypt_keyfiles ) ;
		StringListDelete( &stz ) ;
	}else{
		st = _open_volume( &volume ) ;
	}

	/*
	 * below two return values comes from ../lib/mount_volume.c
	 */
	if( st == -1 ){
		st = 20 ;
	}
	if( st == 12 ){
		st = 21 ;
	}
	if( st == 8 || st == 3 ){
		st = 3 ;
	}

	device = StringMultiplePrepend( *mapper,"/",zuluCryptMapperPrefix(),NULL ) ;

	if( st == 0 && share ){

		/*
		 * user wish to share the mount point bind the mount point to a publicly accessed path at /run/media/public/
		 */
		/*
		 * zuluCryptBindMountVolume() is defined in ../zuluCrypt-cli/bin/bind.c
		 */
		zuluCryptBindMountVolume( device,*m_point,m_flags ) ;
	}

	/*
	 * zuluCryptCheckInvalidKey() is defined in check_invalid_key.c
	 */
	zuluCryptCheckInvalidKey( opts->device ) ;
	return zuluExit_1( st,opts,device,mount_point,stl ) ;
}
Exemplo n.º 15
0
bool IO_ProfileSimResults::AddSimRun(const ProfileSimRunResults& results,
                                    bool             addExisting)
{
    GenAppClearMsgs();

    bool fileOK = addExisting && ReadFileHeader(false);
    try
    {
        SC_IntArray runStartRecs;
        runStartRecs.SetResizable();
        int nextRec, runIndexRecord;
        if (fileOK)
        {
            ReadFileHeader(true);
            ReadNextRecord();
            runIndexRecord = GetCurrentRec();
            nextRec = ReadInt();
            ReadIntArray(runStartRecs);
        }
        else
        {
            OpenFile(fileName, false);
            WriteStdFileHeader(fileHeader, StringLength(fileHeader) + 1, writeVersion, 0);
            WriteInt(0);                        // 0 runs
            FlushBuffer(nextRec);

            runIndexRecord = nextRec;

            // initial header
            BufferReset(nextRec);
            WriteInt(0);
            WriteInt(0);
            WriteInt(0);
            FlushBuffer(nextRec);

            // backup and set nextRec
            BufferReset(runIndexRecord);
            WriteInt(nextRec);
            WriteInt(0);
            WriteInt(0);

            // reflush
            FlushBuffer();
        }

        int runStart = nextRec;

        //  set to next avail
        BufferReset(nextRec);

        // add the run to the end
        WriteOneRun(results, nextRec);
        nRuns++;

        // update header
        BufferReset(0);
        WriteStdFileHeader(fileHeader, StringLength(fileHeader) + 1, writeVersion, 0);
        WriteInt(nRuns);
        FlushBuffer();

        //  update next avail record
        BufferReset(runIndexRecord);
        WriteInt(nextRec);

        // update run start records
        runStartRecs += runStart;
        WriteIntArray(runStartRecs);
        FlushBuffer();

        CloseFile();
        return true;
    }
    catch (BufFileC::BufferFileError& err) {
        GenAppErrorMsg("WriteSimResults", err.errMsg);
     }

    CloseFile();
    return false;
}
Exemplo n.º 16
0
QString SCTEComponentNameDescriptor::NameString(uint i) const
{
    return dvb_decode_text(&_data[loc(i) + 4], StringLength(i));
}
Exemplo n.º 17
0
void DirectGraphicsFont::DrawTextCenterAlign(float x, float y, const char Text[], D3DCOLOR Color, int Spacing)
{
	DrawText(x - StringLength(Text, Spacing) / 2 , y, Text, Color, Spacing);
}
Exemplo n.º 18
0
static int open_plain_as_me_1(const struct_opts * opts,const char * mapping_name,uid_t uid,int op )
{
	/*
	 * Below is a form of memory management.All strings are collected in a stringlist object to easily delete them
	 * when the function returns.This allows for the function to have multiple exit points without risks of leaking
	 * memory from manually examining each exit point to make sure all strings are deleted or go with multiple goto
	 * code deleting blocks to take into account different exit points.
	 */
	stringList_t stl ;
	string_t * stringArray  = StringListArray( &stl,5 ) ;
	string_t * mapper     = &stringArray[ 0 ] ;
	string_t * passphrase = &stringArray[ 1 ] ;
	string_t * p          = &stringArray[ 2 ] ;
	string_t * dev_st     = &stringArray[ 3 ] ;
	string_t * dev_1      = &stringArray[ 4 ] ;

	size_t len = 0 ;

	const char * source      = opts->key_source ;
	const char * pass        = opts->key ;

	int k = opts->ask_confirmation ;

	const char * cpass = NULL ;

	char * d ;

	const char * device = opts->device ;
	const char * dev = opts->device ;

	int j ;
	int n ;

	const char * cmapper ;

	if( StringPrefixEqual( device,"/dev/loop" ) ){
		/*
		 * zuluCryptLoopDeviceAddress() is defined in ../lib/create_loop_device.c
		 */
		d = zuluCryptLoopDeviceAddress( device ) ;
		*dev_st = StringInherit( &d ) ;
		dev = StringContent( *dev_st ) ;
		*dev_1 = StringCopy( *dev_st ) ;
		device = StringReplaceString( * dev_1,"\\040"," " ) ;
	}

	/*
	 * zuluCryptPartitionIsSystemPartition() is defined in ./partition.c
	 */
	if( zuluCryptPartitionIsSystemPartition( device,uid ) ){
		if( uid != 0 ){
			return zuluExit( stl,8 ) ;
		}
	}
	/*
	 * ZULUCRYPTlongMapperPath and ZULUCRYPTshortMapperPath are in ../constants.h
	 * zuluCryptCreateMapperName() is defined at ../lib/create_mapper_name.c
	 */
	*mapper = zuluCryptCreateMapperName( device,mapping_name,uid,ZULUCRYPTshortMapperPath ) ;

	*p = zuluCryptCreateMapperName( device,mapping_name,uid,ZULUCRYPTlongMapperPath ) ;

	j = zuluCryptCheckOpenedMapper( StringContent( *p ) ) ;

	/*
	 * zuluCryptPartitionIsMounted() is defined in ../lib/process_mountinfo.c
	 */
	n = zuluCryptPartitionIsMounted( dev ) ;

	if( j == 1 ){
		return zuluExit( stl,13 ) ;
	}
	if( n == 1 ){
		return zuluExit( stl,14 ) ;
	}
	if( k == 0 ){
		*passphrase = StringRandomString( 64 ) ;
		cpass = StringContent( *passphrase ) ;
		len = StringLength( *passphrase ) ;
	}else if( source == NULL ){
		printf( gettext( "Enter passphrase: " ) ) ;
		/*
		 * ZULUCRYPT_KEY_MAX_SIZE is set in ../constants.h
		 */
		switch( StringSilentlyGetFromTerminal_1( passphrase,ZULUCRYPT_KEY_MAX_SIZE ) ){
			case 1 : return zuluExit( stl,16 ) ;
			case 2 : return zuluExit( stl,17 ) ;
		}
		printf( "\n" ) ;
		cpass = StringContent( *passphrase ) ;
		len = StringLength( *passphrase ) ;
	}else{
		if( strcmp( source,"-p" ) == 0 ){
			*passphrase = String( pass ) ;
			cpass = StringContent( *passphrase ) ;
			len = StringLength( *passphrase ) ;
		}else if( strcmp( source,"-f" ) == 0 ){
			/*
			 * zuluCryptGetPassFromFile() is defined at "path_access.c"
			 */
			switch( zuluCryptGetPassFromFile( pass,uid,passphrase ) ){
				case 1 : return zuluExit( stl,10 ) ;
				case 2 : return zuluExit( stl,11 ) ;
				case 4 : return zuluExit( stl,12 ) ;
			}
			cpass = StringContent( *passphrase ) ;
			len = StringLength( *passphrase ) ;
		}
	}

	if( zuluCryptSecurityGainElevatedPrivileges() ){
		/*
		 * zuluCryptOpenPlain() is defined in ../lib/open_plain.c
		 */
		if( zuluCryptOpenPlain( device,StringContent( *mapper ),"rw",cpass,len ) != 0 ){
			zuluCryptSecurityDropElevatedPrivileges() ;
			return zuluExit( stl,1 ) ;
		}
	}

	zuluCryptSecurityDropElevatedPrivileges() ;

	/*
	 * Create a mapper path(usually at /dev/mapper) associated with opened plain mapper above.
	 */
	cmapper = StringMultiplePrepend( *mapper,"/",crypt_get_dir(),NULL ) ;

	/*
	 *  mapper path is usually a soft link to /dev/dm-X
	 *  resolve the mapper path to its respective /dev/dm-X and set permission on it.
	 *
	 * We set permission of /dev/dm-X pointing to the device to "u+rw" because we want notmal user to be able
	 * to write to the device through the mapper.
	 *
	 * Useful when a normal user want to delete content of the device by writing random data to it.
	 */
	d = zuluCryptRealPath( cmapper ) ;
	if( zuluCryptSecurityGainElevatedPrivileges() ){
		if( d != NULL ){
			_ignore_result( chown( d,uid,0 ) ) ;
			_ignore_result( chmod( d,S_IRWXU ) ) ;
			StringFree( d ) ;
		}
		zuluCryptSecurityDropElevatedPrivileges() ;
	}else{
		return zuluExit( stl,1 ) ;
	}

	if( op == 1 ){
		return zuluExit( stl,0 ) ;
	}else{
		StringListClearDelete( &stl ) ;
		return 0 ;
	}
}
Exemplo n.º 19
0
 void SetASCII(const TCHAR *src) {
   SetASCII(src, src + StringLength(src));
 }
Exemplo n.º 20
0
int startup(int argc, char *argv[])
{ int i, len;  FULL_CHAR *arg;
  OBJECT t, y, res, s;			/* current token, parser output      */
  BOOLEAN stdin_seen;			/* TRUE when stdin file seen         */
  int source_file_count;		/* number of source files in command */
  FULL_CHAR *cross_db;			/* name of cross reference database  */
  FULL_CHAR *outfile;			/* name of output file               */
  FULL_CHAR *lib;			/* name of library directory         */
  FILE *out_fp;
  long MemCheckLong;
  FULL_CHAR oname[MAX_BUFF], oval[MAX_BUFF], buff[MAX_BUFF], *p;
  int bp;  OBJECT z;
  BOOLEAN seen_wordcount;
#if LOCALE_ON
  char catname[MAX_BUFF], *loc;
#endif

  /* find the name of the library directory, from envt or else from -D */
  lib = AsciiToFull(getenv("LOUTLIB"));
  if( lib == (FULL_CHAR *) NULL )
    lib = AsciiToFull(LIB_DIR);

  /* set locale if that's what we are doing */
#if LOCALE_ON
  loc = setlocale(LC_MESSAGES, "");
  if( loc == (char *) NULL )
  { Error(1, 6, "unable to initialize locale", WARN, no_fpos);
    loc = "C";
  }
  sprintf(catname, "%s/%s/%s/LC_MESSAGES/errors.%s",
    lib, LOCALE_DIR, loc, loc);
  MsgCat = catopen(catname, 0);
#endif

  /* initialise various modules, add current directory to search paths */
  TotalWordCount = 0;
  seen_wordcount = FALSE;
  BackEnd = PS_BackEnd;
  PlainCharWidth = PLAIN_WIDTH;
  PlainCharHeight = PLAIN_HEIGHT;
  PlainFormFeed = FALSE;
  InitializeAll = FALSE;
  UseCollate = COLLATE;
  AllowCrossDb = TRUE;
  InMemoryDbIndexes = TRUE;
  Encapsulated = FALSE;
  SafeExecution = SAFE_DFT ? TRUE : FALSE;
  Kern = TRUE;
  MemInit();
  InitSym();
  LexInit();
  InitFiles();
  AddToPath(SOURCE_PATH,   MakeWord(WORD, STR_EMPTY, no_fpos));
  AddToPath(DATABASE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos));
  AddToPath(INCLUDE_PATH,  MakeWord(WORD, STR_EMPTY, no_fpos));

  /* read command line */
  stdin_seen = FALSE;
  AltErrorFormat = FALSE;
  cross_db = CROSS_DB;
  outfile = STR_STDOUT;
  source_file_count = 0;
  New(CommandOptions, ACAT);
  for( i = 1;  i < argc;  i++ )
  {
    if( *argv[i] == CH_HYPHEN ) switch( *(argv[i]+1) )
    {
      case CH_FLAG_OUTFILE:
     
	/* read name of output file */
	if( (outfile = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 7, "usage: -o <filename>", FATAL, no_fpos);
	if( StringEndsWith(outfile, SOURCE_SUFFIX) )
	  Error(1, 28, "-o: output file name %s ends with %s",
	    FATAL, no_fpos, outfile, SOURCE_SUFFIX);
	break;


      case CH_FLAG_SUPPRESS:
     
	/* suppress references to OldCrossDb and NewCrossDb */
	AllowCrossDb = FALSE;
	break;


      case CH_FLAG_MEMCR:
     
	/* don't use in-memory database indexes */
	InMemoryDbIndexes = FALSE;
	break;


      case CH_FLAG_NOKERN:
     
	/* suppress kerning */
	Kern = FALSE;
	break;


      case CH_FLAG_NOCOLLATE:
     
	/* suppress local collation */
	UseCollate = FALSE;
	break;


      case CH_FLAG_COLLATE:
     
	/* invoke local collation */
	UseCollate = TRUE;
	break;


      case CH_FLAG_CROSS:
     
	/* read name of cross reference database */
	if( (cross_db = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 8, "usage: -c <filename>", FATAL, no_fpos);
	break;


      case CH_FLAG_ERRFILE:
     
	/* read log file name */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 9, "usage: -e <filename>", FATAL, no_fpos);
	ErrorInit(arg);
	break;


      case CH_FLAG_ALTERR:
     
	/* alternative error message format */
	AltErrorFormat = TRUE;
	break;


      case CH_FLAG_EPSFIRST:
     
	/* -EPS produces encapsulated PostScript output */
	if( !StringEqual(AsciiToFull(argv[i]+1), STR_EPS) )
	  Error(1, 10, "usage: -EPS", FATAL, no_fpos);
	Encapsulated = TRUE;
	break;


      case CH_FLAG_DIRPATH:
     
	/* add directory to database and sysdatabase paths */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 11, "usage: -D <directoryname>", FATAL, no_fpos);
	AddToPath(DATABASE_PATH, MakeWord(WORD, arg, no_fpos));
	AddToPath(SYSDATABASE_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_ENCPATH:
     
	/* add directory to character mapping path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 12, "usage: -C <directoryname>", FATAL, no_fpos);
	AddToPath(MAPPING_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_FNTPATH:
     
	/* add directory to font path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 13, "usage: -F <directoryname>", FATAL, no_fpos);
	AddToPath(FONT_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_HYPPATH:
     
	/* add directory to hyph path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 14, "usage: -H <directoryname>", FATAL, no_fpos);
	AddToPath(HYPH_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_INCPATH:
     
	/* add directory to include and sysinclude paths */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 15, "usage: -I <directoryname>", FATAL, no_fpos);
	AddToPath(INCLUDE_PATH, MakeWord(WORD, arg, no_fpos));
	AddToPath(SYSINCLUDE_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_INCLUDE:
     
	/* read sysinclude file and strip any .lt suffix */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 16, "usage: -i <filename>", FATAL, no_fpos);
	len = StringLength(arg) - StringLength(SOURCE_SUFFIX);
	if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) )
	  StringCopy(&arg[len], STR_EMPTY);
	debug0(DFS, D, "  calling DefineFile from main (1)");
	DefineFile(arg, STR_EMPTY, no_fpos, SOURCE_FILE, SYSINCLUDE_PATH);
	break;


      case CH_FLAG_HYPHEN:
     
	/* declare hyphenation file */
	if( FirstFile(HYPH_FILE) != NO_FILE )
	  Error(1, 17, "two -h options illegal", FATAL, no_fpos);
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 18, "usage: -h <filename>", FATAL, no_fpos);
	debug0(DFS, D, "  calling DefineFile from main (2)");
	DefineFile(arg, STR_EMPTY, no_fpos, HYPH_FILE, INCLUDE_PATH);
	DefineFile(arg, HYPH_SUFFIX, no_fpos, HYPH_PACKED_FILE, INCLUDE_PATH);
	break;


      case CH_FLAG_VERSION:
     
	fprintf(stderr, "%s\n", LOUT_VERSION);
	fprintf(stderr, "%-28s %s\n",
	  "Basser Lout written by:", "Jeffrey H. Kingston ([email protected])");
	fprintf(stderr, "%-28s %s\n",
	  "Free source available from:", "ftp://ftp.cs.usyd.edu.au/jeff/lout");
	fprintf(stderr, "%-28s %s %s\n",
	  "This executable compiled:", __TIME__, __DATE__);
	fprintf(stderr, "%-28s %s%s%s\n", "System include directory:",
	  lib, STR_DIR, INCL_DIR);
	fprintf(stderr, "%-28s %s%s%s\n", "System database directory:",
	  lib, STR_DIR, DATA_DIR);
	fprintf(stderr, "Database index files created afresh automatically:%s\n",
	  USE_STAT ? " yes" : " no");
	fprintf(stderr, "Safe execution (disabling system()) is default:%s\n",
	  SAFE_DFT ? " yes" : " no");
	fprintf(stderr, "strcoll() used for sorting by default:%s\n",
	  COLLATE ? " yes" : " no");
	fprintf(stderr, "PDF compression on:%s\n",
	  PDF_COMPRESSION ? " yes" : " no");
	fprintf(stderr, "Debugging (-d, -dd, -ddd flags) available:%s\n",
	  DEBUG_ON ? " yes" : " no");
	fprintf(stderr, "\n");
	fprintf(stderr, "Basser Lout comes with ABSOLUTELY NO WARRANTY.\n");
	fprintf(stderr, "This is free software, and you are welcome to\n");
	fprintf(stderr, "redistribute it under certain conditions.  For\n");
	fprintf(stderr, "details on both points, consult the GNU General\n");
	fprintf(stderr, "Public License (distributed with this software).\n");
	exit(0);
	break;


      case CH_FLAG_WORDS:
     
	seen_wordcount = TRUE;
	break;


      case CH_FLAG_PDF:

	BackEnd = PDF_BackEnd;
	break;


      case CH_FLAG_FFPLAIN:

	if( StringEqual(AsciiToFull(argv[i]+1), STR_PDF) )
	{
	  BackEnd = PDF_BackEnd;
	  break;
	}
	PlainFormFeed = TRUE;
	/* NB NO BREAK */


      case CH_FLAG_PLAIN:
     
	BackEnd = Plain_BackEnd;
	if( *(argv[i]+2) != '\0' )
	{ float len1, len2;  FULL_CHAR units1, units2;
	  if( sscanf(argv[i]+2, "%f%c%f%c",&len1,&units1,&len2,&units2) != 4 )
	  { Error(1, 19, "usage: lout -%c<length><length>",
	      FATAL, no_fpos, *(argv[i]+1));
	  }
	  switch( units1 )
	  {
	    case CH_UNIT_CM:	PlainCharWidth = len1 * CM; break;
	    case CH_UNIT_IN:	PlainCharWidth = len1 * IN; break;
	    case CH_UNIT_PT:	PlainCharWidth = len1 * PT; break;
	    case CH_UNIT_EM:	PlainCharWidth = len1 * EM; break;

	    default:	Error(1, 20, "lout -%c: units must be c, i, p, or m",
				  FATAL, no_fpos, *(argv[i]+1));
				break;
	  }
	  switch( units2 )
	  {
	    case CH_UNIT_CM:	PlainCharHeight = len2 * CM; break;
	    case CH_UNIT_IN:	PlainCharHeight = len2 * IN; break;
	    case CH_UNIT_PT:	PlainCharHeight = len2 * PT; break;
	    case CH_UNIT_EM:	PlainCharHeight = len2 * EM; break;

	    default:	Error(1, 21, "lout -%c: units must be c, i, p, or m",
				  FATAL, no_fpos, *(argv[i]+1));
				break;
	  }
	}
	break;


      case CH_FLAG_INITALL:

	InitializeAll = TRUE;
	AllowCrossDb = FALSE;
	break;


      case CH_FLAG_USAGE:

	PrintUsage(stderr);
	exit(0);
	break;


      case CH_FLAG_DEBUG:
     
	debug_init(AsciiToFull(argv[i]));
	break;


      case CH_FLAG_MEMCHECK:

	sscanf(argv[i], "-m%ld", &MemCheckLong);
	MemCheck = (POINTER) MemCheckLong;
	fprintf(stderr, "checking memory location %ld\n", (long) MemCheck);
	break;


      case '\0':
     
	/* read stdin as file name */
	if( stdin_seen )
	  Error(1, 23, "standard input specified twice", FATAL, no_fpos);
	stdin_seen = TRUE;
	debug0(DFS, D, "  calling DefineFile from main (3)");
	DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH);
	break;


      case CH_FLAG_OPTION:

	/* read command-line document option */
	if( sscanf(argv[i]+2, "%[^{ ] { %[^}] }", oname, oval) != 2 ||
	  StringLength(oname) == 0 || StringLength(oval) == 0 )
	  Error(1, 24, "error in command-line option %s", FATAL, no_fpos,
	    argv[i]+2);
	y = MakeWord(WORD, oname, no_fpos);
	Link(CommandOptions, y);
	New(y, ACAT);
	Link(CommandOptions, y);
	bp = 0;
	for( p = oval;  *p != '\0';  p++ )  switch( *p )
	{
	  case ' ':
	  case '\t':
	  case '\n':
	  case '{':
	  case '}':

	    if( bp > 0 )
	    { buff[bp++] = '\0';
	      if( Down(y) != y ) 
	      { OBJECT g;
		New(g, GAP_OBJ);
		hspace(g) = 1;  vspace(g) = 0;
		FposCopy(fpos(g), *no_fpos);
		Link(y, g);
	      }
	      z = MakeWord(WORD, buff, no_fpos);
	      Link(y, z);
	      bp = 0;
	    }
	    break;


	  default:

	    buff[bp++] = *p;
	    break;
	}
	if( bp > 0 )
	{ buff[bp++] = '\0';
	  z = MakeWord(WORD, buff, no_fpos);
	  Link(y, z);
	}
	if( Down(y) == y )
	  Error(1, 25, "error in command-line option %s", FATAL, no_fpos,
	    argv[i]+2);
	break;


      case CH_FLAG_SAFE:

	/* ensure safe execution by disabling system calls */
	SafeExecution = TRUE;
	break;

      case CH_FLAG_UNSAFE:

	/* allow unsafe execution */
	SafeExecution = FALSE;
	break;

      default:
     
	PrintUsage(stderr);
	Error(1, 26, "unknown command line flag %s", FATAL, no_fpos, argv[i]);
	break;

    }
    else
    {   /* argument is source file, strip any .lout suffix and define it */
	arg = AsciiToFull(argv[i]);
	len = StringLength(arg) - StringLength(SOURCE_SUFFIX);
	if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) )
	  StringCopy(&arg[len], STR_EMPTY);
	debug0(DFS, D, "  calling DefineFile from main (4)");
	DefineFile(AsciiToFull(argv[i]), STR_EMPTY, no_fpos,
	    SOURCE_FILE, SOURCE_PATH);
	source_file_count++;
    }
  } /* for */

  if( UseCollate )
  {
    if (!setlocale (LC_COLLATE, ""))
      Error(1, 30, "unable to initialize collation", WARN, no_fpos);
  }

  /* start timing if required */
  ifdebug(DPP, D, ProfileOn("main"));

  /* open output file, or stdout if none specified, and initialize printer */
  if( StringEqual(outfile, STR_STDOUT) )
  {
#if OS_DOS
    /* For DOS/Win32 we need to set binary mode on stdout to prevent
       PDF compressed streams and xrefs from being corrupted - Uwe 12/98 */
    if( BackEnd->code != PLAINTEXT &&
	_setmode(_fileno(stdout), _O_BINARY) == -1 )
      Error(1, 31, "cannot set binary mode on stdout", FATAL, no_fpos);
#endif
    out_fp = stdout;
  }
  else
  { out_fp = StringFOpen(outfile,
		BackEnd->code == PLAINTEXT ? WRITE_TEXT : WRITE_BINARY);
    if( out_fp == null )
      Error(1, 27, "cannot open output file %s", FATAL, no_fpos, outfile);
  }

  /* initialize miscellaneous modules */
  ColourInit();
  LanguageInit();
  BackEnd->PrintInitialize(out_fp);

  /* append default directories to file search paths */
  AddToPath(FONT_PATH,      MakeWordThree(lib, STR_DIR, AsciiToFull(FONT_DIR)));
  AddToPath(HYPH_PATH,      MakeWordThree(lib, STR_DIR, AsciiToFull(HYPH_DIR)));
  AddToPath(MAPPING_PATH,   MakeWordThree(lib, STR_DIR, AsciiToFull(MAPS_DIR)));
  AddToPath(SYSDATABASE_PATH,MakeWordThree(lib,STR_DIR, AsciiToFull(DATA_DIR)));
  AddToPath(DATABASE_PATH,  MakeWordThree(lib, STR_DIR, AsciiToFull(DATA_DIR)));
  AddToPath(SYSINCLUDE_PATH,MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR)));
  AddToPath(INCLUDE_PATH,   MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR)));

  /* use stdin if no source files were mentioned */
  if( source_file_count == 0 )
  { debug0(DFS, D, "  calling DefineFile from main (5)");
    DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH);
  }

  /* load predefined symbols into symbol table */
  StartSym      = nilobj;  /* Not a mistake */
  StartSym      = load(KW_START,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  GalleySym     = load(KW_GALLEY,       0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  ForceGalleySym= load(KW_FORCE_GALLEY, 0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  InputSym      = load(KW_INPUT,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  PrintSym      = load(KW_PRINT,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  FilterInSym   = load(KW_FILTERIN,     0, FALSE,  FALSE,  FALSE, NO_PREC     );
  FilterOutSym  = load(KW_FILTEROUT,    0, FALSE,  FALSE,  FALSE, NO_PREC     );
  FilterErrSym  = load(KW_FILTERERR,    0, FALSE,  FALSE,  FALSE, NO_PREC     );
  OptGallSym    = load(KW_OPTGALL,      0, FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  VerbatimSym   = load(KW_VERBATIM,VERBATIM,FALSE, TRUE,   FALSE, DEFAULT_PREC);
  RawVerbatimSym= load(KW_RAWVERBATIM,RAW_VERBATIM,FALSE,TRUE,FALSE,DEFAULT_PREC);


  load(KW_BEGIN,        BEGIN,          FALSE,  FALSE,  FALSE, BEGIN_PREC  );
  load(KW_END,          END,            FALSE,  FALSE,  FALSE, END_PREC    );
  load(KW_ENV,          ENV,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVA,         ENVA,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVB,         ENVB,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVC,         ENVC,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVD,         ENVD,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CENV,         CENV,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CLOS,         CLOS,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LVIS,         LVIS,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LUSE,         LUSE,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LEO,          LEO,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LBR,          LBR,            FALSE,  FALSE,  FALSE, LBR_PREC    );
  load(KW_RBR,          RBR,            FALSE,  FALSE,  FALSE, RBR_PREC    );
  load(KW_INCLUDE,      INCLUDE,        FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSINCLUDE,   SYS_INCLUDE,    FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_PREPEND,      PREPEND,        FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSPREPEND,   SYS_PREPEND,    FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_DATABASE,     DATABASE,       FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSDATABASE,  SYS_DATABASE,   FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_USE,          USE,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_NOT_REVEALED, NOT_REVEALED,   FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CASE,         CASE,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_YIELD,        YIELD,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BACKEND,      BACKEND,        FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_XCHAR,        XCHAR,          FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_FONT,         FONT,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SPACE,        SPACE,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_YUNIT,        YUNIT,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ZUNIT,        ZUNIT,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BREAK,        BREAK,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_UNDERLINE,    UNDERLINE,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_COLOUR,       COLOUR,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_COLOR,        COLOUR,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_OUTLINE,      OUTLINE,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LANGUAGE,     LANGUAGE,       TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CURR_LANG,    CURR_LANG,      FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_FAMILY,  CURR_FAMILY,    FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_FACE,    CURR_FACE,      FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_YUNIT,   CURR_YUNIT,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_ZUNIT,   CURR_ZUNIT,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_COMMON,       COMMON,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_RUMP,         RUMP,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_MELD,         MELD,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_INSERT,       INSERT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ONE_OF,       ONE_OF,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_NEXT,         NEXT,           FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_PLUS,         PLUS,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_MINUS,        MINUS,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_OPEN,         OPEN,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_TAGGED,       TAGGED,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_WIDE,         WIDE,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HIGH,         HIGH,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSHIFT,       HSHIFT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VSHIFT,       VSHIFT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BEGIN_HEADER, BEGIN_HEADER,   TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_END_HEADER,   END_HEADER,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_SET_HEADER,   SET_HEADER,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CLEAR_HEADER, CLEAR_HEADER,   FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_ONE_COL,      ONE_COL,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ONE_ROW,      ONE_ROW,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSCALE,       HSCALE,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VSCALE,       VSCALE,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HCOVER,       HCOVER,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VCOVER,       VCOVER,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_KERN_SHRINK,  KERN_SHRINK,    TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SCALE,        SCALE,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HCONTRACT,    HCONTRACT,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VCONTRACT,    VCONTRACT,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HLIMITED,     HLIMITED,       FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VLIMITED,     VLIMITED,       FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HEXPAND,      HEXPAND,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VEXPAND,      VEXPAND,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTHVSPAN,  START_HVSPAN,   FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTHSPAN,   START_HSPAN,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTVSPAN,   START_VSPAN,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSPAN,        HSPAN,          FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_VSPAN,        VSPAN,          FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_PADJUST,      PADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HADJUST,      HADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VADJUST,      VADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ROTATE,       ROTATE,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BACKGROUND,   BACKGROUND,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_INCGRAPHIC,   INCGRAPHIC,     FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SINCGRAPHIC,  SINCGRAPHIC,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_PLAINGRAPHIC, PLAIN_GRAPHIC,  TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_GRAPHIC,      GRAPHIC,        TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LINK_SOURCE,   LINK_SOURCE,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LINK_DEST,    LINK_DEST,      TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CROSS,        CROSS,          TRUE,   TRUE,   FALSE, CROSSOP_PREC);
  load(KW_FORCE_CROSS,  FORCE_CROSS,    TRUE,   TRUE,   FALSE, CROSSOP_PREC);
  load(KW_NULL,         NULL_CLOS,      FALSE,  FALSE,  TRUE,  NO_PREC     );
  load(KW_PAGE_LABEL,   PAGE_LABEL,     FALSE,  TRUE,   TRUE,  DEFAULT_PREC);

#define setcat(s, mk, jn)  has_mark(s)=mk, has_join(s)=jn

  s=load(KW_VCAT_NN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,FALSE);
  s=load(KW_VCAT_MN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, FALSE);
  s=load(KW_VCAT_NJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_VCAT_MJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, TRUE);
  s=load(KW_HCAT_NN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,FALSE);
  s=load(KW_HCAT_MN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, FALSE);
  s=load(KW_HCAT_NJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_HCAT_MJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, TRUE);
  s=load(KW_ACAT_NJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_ACAT_MJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,TRUE, TRUE);

  /* intialize fonts and load @FontDef symbol */
  FontInit();

  /* intialize current time and load @Moment symbol */
  InitTime();

  /* initialize filter module */
  FilterInit();

  /* initialize enviroment table module */
  EnvInit();

  /* initialise scope chain to <StartSym> */
  PushScope(StartSym, FALSE, FALSE);

  /* initialise lexical analyser */
  LexPush(FirstFile(SOURCE_FILE), 0, SOURCE_FILE, 1, FALSE);

  /* process input files */
  InitParser(cross_db);
  t = NewToken(BEGIN, no_fpos, 0, 0, BEGIN_PREC, StartSym);
  res = Parse(&t, StartSym, TRUE, TRUE);
  debug0(DGT, D, "calling TransferEnd(res) from main()");
  DisposeObject(CommandOptions);
  TransferEnd(res);
  TransferClose();

  /* close various modules */
  BackEnd->PrintAfterLastPage();
  BackEnd->LinkCheck();
  CrossClose();
  CloseFiles();

  /* remove any leftover filter temporary files */
  FilterScavenge(TRUE);

  /* print word count, if required */
  if( seen_wordcount )
    Error(1, 29, "total of all words printed: %d", WARN,no_fpos,TotalWordCount);

  /* check for unbalanced error blocks */
  CheckErrorBlocks();

  /* wrapup */
  ifdebug(DST, DD, CheckSymSpread() );
  ifdebug(ANY, D, DeleteEverySym() );
  debug0(DMA, D, "at end of run:");
  ifdebug(DMA, D, DebugMemory() );
  ifdebug(DPP, D, ProfileOff("main"));
  ifdebug(DPP, D, ProfilePrint());
  ifdebug(DET, D, EnvDebug());

#if LOCALE_ON
  catclose(MsgCat);
#endif

  exit(0);
  return 0;
} /* end main */
Exemplo n.º 21
0
pword *
term_to_dbformat(pword *parg, dident mod)
{
    pword **save_tt = TT;
    register word arity = 1, len;
    register word curr_offset = 0, top_offset = 2;	/* in 'word's */
    register pword *queue_tail = (pword *) 0;
    pword *queue_head = (pword *) 0;
    register pword *pw;
    register char *dest, *stop;
    pword *header;
    temp_area	meta_attr;
    int		flag = 0;

    Temp_Create(meta_attr, 4 * ATTR_IO_TERM_SIZE * sizeof(pword));
    header = TG;
    dest = (char *) (header + 1) + 4;	/* space for the TBUFFER pword and for
					 * the external format header	*/

    for(;;)	/* handle <arity> consecutive pwords, starting at <parg> */
    {
	do	/* handle the pword pointed to by parg */
	{
	    pw = parg;

	    /* I need here a slightly modified version of Dereference_(pw)
	     * that stops also at MARKed words. Not very nice, I know.
	     */
	    while (IsRef(pw->tag) && !(pw->tag.kernel & MARK) && !IsSelfRef(pw))
		pw = pw->val.ptr;

	    Reserve_Space(6);

	    if (pw->tag.kernel & MARK)
	    {
		if (SameTypeC(pw->tag,TDE))		/* a suspension */
		{
		    Store_Byte(Tag(pw->tag.kernel));
		    Store_Int32((pw[SUSP_FLAGS].tag.kernel & ~MARK));
		    if (SuspDead(pw)) {
			curr_offset += Words(SUSP_HEADER_SIZE-1);
			parg += SUSP_HEADER_SIZE-1;
			arity -= SUSP_HEADER_SIZE-1;
		    } else {
			Store_Byte(SuspPrio(pw) + (SuspRunPrio(pw) << 4));
			curr_offset += Words(SUSP_GOAL-1);
			parg += SUSP_GOAL-1;
			arity -= SUSP_GOAL-1;
		    }
		}
		else if (pw->val.nint == curr_offset)	/* a nonstd variable */
		{
		    Store_Byte(Tag(pw->tag.kernel));
		    Store_Int(pw->val.nint);
		    if (!IsNamed(pw->tag.kernel))
		    {
			Store_Byte(0);
		    }
		    else		/* store its name */
		    {
			dident vdid = TagDid(pw->tag.kernel);
			len = DidLength(vdid);
			Store_Int(len);
			Reserve_Space(len);
			Store_String(len, DidName(vdid));
		    }
		}
		else	/* just a reference to an already encountered variable */
		{
		    Store_Byte(Tag(TVAR_TAG));
		    Store_Int(pw->val.nint);
		}
	    }
	    else switch (TagType(pw->tag))
	    {
	    case TINT:
#if SIZEOF_CHAR_P > 4
		if (pw->val.nint <  WSUF(-2147483648) || WSUF(2147483648) <= pw->val.nint)
		{
		    /* store as a bignum (to be readable on 32bit machines) */
		    len = tag_desc[pw->tag.kernel].string_size(pw->val, pw->tag, 1);
		    Store_Byte(TBIG);
		    Store_Int(len);
		    Reserve_Space(len+1);
		    stop = dest+len;
		    dest += tag_desc[pw->tag.kernel].to_string(pw->val, pw->tag,
			dest, 1);
		    while (dest <= stop)	/* pad and terminate */
		    	*dest++ = 0;
		    break;
		}
#endif
		Store_Byte(TINT);
#ifdef OLD_FORMAT
		Store_Int32(pw->val.nint);
#else
		Store_Int(pw->val.nint);
#endif
		break;

	    case TNIL:
		Store_Byte(Tag(pw->tag.kernel));
		break;

	    case TDICT:
		len = DidLength(pw->val.did);
		Store_Byte(TDICT);
		Store_Int(DidArity(pw->val.did));
		Store_Int(len);
		Reserve_Space(len);
		Store_String(len, DidName(pw->val.did));
		break;

	    case TDBL:
	    {
		ieee_double d;
		d.as_dbl = Dbl(pw->val);
		Store_Byte(TDBL);
		Store_Byte(sizeof(double)-1);	/* backward compat */
		Reserve_Space(sizeof(double));
		Store_Int32(d.as_struct.mant1);
		Store_Int32(d.as_struct.mant0);
		break;
	    }

	    case TIVL:
	    {
		ieee_double dlwb, dupb;
		dlwb.as_dbl = IvlLwb(pw->val.ptr);
		dupb.as_dbl = IvlUpb(pw->val.ptr);
		Store_Byte(TIVL);
		Reserve_Space(2*sizeof(double));
		Store_Int32(dlwb.as_struct.mant1);
		Store_Int32(dlwb.as_struct.mant0);
		Store_Int32(dupb.as_struct.mant1);
		Store_Int32(dupb.as_struct.mant0);
		break;
	    }

	    case TSTRG:
		len = StringLength(pw->val);
		Store_Byte(TSTRG);
		Store_Int(len);
		Reserve_Space(len);
		Store_String(len, StringStart(pw->val));
		break;

	    case TVAR_TAG:	/* standard variable */
		Store_Byte(Tag(TVAR_TAG));
		Store_Int(curr_offset);
		Trail_(pw);
		pw->val.nint = curr_offset;
		pw->tag.kernel |= MARK;
		break;

	    case TNAME:
	    case TUNIV:
		Store_Byte(Tag(TVAR_TAG));
		Store_Int(top_offset);
		Trail_Tag(pw);
		pw->val.nint = top_offset;
		pw->tag.kernel |= MARK;
		top_offset += 2;
		EnQueue_(pw, 1, 0);
		break;

	    case TMETA:
		Store_Byte(Tag(TVAR_TAG));
		Store_Int(top_offset);
		Trail_Tag(pw);
		pw->val.nint = top_offset;
		pw->tag.kernel |= MARK;
		top_offset += 4;
		EnQueue_(pw, 2, QUEUE_MASK_META);
		break;

	    case TSUSP:
		Store_Byte(Tag(TSUSP));
		pw = pw->val.ptr;
		if (pw->tag.kernel & MARK)	/* not the first encounter */
		{
		    Store_Int(pw->val.nint);
		}
		else
		{
		    Store_Int(top_offset);
		    Trail_Pword(pw);
		    pw->tag.kernel |= MARK;
		    pw->val.nint = top_offset;
		    if (SuspDead(pw))
		    {
			top_offset += Words(SUSP_HEADER_SIZE);	/* for TDE */
			EnQueue_(pw, SUSP_HEADER_SIZE, 0);
		    }
		    else
		    {
			top_offset += Words(SUSP_SIZE);	/* for TDE */
			EnQueue_(pw, SUSP_SIZE, 0);
		    }
		}
		break;

	    case TLIST:
		Store_Byte(Tag(TLIST));
		Store_Int(top_offset);
		top_offset += 4;
		EnQueue_(pw->val.ptr, 2, 0);
		break;

	    case TCOMP:
		Store_Byte(Tag(TCOMP));
		Store_Int(top_offset);
		if (flag) {
		    pword pw_out;
		    (void) transf_meta_out(pw->val, pw->tag,
			    (pword *) TempAlloc(meta_attr, ATTR_IO_TERM_SIZE * sizeof(pword)),
			    D_UNKNOWN, &pw_out);
		    pw = pw_out.val.ptr;
		    len = 1 + DidArity(pw->val.did);
		    EnQueue_(pw, len, 0);
		} else {
		    len = 1 + DidArity(pw->val.ptr->val.did);
		    EnQueue_(pw->val.ptr, len, 0);
		}
		top_offset += 2*len;
		break;

	    default:
		if (TagType(pw->tag) >= 0 && TagType(pw->tag) <= NTYPES)
		{
		    len = tag_desc[TagType(pw->tag)].string_size(pw->val, pw->tag, 1);
		    Store_Byte(Tag(pw->tag.kernel));
		    Store_Int(len);
		    Reserve_Space(len+1);
		    stop = dest+len;
		    dest += tag_desc[TagType(pw->tag)].to_string(pw->val, pw->tag,
			dest, 1);
		    while (dest <= stop)	/* pad and terminate */
		    	*dest++ = 0;
		}
		else
		{
		    p_fprintf(current_err_,
			"bad type in term_to_dbformat: 0x%x\n",
			pw->tag.kernel);
		}
		break;
	    }
	    curr_offset += Words(1);
	    ++parg;
	} while (--arity);
	if (EmptyQueue())
	    break;
	DeQueue_(parg, arity, flag);
    }
					/* # bytes of external representation */
    Store_Byte(0);			/* add a terminating 0		*/
    Set_Buffer_Size(header, dest - (char*) header - sizeof(pword));
    header->tag.kernel = TBUFFER;
    Align();				/* align the global stack pointer */
    TG = (pword *) dest;
    dest = (char *) (header + 1);	/* fill in the external format header */
    Store_Int32(top_offset);		/* (size of term after restoring) */
    Untrail_Variables(save_tt);
    Temp_Destroy(meta_attr);
    return header;
}
Exemplo n.º 22
0
void Burger::Filename::SetFromNative(const char *pInput)
{
	Clear();	// Clear out the previous string

	// Determine the length of the prefix
	WordPtr uInputLength = StringLength(pInput);
	const char *pBaseName;
	WordPtr uBaseNameLength;
	if (reinterpret_cast<const Word8 *>(pInput)[0]!='/') {		// Must I prefix with the current directory?
		if ((uInputLength>=2) && !MemoryCompare("./",pInput,2)) {		// Dispose of "current directory"
			pInput+=2;
			uInputLength-=2;
		}
		pBaseName = "8:";
		uBaseNameLength = 2;
	} else {
		if ((uInputLength>9) && !MemoryCompare(pInput,"/Volumes/",9)) {
			pBaseName = ":";		// Place a leading colon in the output
			uBaseNameLength = 1;
			pInput+=9;
			uInputLength-=9;
		} else {
			pBaseName = FileManager::GetBootName();
			uBaseNameLength = FileManager::GetBootNameSize();
			++pInput;
			--uInputLength;
		}
	}

	WordPtr uOutputLength = uBaseNameLength+uInputLength+10;
	char *pOutput = m_Filename;
	if (uOutputLength>=sizeof(m_Filename)) {
		pOutput = static_cast<char *>(Alloc(uOutputLength));
		if (!pOutput) {
			return;
		}
	}
	m_pFilename = pOutput;
	
	MemoryCopy(pOutput,pBaseName,uBaseNameLength);
	pOutput+=uBaseNameLength;
	
// Now, just copy the rest of the path	
	
	Word uTemp = reinterpret_cast<const Word8*>(pInput)[0];
	if (uTemp) {				// Any more?
		do {
			++pInput;			// Accept char
			if (uTemp=='/') {
				uTemp = ':';
			}
			pOutput[0] = uTemp;	// Save char
			++pOutput;
			uTemp = reinterpret_cast<const Word8*>(pInput)[0];	// Next char
		} while (uTemp);		// Still more?
	}

	// The wrap up...
	// Make sure it's appended with a colon

	if (reinterpret_cast<const Word8*>(pOutput)[-1]!=':') {
		pOutput[0] = ':';
		++pOutput;
	}
	pOutput[0] = 0;			// End the string with zero
}
Exemplo n.º 23
0
/*
 * get_pass_from_file function is defined at get_pass_from_file.c *
 */
int zuluCryptEXEAddKey( const struct_opts * opts,uid_t uid )
{
	const char * device      = opts->device ;
	const char * keyType1    = opts->existing_key_source ;
	const char * existingKey = opts->existing_key ;
	const char * keyType2    = opts->new_key_source ;
	const char * newKey      = opts->new_key ;

	/*
	 * Below is a form of memory management.All strings are collected in a stringlist object to easily delete them
	 * when the function returns.This allows for the function to have multiple exit points without risks of leaking
	 * memory from manually examining each exit point to make sure all strings are deleted or go with multiple goto
	 * code deleting blocks to take into account different exit points.
	 */
	stringList_t stl ;
	string_t * stringArray  = StringListArray( &stl,5 ) ;
	string_t * presentKey	= &stringArray[ 0 ] ;
	string_t * newKey_1  	= &stringArray[ 1 ] ;
	string_t * newKey_2    	= &stringArray[ 2 ] ;
	string_t * ek          	= &stringArray[ 3 ] ;
	string_t * nk          	= &stringArray[ 4 ] ;

	const char * key1 = NULL ;
	const char * key2 = NULL ;

	size_t len1 = 0 ;
	size_t len2 = 0 ;

	int status = 0 ;

	int socket_path ;

	tcrypt_opts tcrypt ;

	memset( &tcrypt,'\0',sizeof( tcrypt_opts ) ) ;

	/*
	 * zuluCryptPartitionIsSystemPartition() is defined in ./partitions.c
	 */
	if( zuluCryptPartitionIsSystemPartition( device,uid ) ){

		if( zuluCryptExeOriginalUserIsNotRoot() ){

			if( !zuluCryptUserIsAMemberOfAGroup( uid,"zulucrypt" ) ){

				return zuluExit( 4,stl ) ;
			}
		}
	}
	/*
	 * zuluCryptSecurityDeviceIsWritable() is defined in path_access.c
	 */
	status = zuluCryptCanOpenPathForWriting( device,uid ) ;
	/*
	 * 1-permissions denied
	 * 2-invalid path
	 * 3-shenanigans
	 * 4-common error
	 */
	switch( status ){

		case 0 :  break ;
		case 1 :  return zuluExit( 5,stl ) ;
		case 2 :  return zuluExit( 5,stl ) ;
		case 3 :  return zuluExit( 5,stl ) ;
		case 4 :  return zuluExit( 5,stl ) ;
		default:  return zuluExit( 5,stl ) ;
	}

	switch( _zuluCryptCheckEmptySlots( device ) ){

		case 0 : return zuluExit( 6,stl ) ;
		case 1 : return zuluExit( 2,stl ) ;
		case 2 : /* no complains,continue */ ;
	}

	if( keyType1 == NULL && keyType2 == NULL ){

		switch( zuluGetKeys( presentKey,newKey_1,newKey_2 ) ){

			case 1 : return zuluExit( 7,stl ) ;
			case 2 : return zuluExit( 8,stl ) ;
		}

		if( StringsAreEqual_1( *newKey_1,*newKey_2 ) ){

			key1 = StringContent( *presentKey ) ;
			len1 = StringLength ( *presentKey ) ;
			key2 = StringContent( *newKey_1   ) ;
			len2 = StringLength ( *newKey_1   ) ;
		}else{
			return zuluExit( 9,stl ) ;
		}
	}else{
		if( newKey == NULL || existingKey == NULL ){

			return zuluExit( 10,stl ) ;
		}
		if( StringsAreEqual( keyType1,"-f" ) ){

			/*
			 * this function is defined at "path_access.c"
			 */

			switch( zuluCryptGetPassFromFile( &socket_path,existingKey,uid,ek ) ){

				case 1 : return zuluExit( 11,stl ) ;
				case 4 : return zuluExit( 12,stl ) ;
				case 2 : return zuluExit( 13,stl ) ;
				case 5 : return zuluExit( 14,stl ) ;
			}

			key1 = StringContent( *ek ) ;
			len1 = StringLength( *ek ) ;

			if( !socket_path ){

				tcrypt.existing_key_is_keyfile = 1 ;
			}
		}
		if( StringsAreEqual( keyType2,"-f" ) ){

			/*
			 * this function is defined at "path_access.c"
			 */

			switch( zuluCryptGetPassFromFile( &socket_path,newKey,uid,nk ) ){

				case 1 : return zuluExit( 11,stl ) ;
				case 4 : return zuluExit( 12,stl ) ;
				case 2 : return zuluExit( 13,stl ) ;
				case 5 : return zuluExit( 14,stl ) ;
			}

			key2 = StringContent( *nk ) ;
			len2 = StringLength( *nk ) ;

			if( !socket_path ){

				tcrypt.new_key_is_keyfile = 1 ;
			}
		}
		if( StringsAreEqual( keyType1,"-f" ) && StringsAreEqual( keyType2,"-f" ) ){

			;

		}else if( StringsAreEqual( keyType1,"-p" ) && StringsAreEqual( keyType2,"-p" ) ){

			key1 = existingKey ;
			len1 = StringSize( existingKey ) ;
			key2 = newKey ;
			len2 = StringSize( newKey ) ;

		}else if( StringsAreEqual( keyType1,"-p" ) && StringsAreEqual( keyType2,"-f" ) ){

			key1 = existingKey ;
			len1 = StringSize( existingKey ) ;

		}else if( StringsAreEqual( keyType1,"-f" ) && StringsAreEqual( keyType2,"-p" ) ){

			key2 = newKey ;
			len2 = StringSize( newKey ) ;
		}else{
			return zuluExit( 10,stl ) ;
		}
	}

	zuluCryptSecurityLockMemory( stl ) ;

	zuluCryptSecurityGainElevatedPrivileges() ;

	/*
	 * zuluCryptVolumeIsLuks() is defined in ../lib/is_luks.c
	 */
	if( zuluCryptVolumeIsLuks( device ) ){

		/*
		* zuluCryptAddKey() is defined in ../lib/add_key.c
		*/
		status = zuluCryptAddKey( device,key1,len1,key2,len2 ) ;
	}else{
		tcrypt.device = device ;

		tcrypt.existing_key      = key1 ;
		tcrypt.existing_key_size = len1 ;

		tcrypt.new_key           = key2 ;
		tcrypt.new_key_size      = len2 ;

		tcrypt.type              = opts->type ;

		status = _replace_truecrypt_key( &tcrypt ) ;
	}

	zuluCryptSecurityDropElevatedPrivileges() ;

	return zuluExit( status,stl ) ;
}
Exemplo n.º 24
0
const char *Burger::Filename::GetNative(void)
{
	Expand();		// Resolve prefixes

	const Word8 *pFullPathName = reinterpret_cast<const Word8 *>(m_pFilename);
	WordPtr uOutputLength = StringLength(reinterpret_cast<const char *>(pFullPathName))+10;
	char *pOutput = m_NativeFilename;
	if (uOutputLength>=sizeof(m_NativeFilename)) {
		pOutput = static_cast<char *>(Alloc(uOutputLength));
		if (!pOutput) {
			m_NativeFilename[0] = 0;
			return m_NativeFilename;
		}
	}
	m_pNativeFilename = pOutput;
	
	// Now, is this a fully qualified name?
	
	if (pFullPathName[0]==':') {				// First char is ':' for a qualified pathname
	
		// Look for the volume name by scanning for the ending colon
		const Word8 *pFileParsed = reinterpret_cast<Word8*>(StringCharacter(reinterpret_cast<const char *>(pFullPathName)+1,':'));
		if (pFileParsed) {
			// Is this on the boot volume?
			// Also test for the special case of :Foo vs :FooBar
			
			{
				Word uIndex = FileManager::GetBootNameSize();

				// Test for boot name match
				if (MemoryCaseCompare(FileManager::GetBootName(),pFullPathName,uIndex)) {
					StringCopy(pOutput,"/Volumes");	// Look in the mounted volumes folder
					pOutput+=8;								// At the end of /Volumes
				} else {
					// If the volume requested is the boot volume, remove the name
					// and use the leading "/" for the root prefix.
					pFullPathName+=(uIndex-1);
				}
			}
		}
	}

	// Convert the rest of the path
	// Colons to slashes
	
	Word uTemp = pFullPathName[0];
	if (uTemp) {
		do {
			++pFullPathName;
			if (uTemp==':') {
				uTemp = '/';		// Unix style
			}
			
			pOutput[0] = uTemp;
			++pOutput;
			uTemp = pFullPathName[0];
		} while (uTemp);
		
		// A trailing slash assumes more to follow, get rid of it
		--pOutput;
		if ((pOutput==m_pNativeFilename) ||		// Only a '/'? (Skip the check then)
			(reinterpret_cast<Word8*>(pOutput)[0]!='/')) {
			++pOutput;		// Remove trailing slash
		}
	}
	pOutput[0] = 0;			// Terminate the "C" string
	return m_pNativeFilename;
}
Exemplo n.º 25
0
void Test::compareWithFail() {
    CORRADE_COMPARE_WITH("You rather GTFO", "hello", StringLength(9)); // #14
}
Exemplo n.º 26
0
string_t zuluCryptCreateKeyFile_1( string_t st,const char * fileName )
{
	return zuluCryptCreateKeyFile( StringContent( st ),StringLength( st ),fileName ) ;
}
Exemplo n.º 27
0
static int
p_string_list(value vs, type ts, value vl, type tl)
{
    register pword	*pw, *list;
    register char	*s;
    register int	len;
    pword		*old_tg = Gbl_Tg;

    if (IsRef(ts))			/* no string given	*/
    {
	if (IsRef(tl))			/* we need at least one	*/
	{
	    Bip_Error(PDELAY_1_2);
	}
	else if (IsList(tl))		/* make a string from a list	*/
	{
	    list = vl.ptr;		/* space for the string header	*/
	    Push_Buffer(1);		/* make minimum buffer		*/
	    s = (char *) BufferStart(old_tg);	/* start of the new string */
	    for(;;)			/* loop through the list	*/
	    {
		pw = list++;
		Dereference_(pw);		/* get the list element	*/
		if (IsRef(pw->tag))		/* check it		*/
		{
		    Gbl_Tg = old_tg;
		    Push_var_delay(vs.ptr, ts.all);
		    Push_var_delay(pw, pw->tag.all);
		    Bip_Error(PDELAY);
		}
		else if (!IsInteger(pw->tag))
		{
		    Gbl_Tg = old_tg;
		    Bip_Error(TYPE_ERROR);
		}
		else if (pw->val.nint < 0  ||  pw->val.nint > 255)
		{
		    Gbl_Tg = old_tg;
		    Bip_Error(RANGE_ERROR);
		}
		*s++ = pw->val.nint;
		if (s == (char *) Gbl_Tg)	/* we need another pword */
		{
		    Gbl_Tg += 1;
		    Check_Gc;
		}
		Dereference_(list);		/* get the list tail	*/
		if (IsRef(list->tag))
		{
		    Gbl_Tg = old_tg;
		    Push_var_delay(vs.ptr, ts.all);
		    Push_var_delay(list, list->tag.all);
		    Bip_Error(PDELAY);
		}
		else if (IsList(list->tag))
		    list = list->val.ptr;
		else if (IsNil(list->tag))
		    break;			/* end of the list	*/
		else
		{
		    Gbl_Tg = old_tg;
		    Bip_Error(TYPE_ERROR);
		}
	    }
	    *s = '\0';			/* terminate the string		*/
	    Set_Buffer_Size(old_tg, s - (char *)(old_tg + 1) + 1);
	    Kill_DE;
	    Return_Unify_String(vs, ts, old_tg);
	}
	else if (IsNil(tl))
	{
	    Kill_DE;
	    Return_Unify_String(vs, ts, empty_string);
	}
	else
	{
	    Bip_Error(TYPE_ERROR);
	}
    }
    else if (IsString(ts))
    {
	Kill_DE;
	Check_Output_List(tl);
	s = StringStart(vs);		/* get a pointer to the string	*/
	len = StringLength(vs);
	if (len == 0)
	{
	    Return_Unify_Nil(vl, tl);
	}
	/* Additional a-priori overflow check because adding to TG may
	 * may wrap around the address space and break Check_Gc below
	 */
	Check_Available_Pwords(2*len);
	pw = Gbl_Tg;			/* reserve space for the list	*/
	Gbl_Tg += 2*len;
	Check_Gc;
	pw->val.nint = *s++ & 0xFFL;	/* construct the list	*/
	pw++->tag.kernel = TINT;
	while (--len > 0)
	{
	    pw->val.ptr = pw + 1;
	    pw++->tag.kernel = TLIST;
	    pw->val.nint = *s++ & 0xFFL;
	    pw++->tag.kernel = TINT;
	}
	pw->tag.kernel = TNIL;
	Return_Unify_List(vl, tl, old_tg);
    }
    else
    {
	Bip_Error(TYPE_ERROR);
    }
}
Exemplo n.º 28
0
void zuluCryptSecurityLockMemory_1( string_t st )
{
	if( st != StringVoid ){
		mlock( StringContent( st ),StringLength( st ) ) ;
	}
}
Exemplo n.º 29
0
static void Win32BuildExePathFileName( win32State_t *state, char *filename, int destCount, char *dest ) {
	CatStrings( state->onePastLastExeFileNameSlash - state->filename, state->filename, StringLength( filename ), filename, destCount, dest );
}
Exemplo n.º 30
0
static
void aws_parse_file ( const KFile *self, KConfigNode *aws_node, 
                      char *buffer, size_t buf_size, bool isCredentialsFile )
{
    char *sep;
    const char *start = buffer;
    const char *end = start + buf_size;

    for ( ; start < end; start = sep + 1 )
    {
        rc_t rc;
        String string, trim;
        String key, value;
        
        sep = string_chr ( start, end - start, '\n' );
        if ( sep == NULL )
            sep = ( char * ) end;

        StringInit ( &string, start, sep - start, string_len ( start, sep - start ) );
        
        StringTrim ( &string, &trim );

        /* check for comment line and skip */
        if ( StringLength ( & trim ) != 0 && trim . addr [ 0 ] == '#' )
            continue;

        /* check for [default] line */
        if ( StringLength ( & trim ) != 0 && trim . addr [ 0 ] == '[' )
            continue;

        /* check for key/value pairs and skip if none found */
        rc = aws_extract_key_value_pair ( &trim, &key, &value );
        if ( rc != 0 )
            continue;

        /* now check keys we are looking for and populate the node*/
        if ( isCredentialsFile )
        {
            String access_key_id, secret_access_key;
            CONST_STRING ( &access_key_id, "aws_access_key_id" );
            CONST_STRING ( &secret_access_key, "aws_secret_access_key" );

            if ( StringCaseEqual ( &key, &access_key_id ) )
            {
                rc = aws_KConfigNodeUpdateChild ( aws_node, &key, &value );
                if ( rc != 0 )
                    return;
            }
            if ( StringCaseEqual ( &key, &secret_access_key  ) )
            {
                rc = aws_KConfigNodeUpdateChild ( aws_node, &key, &value );
                if ( rc != 0 )
                    return;
            }
        }
        else
        {
            String region, output;
            CONST_STRING ( &region, "region" );
            CONST_STRING ( &output, "output" );

            if ( StringCaseEqual ( &key, &region ) )
            {
                rc = aws_KConfigNodeUpdateChild ( aws_node, &key, &value );
                if ( rc != 0 )
                    return;
            }
            if ( StringCaseEqual ( &key, &output  ) )
            {
                rc = aws_KConfigNodeUpdateChild ( aws_node, &key, &value );
                if ( rc != 0 )
                    return;
            }
        }
    }
}