Пример #1
0
static void
get_cats(char *cat1, char *cat2)
{
	QE *qp;
	int i;
	const char *s;

	downcase(cat1);
	downcase(cat2);
	for (qp = qlist.q_next; qp; qp = qp->q_next) {
		s = next_cat(qp->q_text);
		catone = cattwo = i = 0;
		while (s) {
			if (!rxp_compile(s))
				errx(1, "%s", rxperr);
			i++;
			if (rxp_match(cat1))
				catone = i;
			if (rxp_match(cat2))
				cattwo = i;
			s = next_cat(s);
		}
		if (catone && cattwo && catone != cattwo) {
			if (!rxp_compile(qp->q_text))
				errx(1, "%s", rxperr);
			get_file(rxp_expand());
			return;
		}
	}
	errx(1, "invalid categories");
}
Пример #2
0
// Return ID in `fortranized' form -- that is, in lower/upper case and
// with appended `_'.  If GLOBALS_FIRST is set, try global symbols first.
static string _fortranize(const string& id, bool globals_first)
{
    if (globals_first)
    {
	// Try global identifier first.
	string global_id = _fortranize_globals(id);
	if (global_id != id)
	    return global_id;
    }

    // Try identifier as given.
    if (is_valid(gdbValue(id), gdb))
	return id;

    // Try in lower-case.  g77 does this for local objects.
    if (is_valid(gdbValue(downcase(id)), gdb))
	return downcase(id);

    // Try in upper-case.  f77 does this for local objects.
    if (is_valid(gdbValue(upcase(id)), gdb))
	return upcase(id);

    // Try global objects.
    return _fortranize_globals(id);
}
Пример #3
0
// True if COND is `false' or starts with `false and'
bool BreakPoint::is_false(const string& cond)
{
    if (cond == false_value())
	return true;

    const string c = downcase(cond);
    const string prefix = downcase(false_value() + and_op());

    return c.contains(prefix, 0);
}
Пример #4
0
static int
CompareImpl(const char *p1, const char *p2, int nocase)
{
    const int len1 = Next(p1) - p1;
    const int len2 = Next(p2) - p2;
#ifdef _WIN32
    char buf1[10], buf2[10]; /* large enough? */
#endif

    if (len1 < 0 || len2 < 0) {
	rb_fatal("CompareImpl: negative len");
    }

    if (len1 == 0) return  len2;
    if (len2 == 0) return -len1;

#ifdef _WIN32
    if (nocase && rb_w32_iswinnt()) {
	if (len1 > 1) {
	    if (len1 >= sizeof(buf1)) {
		rb_fatal("CompareImpl: too large len");
	    }
	    memcpy(buf1, p1, len1);
	    buf1[len1] = '\0';
	    CharLower(buf1);
	    p1 = buf1; /* trick */
	}
	if (len2 > 1) {
	    if (len2 >= sizeof(buf2)) {
		rb_fatal("CompareImpl: too large len");
	    }
	    memcpy(buf2, p2, len2);
	    buf2[len2] = '\0';
	    CharLower(buf2);
	    p2 = buf2; /* trick */
	}
    }
#endif
    if (len1 == 1)
	if (len2 == 1)
	    return compare(downcase(*p1), downcase(*p2));
	else {
	    const int ret = compare(downcase(*p1), *p2);
	    return ret ? ret : -1;
	}
    else
	if (len2 == 1) {
	    const int ret = compare(*p1, downcase(*p2));
	    return ret ? ret : 1;
	}
	else {
	    const int ret = memcmp(p1, p2, len1 < len2 ? len1 : len2);
	    return ret ? ret : len1 - len2;
	}
}
Пример #5
0
static int memieq(const void *a, const void *b, size_t n) {
  size_t i;
  const uint8_t *aa = a, *bb = b;

  for (i = 0; i < n; ++i) {
    if (downcase(aa[i]) != downcase(bb[i])) {
      return 0;
    }
  }
  return 1;
}
Пример #6
0
/*	findStudent
	routine to find a student (by last name)
	in:  none
	out: none
*/
void findStudent()
{
	// declarations
	int i = 0;					// loop counter
	char *findLastName;			// last name to search
	char *lastName;				// holds "current" student last name in loop
	int found[MAX_STUDENTS];	// array to store indices of found students
	int numFound = 0;			// # of students found
	
	// print header
	printf("FIND STUDENT BY LAST NAME\n\n");
	
	// loop until user quits
	do {
		numFound = 0;		// reset # found to 0
		
		// input last name and convert to lowercase
		findLastName = downcase(inputString("Enter partial or entire last name: ", 32));
		printf("\n\nSearching ... ");
		
		// loop through all student records
		for (i = 0; i < numStudents; i++)
		{
			// set lastName to lowercase of "current" student last name
			lastName = downcase(students[i].lastName);
			
			// if the student last name *contains* the text the user entered
			if (strstr(lastName, findLastName) != NULL)
			{
				found[numFound] = i;	// add student to found students array
				numFound ++;	// increment counter
			}
		}
		// if we didn't find any
		if (numFound == 0) printf("No matches found.\n");
		
		else	// we did find at least one
		{
			// print # students found
			printf("Found %d students:\n\n", numFound);
			
			// loop through found students & print each
			for (i = 0; i < numFound; i++)
			{
				printStudent(&students[found[i]]);
				printf("\n");
			}
		}
		
		// ask user for another search
	} while (confirm("Find another (y/n) ? "));
}
Пример #7
0
int strncasecmp(char* a, char* b, int n) {
  /* why isn't this in string library??? */
  char* copya; char* copyb; int retval;
  copya = malloc(1+strlen(a));
  strcpy(copya, a);
  downcase(copya);
  copyb = malloc(1+strlen(b));
  strcpy(copyb,b);
  downcase(copyb);
  retval=strncmp(copya, copyb, n);
  free(copya); free(copyb);
  return(retval);
}
Пример #8
0
static int parse_html_tag (char **start, char *end)
{
  int result = -1;
  char *token = NULL;
  int closing = 0;
  skip_white(start, end);
  if (*start < end) {
    if (**start == '/') {
      (*start)++;
      closing = 1;
    }
    if (*start < end && (token = parse_ident (start, end))) {
      downcase (token);
      {
	int i;
	for (i=0; i<sizeof(tags)/sizeof(tags[0]); i++) {
	  if (!strcmp (token, tags[i])) {
	    result = i;
	    if (closing) 
	      result += sizeof(tags)/sizeof(tags[0]);
	  }
	  break;
	}
	if (i>=sizeof(tags)/sizeof(tags[0]))
	  result = -1;
      }
      RELEASE (token);
    }
  }
  return result;
}
Пример #9
0
static void cmpDecompile(char *Output, char *Input) {
  char Tmp[1024], Name[256];
  u1 Hash[256], Key[256], ArName[128]; 
  int I, J, K, C, Off, Len, NFiles, L;
  u1 *M, *Q, *Z;

  pathParts(0, ArName, 0, Input);

  downcase(ArName);

  if (!strcmp(ArName, "magic")
   || !strcmp(ArName, "treasure")
   || !strcmp(ArName, "status")
   || !strcmp(ArName, "itemgen")
   || !strcmp(ArName, "mono")
   || !strcmp(ArName, "text")) {
    printf("  not an archive CMP\n");
    abort();
  }

  Q = M = readFile(0, 1<<20, Input);
  NFiles = ru4(Q);

  //printf("  NFiles=%d\n", NFiles);
  times (K, NFiles) {
    C = ru4(Q);
    
    times(I, C) {
      Name[I] = *Q++ ^ CmpKey[I%32];
      if (Name[I]=='\\') Name[I] = '/';
    }
Пример #10
0
// Return ID in `fortranized' form -- that is, in lower/upper case and
// with `_' suffix.
static string _fortranize_globals(const string& id)
{
    if (!id.contains('_', -1))
    {
	// 1. Try `_'  postfix, lower-case.  Global objects in g77.
	// 2. Try `__' postfix, lower-case.  In g77, if the name contains `_'.
	// 3. Try `_'  postfix, upper-case.  Global objects in f77.
	// 4. Try `__' postfix, upper-case.  In f77?

	for (int caps = 0; caps < 2; caps++)
	{
	    string new_id = caps ? upcase(id) : downcase(id);
	    
	    for (int suffix_length = 1; suffix_length < 3; suffix_length++)
	    {
		new_id += '_';
		if (is_valid(gdbValue(new_id), gdb))
		    return new_id;
	    }
	}
    }

    // Don't know what to try next - use as given
    return id;
}
Пример #11
0
int  lookup_resolve( const char *str )
{
    char *buf = strdup( str );
    int ret;

    downcase( buf );
    if ( strcmp( buf, "both" ) == 0 )
        ret = RESOLVE_BOTH;
    else if ( strcmp( buf, "remote" ) == 0 )
        ret = RESOLVE_REMOTE;
    else if ( strcmp( buf, "local" ) == 0 )
        ret = RESOLVE_LOCAL;
    else if ( strspn(buf, dotdigits) == strlen(buf) ) {
#ifndef WITH_RESOLVER
        g_error("Sorry, you can't specify to resolve the hostname with the -R option on Win32 environment.");
#endif 
        ret = RESOLVE_LOCAL;                  
        socks_ns.sin_addr.s_addr = inet_addr(buf);
        socks_ns.sin_family = AF_INET;
    }
    else
        ret = RESOLVE_UNKNOWN;
    free(buf);
    return ret;
}
Пример #12
0
int  is_direct_name (const char *name)
{
    int len, i;
    g_debug("checking %s is for direct?\n", name);
    name = downcase(strdup(name));
    len = strlen(name);
    if (len < 1)
        return 0;                             
    for (i=0; i<n_direct_addr_list; i++ ) {
        int neg;
        const char *dname;
        dname = direct_addr_list[i].name;
        if (dname == NULL)
            continue;                          
        neg = direct_addr_list[i].negative;
        if (domain_match(name, dname)) {
            //debug("match with: %s%s\n", dname, neg? " (negative)": "");
            if (neg) {
                return 0;      
            } else {
                return 1;      
            }
        }
    }
    return 0;                               
}
Пример #13
0
// Convert String to Pixmap (using XmGetPixmap)
// A Pixmap will be read in as bitmap file
// 1 and 0 values are set according to the widget's 
// foreground/background colors.
static Boolean CvtStringToPixmap(Display *display, 
				 XrmValue *args, Cardinal *num_args, 
				 XrmValue *fromVal, XrmValue *toVal,
				 XtPointer *)
{
    // Default parameters
    Screen *screen   = DefaultScreenOfDisplay(display);
    Pixel background = WhitePixelOfScreen(screen);
    Pixel foreground = BlackPixelOfScreen(screen);

    if (*num_args >= 1)
    {
	// convert first arg into widget
	Widget w = *(Widget *) args[0].addr;
	background = w->core.background_pixel;
	
	screen = XtScreen(w);
	
	if (XtIsWidget(w) && XmIsPrimitive(w))
	{
	    // Get foreground color from widget
	    foreground = XmPrimitiveWidget(w)->primitive.foreground;
	}
	else
	{
	    // Ask Motif for a default foreground color
	    Pixel newfg, newtop, newbot, newselect;
	    XmGetColors(screen, w->core.colormap, background,
			&newfg, &newtop, &newbot, &newselect);
	    foreground = newfg;
	}
    }

    // Get pixmap
    Pixmap p = XmUNSPECIFIED_PIXMAP;

    string value = str(fromVal, false);

    // Some Motif versions use `unspecified_pixmap' and `unspecified pixmap'
    // as values for XmUNSPECIFIED_PIXMAP.  Check for this.
    string v = downcase(value);
    v.gsub(" ", "_");
    if (v.contains("xm", 0))
	v = v.after("xm");
    if (v != "unspecified_pixmap")
    {
	p = XmGetPixmap(screen, XMST(value.chars()), foreground, background);

	if (p == XmUNSPECIFIED_PIXMAP)
	{
	    XtDisplayStringConversionWarning(display, fromVal->addr, 
					     XmRPixmap);
	    return False;
	}
    }

    done(Pixmap, p);
}
Пример #14
0
bool TST::searchr(TSTp p,string *s, unsigned int pos) {
  if(!p || s->empty()) return false;
  char c = downcase(pos < s->length() ? s->at(pos) : 0);
  if(c < p->val)
    return searchr(p->left,s,pos);
  else if(c > p->val)
    return searchr(p->right,s,pos);
  else {
    if(c==0) return true;
    return searchr(p->middle,s,pos+1);
  }
}
Пример #15
0
void TST::searchp(TSTp p,string *s, unsigned int pos, list_t *output) {
  if(!p || s->empty()) return;
  char c = downcase(pos < s->length() ? s->at(pos) : 0);
  if(c < p->val)
    searchp(p->left,s,pos,output);
  else if(c > p->val)
    searchp(p->right,s,pos,output);
  else {
    if(pos==s->length()-1)
      sort(p->middle,output);
    searchp(p->middle,s,pos+1,output);
  }
}
Пример #16
0
char* uname(void) {
#ifdef __CYGWIN__
  return q("windows");
#endif
#ifndef HAVE_WINDOWS_H
  char *p=system_("uname");
  char *p2;
  p2=remove_char("\r\n",p);
  s(p);
  return downcase(p2);
#else
  return q("windows");
#endif
}
Пример #17
0
void TST::searchh(TSTp p, string *s, unsigned int pos, int d, list_t *output) {
  if(!p || d<0) return;
  char c = downcase(pos < s->length() ? s->at(pos) : 0);
  if(d>0 || c < p->val)
    searchh(p->left,s,pos,d,output);
  if(p->val == 0) {
    // if( s->length()-pos <= d)
    if(pos >= s->length()) // no shorter words
      output->push_back(*p->data);
  }
  else
    searchh(p->middle,s,c ? pos+1:pos, (c==p->val) ? d:d-1,output);
  if(d>0 || c > p->val)
    searchh(p->right,s,pos,d,output);
}
Пример #18
0
// Return ID in `fortranized' form -- that is, in lower/upper case and
// with `_' appended.  If GLOBALS_FIRST is set, try global symbols
// first.  In case of pointers, dereference automatically.
string fortranize(const string& id, bool globals_first)
{
    if (gdb->program_language() != LANGUAGE_FORTRAN)
	return id;
    if (!id.matches(rxidentifier))
	return id;

    string name  = _fortranize(id, globals_first);
    string value = gdbValue(name);

    // Dereference pointers automatically.
    // GDB issues `(PTR TO -> ( integer )) 0x2290'
    if (is_valid(value, gdb) && 
	downcase(value).contains("ptr to") && 
	!value.contains("0x0", -1))
	return deref(name);
    else
	return name;
}
Пример #19
0
static size_t header_callback(char *buffer, size_t size,size_t nitems, int *opt) {
  int pos=-1,pos2,code=0;
  if(strncmp("HTTP",buffer,nitems<4?nitems:4)==0) {
    pos=position_char(" ",buffer);
    if(pos!=-1 && (pos2=position_char_not("0123456789",&buffer[pos+1]))!=-1) {
      char *num=subseq(&buffer[pos+1],0,pos2);
      code=atoi(num),s(num);
      if(verbose)
        fprintf(c_out, "http response:%d\n",code);
    }
    if(400<=code)
      return 0; /*invoke error for curl*/
  }else if(strncmp("content-length:",downcase(buffer),nitems<15?nitems:15)==0) {
    pos=position_char(" ",buffer);
    if(pos!=-1 && (pos2=position_char_not("0123456789",&buffer[pos+1]))!=-1) {
      char *num=subseq(&buffer[pos+1],0,pos2);
      code=atoi(num),s(num);
      content_length=code;
    }
  }
  return nitems * size;
}
Пример #20
0
int main (void) {
    cout << __FILE__ << endl;
  CoolString s1 = "Hello";                      // Create CoolString object
  cout << "s1 reads: " << s1 << "\n";           // Display CoolString value
  cout << "s1 has " << strlen (s1) << " characters\n"; // Display char count
  s1 = s1 + " " + "world!";                            // Concatenate characters
  cout << "s1 reads: " << s1 << "\n";                  // Display CoolString value
  cout << "s1 has " << strlen (s1) << " characters\n"; // Display char count
  s1.reverse ();                                       // Reverse character order
  cout << "s1 backwards reads: " << s1 << "\n";        // Output reversed CoolString
  s1.reverse ();                                       // Get normal ordering back
  cout << "s1 upper case: " << upcase (s1) << "\n";    // Display uppercase value
  cout << "s1 lower case: " << downcase (s1) << "\n";  // Display downcase value
  cout << "s1 capitalized: " << capitalize (s1) << "\n"; // Display capitalized value
  s1.insert ("Oh, ", 0);                                 // Insert at start of CoolString
  cout << "s1 reads: " << s1 << "\n";                    // Display CoolString value
  s1.replace ("Goodbye", 4, 9);                          // Replace `hello' with `goodbye'
  cout << "s1 reads: " << s1 << "\n";                    // Display CoolString value
  s1.remove (4, 12);                                     // Remove `goodbye'
  cout << "s1 reads: " << s1 << "\n";                    // Display CoolString value
  return (0);                                            // Exit with OK status
}
Пример #21
0
void User::load(struct passwd *entry)
{
    if (entry) {
        exists_ = true;
        id_ = entry->pw_uid;
        groupId_ = entry->pw_gid;
        loginName_ = entry->pw_name;
        fullName_ = entry->pw_gecos;
        if (fullName_->count() > 0)
            if ((fullName_->at(0) == ',') || (fullName_->at(fullName_->count() - 1) == ',')) {
                fullName_ = loginName_->copy();
                if (isLower(fullName_->at(0)))
                    fullName_->at(0) = downcase(fullName_->at(0));
                // fullName_ << " Anonymous";
            }
        home_ = entry->pw_dir;
        shell_ = entry->pw_shell;
    }
    else {
        exists_ = false;
        id_ = 0;
        groupId_ = 0;
    }
}
Пример #22
0
static PlotWindowInfo *new_decoration(const string& name)
{
    PlotWindowInfo *plot = 0;

    // Check whether we can reuse an existing decoration
    for (int i = 0; i < plot_infos.size(); i++)
    {
	PlotWindowInfo *info = (PlotWindowInfo *)plot_infos[i];
	if (info->plotter == 0)
	{
	    // Shell is unused - use this one
	    plot = info;
	    break;
	}
    }

    if (plot == 0)
    {
	plot = new PlotWindowInfo;

	// Create decoration windows
	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNallowShellResize, True);       arg++;
	XtSetArg(args[arg], XmNdeleteResponse, XmDO_NOTHING); arg++;

	// Mark shell as `used'
	XtSetArg(args[arg], XmNuserData, XtPointer(True)); arg++;
	plot->shell = verify(XtCreateWidget("plot", topLevelShellWidgetClass,
					    find_shell(), args, arg));

	AddDeleteWindowCallback(plot->shell, CancelPlotCB, XtPointer(plot));

	arg = 0;
	Widget main_window = XmCreateMainWindow(plot->shell, 
						XMST("main_window"), 
						args, arg);
	XtManageChild(main_window);

	MMcreateMenuBar(main_window, "menubar", menubar);
	MMaddCallbacks(file_menu,    XtPointer(plot));
	MMaddCallbacks(simple_edit_menu);
	MMaddCallbacks(view_menu,    XtPointer(plot));
	MMaddCallbacks(plot_menu,    XtPointer(plot));
	MMaddCallbacks(scale_menu,   XtPointer(plot));
	MMaddCallbacks(contour_menu, XtPointer(plot));
	MMaddCallbacks(simple_help_menu);
	MMaddHelpCallback(menubar, ImmediateHelpCB);

	arg = 0;
	XtSetArg(args[arg], XmNscrollingPolicy, XmAPPLICATION_DEFINED); arg++;
	XtSetArg(args[arg], XmNvisualPolicy,    XmVARIABLE);            arg++;
	Widget scroll = 
	    XmCreateScrolledWindow(main_window, XMST("scroll"), args, arg);
	XtManageChild(scroll);

	// Create work window
	Widget work;
	string plot_term_type = downcase(app_data.plot_term_type);
	if (plot_term_type.contains("xlib", 0))
	{
	    // xlib type - create plot area to draw plot commands
	    arg = 0;
	    work = XmCreateDrawingArea(scroll, 
				       XMST(PLOT_AREA_NAME), args, arg);
	    XtManageChild(work);

	    plot->area = 
		new PlotArea(work, make_font(app_data, FixedWidthDDDFont));
	    XtVaSetValues(work, XmNuserData, XtPointer(plot->area), 
			  XtPointer(0));
	}
	else if (plot_term_type.contains("x11", 0))
	{
	    // x11 type - swallow Gnuplot window
	    arg = 0;
	    work = plot->swallower = 
		XtCreateManagedWidget(SWALLOWER_NAME, swallowerWidgetClass, 
				      scroll, args, arg);
	}
	else
	{
	    // Unknown terminal type
	    post_error("Unknown plot terminal type " + 
		       quote(app_data.plot_term_type),
		       "unknown_plot_term_type_error");
	    return 0;
	}

	// Create scroll bars
	const int slider_size = 20;

	arg = 0;
	XtSetArg(args[arg], XmNorientation, XmHORIZONTAL);      arg++;
	XtSetArg(args[arg], XmNminimum,     0);                 arg++;
	XtSetArg(args[arg], XmNmaximum,     360 + slider_size); arg++;
	plot->hsb = XmCreateScrollBar(scroll, XMST("hsb"), args, arg);
	XtManageChild(plot->hsb);

	arg = 0;
	XtSetArg(args[arg], XmNorientation, XmVERTICAL);        arg++;
	XtSetArg(args[arg], XmNminimum,     0);                 arg++;
	XtSetArg(args[arg], XmNmaximum,     180 + slider_size); arg++;
	plot->vsb = XmCreateScrollBar(scroll, XMST("vsb"), args, arg);
	XtManageChild(plot->vsb);

	XtAddCallback(plot->hsb, XmNvalueChangedCallback,
		      SetViewCB, XtPointer(plot));
	XtAddCallback(plot->vsb, XmNvalueChangedCallback,
		      SetViewCB, XtPointer(plot));

#if 0
	XtAddCallback(plot->hsb, XmNdragCallback, SetViewCB, XtPointer(plot));
	XtAddCallback(plot->vsb, XmNdragCallback, SetViewCB, XtPointer(plot));
#endif

	XmScrolledWindowSetAreas(scroll, plot->hsb, plot->vsb, work);

	Delay::register_shell(plot->shell);
	InstallButtonTips(plot->shell);

	plot_infos += plot;
    }

    string title = DDD_NAME ": " + name;
    XtVaSetValues(plot->shell,
		  XmNtitle, title.chars(),
		  XmNiconName, title.chars(),
		  XtPointer(0));

    if (plot->swallower != 0)
    {
	XtRemoveAllCallbacks(plot->swallower, XtNwindowCreatedCallback);
	XtAddCallback(plot->swallower, XtNwindowCreatedCallback,
		      SwallowCB, XtPointer(plot));

	XtRemoveAllCallbacks(plot->swallower, XtNwindowGoneCallback);
	XtAddCallback(plot->swallower, XtNwindowGoneCallback, 
		      SwallowAgainCB, XtPointer(plot));

	if (plot->swallow_timer != 0)
	    XtRemoveTimeOut(plot->swallow_timer);

	plot->swallow_timer = 
	    XtAppAddTimeOut(XtWidgetToApplicationContext(plot->swallower),
			    app_data.plot_window_delay, SwallowTimeOutCB, 
			    XtPointer(plot));
    }

    plot->active = false;

    return plot;
}
Пример #23
0
void relations_convert_open(database db) {
/* relations_open
 * Load all of the relations in the specified database
 */
	boolean masterdb;
	DIR *directory;
	char dirpath[FILE_PATH_SIZE+1];
	char newdir[FILE_PATH_SIZE+1],ddname[FILE_PATH_SIZE+1];
	mode_t mode;
	tuple nt;
	relation ddrel;
	struct dirent *d;
	relation rel;

	masterdb=(strcmp(database_name(db),MASTER_DB_NAME)==0);

	leap_fprintf(stdout,"Converting database [%s] ",database_name(db));
	if (masterdb==TRUE) {
		leap_printf("(Master Database)\n");
	} else {
		leap_printf("(User Database)\n");
	}

	sprintf(dirpath,"%s%s",database_dir(db),LEAP_RELATION_DIR);
	directory=opendir(dirpath);
		
		if (directory!=NULL) {

			/* Create a backup directory for the old format
			 * relations.
			 */

			mode=sprintf(newdir,"%soldfmt",dirpath);
			mkdir(newdir,0777);
		
			d=readdir(directory);

			while (d!=NULL) {

#ifdef __MSDOS__
				/* See comment in util.c for list_source
				 * DOS filenames are always in capitals.
				 */
				downcase(d->d_name);
#endif

					if (strstr(d->d_name,LEAP_RELATION_EXT)!=NULL) {
						/* Read the relation from the disk */
						rel=relation_read(dirpath,d->d_name);
						/* Insert the relation into the database */
						relation_insert(db,rel);
					}

					d=readdir(directory);
				}		

			/* Close the directory */
			closedir(directory);
	}

	leap_fprintf(stdout,"Completed conversion of [%s]\n",database_name(db));
	
	leap_fprintf(stdout,"Updating [%s]...",LEAP_DD_RELATIONS);
	fflush(stdout);

	/* Open the leaprel database */
	sprintf(dirpath,"%s%s",database_dir(db),LEAP_RELATION_DIR);
	sprintf(ddname,"%s%s",LEAP_DD_RELATIONS,LEAP_NEW_RELATION_EXT);
	ddrel=relation_new_read(dirpath,ddname);

	/* Did the relation get returned? */
	if (ddrel!=NULL) {
	
		/* Prepare a tuple */
		nt=tuple_prepare(ddrel);
		
		/* Find the first relation in the database */
		rel=relation_findfirst(db);
		
		/* Whilst a relation is being returned */
		while( (rel!=NULL) && (strlen(relation_name(rel))>=0) ){

			/* TODO: Why does the relation name sometimes have nothing in it? */
		
			/* Populate the output tuple */
			
			/* Relation name */
			strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_NAME_NO),relation_name(rel));
			
			/* Relation filename */
			sprintf(tuple_d(nt,LEAP_DDA_RELATIONS_FNAME_NO), "%s%s", relation_name(rel), LEAP_NEW_RELATION_EXT);
			
			/* Temporary status */
			if ( relation_temporary(rel) ) {
				strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_TEMP_NO),TRUE_STRING);
			} else {
				strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_TEMP_NO),FALSE_STRING);
			}

			/* Noattributes status */
			strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_NOATTRIBS_NO),"1");
			
			/* Updated status */
			strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_UPDATED_NO),FALSE_STRING);
			
			/* System relation status */			
			if ( relation_system(rel) ) {
				strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_SYSTEM_NO),TRUE_STRING);
			} else {
				strcpy( tuple_d(nt,LEAP_DDA_RELATIONS_SYSTEM_NO),FALSE_STRING);
			}
		
			/* Write the tuple */
			(void)tuple_append(nt);
	
			/* Read the next relation */
			rel=relation_findnext(rel);
		}
		
		/* Dispose of the output tuple */
		tuple_dispose(&nt);
	} else {
		leap_fprintf(stderr,"\nERROR: System relation [%s] does not exist. See release NOTES\nin base directory!\n",
			LEAP_DD_RELATIONS);
		exit(1);
	}
	
	leap_fprintf(stdout,"Completed conversion.\n");
}
Пример #24
0
long
pty_make_sane_hostname(const struct sockaddr *addr, int maxlen,
		       int strip_ldomain, int always_ipaddr, char **out)
{
    struct addrinfo *ai = 0;
    char addrbuf[NI_MAXHOST];
#ifdef HAVE_STRUCT_UTMP_UT_HOST
    struct utmp ut;
#else
    struct utmpx utx;
#endif
    char *cp, *domain;
    char lhost[MAXHOSTNAMELEN];
    size_t ut_host_len;

    /* Note that on some systems (e.g., AIX 4.3.3), we may get an IPv6
       address such as ::FFFF:18.18.1.71 when an IPv4 connection comes
       in.  That's okay; at least on AIX, getnameinfo will deal with
       that properly.  */

    *out = NULL;
    if (maxlen && maxlen < 16)
	/* assume they meant 16, otherwise IPv4 addr won't fit */
	maxlen = 16;
#ifdef HAVE_STRUCT_UTMP_UT_HOST
    ut_host_len = sizeof (ut.ut_host);
#else
    ut_host_len = sizeof (utx.ut_host);
#endif
    if (maxlen == 0)
	maxlen = ut_host_len;
    *out = malloc(ut_host_len);
    if (*out == NULL)
	return ENOMEM;

    if (always_ipaddr) {
    use_ipaddr:
	if (getnameinfo (addr, socklen (addr), addrbuf, sizeof (addrbuf),
			 (char *)0, 0, NI_NUMERICHOST) == 0)
	    strncpy(*out, addrbuf, ut_host_len);
	else
	    strncpy(*out, "??", ut_host_len);
	(*out)[ut_host_len - 1] = '\0';
	return 0;
    }

    /* If we didn't want to chop off the local domain, this would be
       much simpler -- just a single getnameinfo call and a strncpy.  */
    if (getnameinfo(addr, socklen (addr), addrbuf, sizeof (addrbuf),
		    (char *) NULL, 0, NI_NAMEREQD) != 0)
	goto use_ipaddr;
    downcase (addrbuf);
    if (strip_ldomain) {
	struct addrinfo hints;
	(void) gethostname(lhost, sizeof (lhost));
	memset (&hints, 0, sizeof (hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_flags = AI_CANONNAME;
	if (getaddrinfo(lhost, (char *)NULL, &hints, &ai) == 0
	    && ai != NULL) {
		if (ai->ai_canonname != NULL) {
			downcase (ai->ai_canonname);
			domain = strchr (ai->ai_canonname, '.');
			if (domain != NULL) {
				cp = strstr (addrbuf, domain);
				if (cp != NULL)
					*cp = '\0';
			}
		}
		freeaddrinfo (ai);
	}
    }
    strncpy(*out, addrbuf, ut_host_len);
    (*out)[ut_host_len - 1] = '\0';
    if (strlen(*out) >= maxlen)
	goto use_ipaddr;
    return 0;
}
Пример #25
0
static void
quiz(void)
{
	QE *qp;
	int i;
	size_t len;
	unsigned guesses, rights, wrongs;
	unsigned next, j;
	char *answer, *t, question[LINE_SZ];
	const char *s;

	srandom(time(NULL));
	guesses = rights = wrongs = 0;
	for (;;) {
		if (qsize == 0)
			break;
		next = random() % qsize;
		qp = qlist.q_next;
		for (j = 0; j < next; j++)
			qp = qp->q_next;
		while (qp && qp->q_answered)
			qp = qp->q_next;
		if (!qp) {
			qsize = next;
			continue;
		}
		if (tflag && random() % 100 > 20) {
			/* repeat questions in tutorial mode */
			while (qp && (!qp->q_asked || qp->q_answered))
				qp = qp->q_next;
			if (!qp)
				continue;
		}
		s = qp->q_text;
		for (i = 0; i < catone - 1; i++)
			s = next_cat(s);
		if (!rxp_compile(s))
			errx(1, "%s", rxperr);
		t = rxp_expand();
		if (!t || *t == '\0') {
			qp->q_answered = TRUE;
			continue;
		}
		(void)strcpy(question, t);
		s = qp->q_text;
		for (i = 0; i < cattwo - 1; i++)
			s = next_cat(s);
		if (!rxp_compile(s))
			errx(1, "%s", rxperr);
		t = rxp_expand();
		if (!t || *t == '\0') {
			qp->q_answered = TRUE;
			continue;
		}
		qp->q_asked = TRUE;
		(void)printf("%s?\n", question);
		for (;; ++guesses) {
			if ((answer = fgetln(stdin, &len)) == NULL ||
			    answer[len - 1] != '\n') {
				score(rights, wrongs, guesses);
				exit(0);
			}
			answer[len - 1] = '\0';
			downcase(answer);
			if (rxp_match(answer)) {
				(void)printf("Right!\n");
				++rights;
				qp->q_answered = TRUE;
				break;
			}
			if (*answer == '\0') {
				(void)printf("%s\n", t);
				++wrongs;
				if (!tflag)
					qp->q_answered = TRUE;
				break;
			}
			(void)printf("What?\n");
		}
	}
	score(rights, wrongs, guesses);
}
Пример #26
0
int begin_http_relay( SOCKET s )
{
    char buf[1024];
    int result;
    char *auth_what;

    g_debug("begin_http_relay()\n");

    if (sendf(s,"CONNECT %s:%d HTTP/1.0\r\n", dest_host, dest_port) < 0)
        return START_ERROR;
    
    if (proxy_auth_type == PROXY_AUTH_BASIC   && basic_auth (s)  < 0) 
      return START_ERROR;
    
    if (sendf(s,"\r\n") < 0)
        return START_ERROR;

    
    if ( line_input(s, buf, sizeof(buf)) < 0 ) {
        g_debug("failed to read http response.\n");
        return START_ERROR;
    }

   
    if (!strchr(buf, ' ')) {
        g_error ("Unexpected http response: '%s'.\n", buf);
        return START_ERROR;
    }
    result = atoi(strchr(buf,' '));

    switch ( result ) {
        case 200:
         
            g_debug("connected, start user session.\n");
            break;
        case 302:                                  
            do {
                if (line_input(s, buf, sizeof(buf)))
                    break;
                downcase(buf);
                if (expect(buf, "Location: ")) {
                    relay_host = cut_token(buf, "//");
                    cut_token(buf, "/");
                    relay_port = atoi(cut_token(buf, ":"));
                }
            } while (strcmp(buf,"\r\n") != 0);
            return START_RETRY;

           
        case 401:                                   
        case 407:                                  
            /*TODO - authentication*/
            if (proxy_auth_type != PROXY_AUTH_NONE) {
                g_error("Authentication failed.\n");
                return START_ERROR;
            }
            auth_what = (result == 401) ? "WWW-Authenticate:" : "Proxy-Authenticate:";
            do {
                if ( line_input(s, buf, sizeof(buf)) ) {
                    break;
                }
                downcase(buf);
                if (expect(buf, auth_what)) {
                  
                    char *scheme, *realm;
                    scheme = cut_token(buf, " ");
                    realm = cut_token(scheme, " ");
                    if ( scheme == NULL || realm == NULL ) {
                        g_debug("Invalid format of %s field.", auth_what);
                        return START_ERROR;        
                    }
                   
                    if (expect(scheme, "basic")) {
                        proxy_auth_type = PROXY_AUTH_BASIC;
                    } else {
                        g_debug("Unsupported authentication type: %s", scheme);
                    }
                }
            } while (strcmp(buf,"\r\n") != 0);
            if ( proxy_auth_type == PROXY_AUTH_NONE ) {
                g_debug("Can't find %s in response header.", auth_what);
                return START_ERROR;
            } else {
                return START_RETRY;
            }

        default:
            g_debug("http proxy is not allowed.\n");
            return START_ERROR;
    }
  
    do {
        if ( line_input(s, buf, sizeof(buf) ) ) {
            g_debug("Can't skip response headers\n");
            return START_ERROR;
        }
    } while ( strcmp(buf,"\r\n") != 0 );

    return START_OK;
}
Пример #27
0
void LibRnrsUnicode::StringDowncase::func(KevesVM* vm, const_KevesIterator pc) {
  const StringKev* original(vm->acc_);
  StringKev downcase(original->toLower(vm->gc()));
  vm->acc_ = &downcase;
  return KevesVM::returnValueSafe(vm, pc);
}
Пример #28
0
int validarUsuarioMensaje(char *mensaje, DatosUsuario * datosUsuario, DatosConfig *configuracion){
  int i = 0, valido = 0, fd = 0, linea = 0, lineaActual = 0;
  char * comando = strtok(mensaje, " ");
  char * usuarioMensaje = strtok(NULL, " ");
  char * passwordMensaje = strtok(NULL, " ");
  char *token, *usuario, *password;
  char lineas[100][100];  
  char buffer[512];

  /********INICIALIZAR*****/
  memset(lineas, 0, sizeof lineas);
  memset(buffer, 0, sizeof buffer);
  /************************/

  trimwhitespace(passwordMensaje);
  downcase(usuarioMensaje);
  downcase(comando);
  
  /*********CERRAR CONEXION SI EL COMANDO NO EXISTE*********/
  if(strcmp(comando, "pull") != 0 && strcmp(comando, "status") != 0){
    return -1;
  }
  
  /*************ARMAR UN ARRAY CON CADA LINEA DEL ARCHIVO CFG***********/
  char * aux = (char *)malloc(strlen(configuracion->dbUsuarios) * sizeof(char));
  memset(aux, 0, strlen(configuracion->dbUsuarios)* sizeof(char));

  strcpy(aux, configuracion->dbUsuarios);

  if((token = strtok(aux, "\n")) == NULL){
    write(1,"Error archivo de configuracion\n",31);
    return -1;
  }

  strcpy(lineas[lineaActual], token);
  
  while((token = strtok(NULL,"\n")) != NULL){
    lineaActual++;
    strcpy(lineas[lineaActual], token);
  }

  /*************BUSCAR COINCIDENCIA DE USUARIO - PASSWORD***************/
  //DEBERIAN ESTAR ENCRIPTADOS

  for(i = 0; i<=lineaActual;i++){
    usuario = strtok(lineas[i], ":");
    password = strtok(NULL,":"); //desencriptarla..

    if((strcmp(usuarioMensaje, usuario) == 0) && (strcmp(passwordMensaje, password)) == 0){
      valido = 1;
      strcpy(datosUsuario->username, usuario);
      strcpy(datosUsuario->password, password);
      strcpy(datosUsuario->usernameGit, strtok(NULL,":"));
      strcpy(datosUsuario->passwordGit, strtok(NULL,":"));
      break;
    }
  }

  if(!valido) // CERRAR CONEXION SI NO ES CORRECTO EL USUARIO O LA PASS
    return -1;

  int status = procesarComandos(comando, datosUsuario, configuracion);
  
  if(status == -1){
    return -1;
  }

  return 0;
}
Пример #29
0
static Lisp_Object
casify_object (enum case_action flag, Lisp_Object obj)
{
  register int c, c1;
  register int inword = flag == CASE_DOWN;

  /* If the case table is flagged as modified, rescan it.  */
  if (NILP (XCHAR_TABLE (BVAR (current_buffer, downcase_table))->extras[1]))
    Fset_case_table (BVAR (current_buffer, downcase_table));

  if (INTEGERP (obj))
    {
      int flagbits = (CHAR_ALT | CHAR_SUPER | CHAR_HYPER
		      | CHAR_SHIFT | CHAR_CTL | CHAR_META);
      int flags = XINT (obj) & flagbits;
      int multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));

      /* If the character has higher bits set
	 above the flags, return it unchanged.
	 It is not a real character.  */
      if ((unsigned) XFASTINT (obj) > (unsigned) flagbits)
	return obj;

      c1 = XFASTINT (obj) & ~flagbits;
      /* FIXME: Even if enable-multibyte-characters is nil, we may
	 manipulate multibyte chars.  This means we have a bug for latin-1
	 chars since when we receive an int 128-255 we can't tell whether
	 it's an eight-bit byte or a latin-1 char.  */
      if (c1 >= 256)
	multibyte = 1;
      if (! multibyte)
	MAKE_CHAR_MULTIBYTE (c1);
      c = downcase (c1);
      if (inword)
	XSETFASTINT (obj, c | flags);
      else if (c == (XFASTINT (obj) & ~flagbits))
	{
	  if (! inword)
	    c = upcase1 (c1);
	  if (! multibyte)
	    MAKE_CHAR_UNIBYTE (c);
	  XSETFASTINT (obj, c | flags);
	}
      return obj;
    }

  if (!STRINGP (obj))
    wrong_type_argument (Qchar_or_string_p, obj);
  else if (!STRING_MULTIBYTE (obj))
    {
      EMACS_INT i;
      EMACS_INT size = SCHARS (obj);

      obj = Fcopy_sequence (obj);
      for (i = 0; i < size; i++)
	{
	  c = SREF (obj, i);
	  MAKE_CHAR_MULTIBYTE (c);
	  c1 = c;
	  if (inword && flag != CASE_CAPITALIZE_UP)
	    c = downcase (c);
	  else if (!uppercasep (c)
		   && (!inword || flag != CASE_CAPITALIZE_UP))
	    c = upcase1 (c1);
	  if ((int) flag >= (int) CASE_CAPITALIZE)
	    inword = (SYNTAX (c) == Sword);
	  if (c != c1)
	    {
		  MAKE_CHAR_UNIBYTE (c);
	      /* If the char can't be converted to a valid byte, just don't
		 change it.  */
	      if (c >= 0 && c < 256)
		SSET (obj, i, c);
	    }
	}
      return obj;
    }
  else
    {
      EMACS_INT i, i_byte, size = SCHARS (obj);
      int len;
      USE_SAFE_ALLOCA;
      unsigned char *dst, *o;
      /* Over-allocate by 12%: this is a minor overhead, but should be
	 sufficient in 99.999% of the cases to avoid a reallocation.  */
      EMACS_INT o_size = SBYTES (obj) + SBYTES (obj) / 8 + MAX_MULTIBYTE_LENGTH;
      SAFE_ALLOCA (dst, void *, o_size);
      o = dst;

      for (i = i_byte = 0; i < size; i++, i_byte += len)
	{
	  if ((o - dst) + MAX_MULTIBYTE_LENGTH > o_size)
	    { /* Not enough space for the next char: grow the destination.  */
	      unsigned char *old_dst = dst;
	      o_size += o_size;	/* Probably overkill, but extremely rare.  */
	      SAFE_ALLOCA (dst, void *, o_size);
	      memcpy (dst, old_dst, o - old_dst);
	      o = dst + (o - old_dst);
	    }
	  c = STRING_CHAR_AND_LENGTH (SDATA (obj) + i_byte, len);
	  if (inword && flag != CASE_CAPITALIZE_UP)
	    c = downcase (c);
	  else if (!uppercasep (c)
		   && (!inword || flag != CASE_CAPITALIZE_UP))
	    c = upcase1 (c);
	  if ((int) flag >= (int) CASE_CAPITALIZE)
	    inword = (SYNTAX (c) == Sword);
	  o += CHAR_STRING (c, o);
	}
      eassert (o - dst <= o_size);
      obj = make_multibyte_string ((char *) dst, size, o - dst);
      SAFE_FREE ();
      return obj;
    }
}
Пример #30
0
static size_t
date_strftime_with_tmx(char *s, size_t maxsize, const char *format,
		       const struct tmx *tmx)
{
    char *endp = s + maxsize;
    char *start = s;
    const char *sp, *tp;
    auto char tbuf[100];
    ptrdiff_t i;
    int v, w;
    size_t colons;
    int precision, flags;
    char padding;
    /* LOCALE_[OE] and COLONS are actually modifiers, not flags */
    enum {LEFT, CHCASE, LOWER, UPPER, LOCALE_O, LOCALE_E, COLONS};
#define BIT_OF(n) (1U<<(n))

    /* various tables for locale C */
    static const char days_l[][10] = {
	"Sunday", "Monday", "Tuesday", "Wednesday",
	"Thursday", "Friday", "Saturday",
    };
    static const char months_l[][10] = {
	"January", "February", "March", "April",
	"May", "June", "July", "August", "September",
	"October", "November", "December",
    };
    static const char ampm[][3] = { "AM", "PM", };

    if (s == NULL || format == NULL || tmx == NULL || maxsize == 0)
	return 0;

    /* quick check if we even need to bother */
    if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize) {
      err:
	errno = ERANGE;
	return 0;
    }

    for (; *format && s < endp - 1; format++) {
#define FLAG_FOUND() do {						\
	    if (precision > 0 || flags & (BIT_OF(LOCALE_E) | BIT_OF(LOCALE_O) | BIT_OF(COLONS))) \
		goto unknown;						\
	} while (0)
#define NEEDS(n) do if (s >= endp || (n) >= endp - s - 1) goto err; while (0)
#define FILL_PADDING(i) do {						\
	    if (!(flags & BIT_OF(LEFT)) && precision > (i)) {		\
		NEEDS(precision);					\
		memset(s, padding ? padding : ' ', precision - (i));	\
		s += precision - (i);					\
	    }								\
	    else {							\
		NEEDS(i);						\
	    }								\
	} while (0);
#define FMT(def_pad, def_prec, fmt, val)				\
	do {								\
	    int l;							\
	    if (precision <= 0) precision = (def_prec);			\
	    if (flags & BIT_OF(LEFT)) precision = 1;			\
	    l = snprintf(s, endp - s,					\
			 ((padding == '0' || (!padding && (def_pad) == '0')) ? \
			  "%0*"fmt : "%*"fmt),				\
			 precision, (val));				\
	    if (l < 0) goto err;					\
	    s += l;							\
	} while (0)
#define STRFTIME(fmt)							\
	do {								\
	    i = date_strftime_with_tmx(s, endp - s, (fmt), tmx);	\
	    if (!i) return 0;						\
	    if (flags & BIT_OF(UPPER))					\
		upcase(s, i);						\
	    if (!(flags & BIT_OF(LEFT)) && precision > i) {		\
		if (start + maxsize < s + precision) {			\
		    errno = ERANGE;					\
		    return 0;						\
		}							\
		memmove(s + precision - i, s, i);			\
		memset(s, padding ? padding : ' ', precision - i);	\
		s += precision;						\
	    }								\
	    else s += i;						\
	} while (0)
#define FMTV(def_pad, def_prec, fmt, val)				\
	do {								\
	    VALUE tmp = (val);						\
	    if (FIXNUM_P(tmp)) {					\
		FMT((def_pad), (def_prec), "l"fmt, FIX2LONG(tmp));	\
	    }								\
	    else {							\
		VALUE args[2], result;					\
		size_t l;						\
		if (precision <= 0) precision = (def_prec);		\
		if (flags & BIT_OF(LEFT)) precision = 1;		\
		args[0] = INT2FIX(precision);				\
		args[1] = (val);					\
		if (padding == '0' || (!padding && (def_pad) == '0'))	\
		    result = rb_str_format(2, args, rb_str_new2("%0*"fmt)); \
		else							\
		    result = rb_str_format(2, args, rb_str_new2("%*"fmt)); \
		l = strlcpy(s, StringValueCStr(result), endp - s);	\
		if ((size_t)(endp - s) <= l)				\
		    goto err;						\
		s += l;							\
	    }								\
	} while (0)

	if (*format != '%') {
	    *s++ = *format;
	    continue;
	}
	tp = tbuf;
	sp = format;
	precision = -1;
	flags = 0;
	padding = 0;
	colons = 0;
      again:
	switch (*++format) {
	  case '\0':
	    format--;
	    goto unknown;

	  case 'A':	/* full weekday name */
	  case 'a':	/* abbreviated weekday name */
	    if (flags & BIT_OF(CHCASE)) {
		flags &= ~(BIT_OF(LOWER) | BIT_OF(CHCASE));
		flags |= BIT_OF(UPPER);
	    }
	    {
		int wday = tmx_wday;
		if (wday < 0 || wday > 6)
		    i = 1, tp = "?";
		else {
		    if (*format == 'A')
			i = strlen(tp = days_l[wday]);
		    else
			i = 3, tp = days_l[wday];
		}
	    }
	    break;

	  case 'B':	/* full month name */
	  case 'b':	/* abbreviated month name */
	  case 'h':	/* same as %b */
	    if (flags & BIT_OF(CHCASE)) {
		flags &= ~(BIT_OF(LOWER) | BIT_OF(CHCASE));
		flags |= BIT_OF(UPPER);
	    }
	    {
		int mon = tmx_mon;
		if (mon < 1 || mon > 12)
		    i = 1, tp = "?";
		else {
		    if (*format == 'B')
			i = strlen(tp = months_l[mon - 1]);
		    else
			i = 3, tp = months_l[mon - 1];
		}
	    }
	    break;

	  case 'C':	/* century (year/100) */
	    FMTV('0', 2, "d", div(tmx_year, INT2FIX(100)));
	    continue;

	  case 'c':	/* appropriate date and time representation */
	    STRFTIME("%a %b %e %H:%M:%S %Y");
	    continue;

	  case 'D':
	    STRFTIME("%m/%d/%y");
	    continue;

	  case 'd':	/* day of the month, 01 - 31 */
	  case 'e':	/* day of month, blank padded */
	    v = range(1, tmx_mday, 31);
	    FMT((*format == 'd') ? '0' : ' ', 2, "d", v);
	    continue;

	  case 'F':
	    STRFTIME("%Y-%m-%d");
	    continue;

	  case 'G':	/* year of ISO week with century */
	  case 'Y':	/* year with century */
	    {
		VALUE year = (*format == 'G') ? tmx_cwyear : tmx_year;
		if (FIXNUM_P(year)) {
		    long y = FIX2LONG(year);
		    FMT('0', 0 <= y ? 4 : 5, "ld", y);
		}
		else {
		    FMTV('0', 4, "d", year);
		}
	    }
	    continue;

	  case 'g':	/* year of ISO week without a century */
	  case 'y':	/* year without a century */
	    v = NUM2INT(mod((*format == 'g') ? tmx_cwyear : tmx_year, INT2FIX(100)));
	    FMT('0', 2, "d", v);
	    continue;

	  case 'H':	/* hour, 24-hour clock, 00 - 23 */
	  case 'k':	/* hour, 24-hour clock, blank pad */
	    v = range(0, tmx_hour, 23);
	    FMT((*format == 'H') ? '0' : ' ', 2, "d", v);
	    continue;

	  case 'I':	/* hour, 12-hour clock, 01 - 12 */
	  case 'l':	/* hour, 12-hour clock, 1 - 12, blank pad */
	    v = range(0, tmx_hour, 23);
	    if (v == 0)
		v = 12;
	    else if (v > 12)
		v -= 12;
	    FMT((*format == 'I') ? '0' : ' ', 2, "d", v);
	    continue;

	  case 'j':	/* day of the year, 001 - 366 */
	    v = range(1, tmx_yday, 366);
	    FMT('0', 3, "d", v);
	    continue;

	  case 'L':	/* millisecond */
	  case 'N':	/* nanosecond */
	    if (*format == 'L')
		w = 3;
	    else
		w = 9;
	    if (precision <= 0)
		precision = w;
	    NEEDS(precision);

	    {
		VALUE subsec = tmx_sec_fraction;
		int ww;
		long n;

		ww = precision;
		while (9 <= ww) {
		    subsec = mul(subsec, INT2FIX(1000000000));
		    ww -= 9;
		}
		n = 1;
		for (; 0 < ww; ww--)
		    n *= 10;
		if (n != 1)
		    subsec = mul(subsec, INT2FIX(n));
		subsec = div(subsec, INT2FIX(1));

		if (FIXNUM_P(subsec)) {
		    (void)snprintf(s, endp - s, "%0*ld",
				   precision, FIX2LONG(subsec));
		    s += precision;
		}
		else {
		    VALUE args[2], result;
		    args[0] = INT2FIX(precision);
		    args[1] = subsec;
		    result = rb_str_format(2, args, rb_str_new2("%0*d"));
		    (void)strlcpy(s, StringValueCStr(result), endp - s);
		    s += precision;
		}
	    }
	    continue;

	  case 'M':	/* minute, 00 - 59 */
	    v = range(0, tmx_min, 59);
	    FMT('0', 2, "d", v);
	    continue;

	  case 'm':	/* month, 01 - 12 */
	    v = range(1, tmx_mon, 12);
	    FMT('0', 2, "d", v);
	    continue;

	  case 'n':	/* same as \n */
	    FILL_PADDING(1);
	    *s++ = '\n';
	    continue;

	  case 't':	/* same as \t */
	    FILL_PADDING(1);
	    *s++ = '\t';
	    continue;

	  case 'P':	/* am or pm based on 12-hour clock */
	  case 'p':	/* AM or PM based on 12-hour clock */
	    if ((*format == 'p' && (flags & BIT_OF(CHCASE))) ||
		(*format == 'P' && !(flags & (BIT_OF(CHCASE) | BIT_OF(UPPER))))) {
		flags &= ~(BIT_OF(UPPER) | BIT_OF(CHCASE));
		flags |= BIT_OF(LOWER);
	    }
	    v = range(0, tmx_hour, 23);
	    if (v < 12)
		tp = ampm[0];
	    else
		tp = ampm[1];
	    i = 2;
	    break;

	  case 'Q':	/* milliseconds since Unix epoch */
	    FMTV('0', 1, "d", tmx_msecs);
	    continue;

	  case 'R':
	    STRFTIME("%H:%M");
	    continue;

	  case 'r':
	    STRFTIME("%I:%M:%S %p");
	    continue;

	  case 'S':	/* second, 00 - 59 */
	    v = range(0, tmx_sec, 59);
	    FMT('0', 2, "d", v);
	    continue;

	  case 's':	/* seconds since Unix epoch */
	    FMTV('0', 1, "d", tmx_secs);
	    continue;

	  case 'T':
	    STRFTIME("%H:%M:%S");
	    continue;

	  case 'U':	/* week of year, Sunday is first day of week */
	  case 'W':	/* week of year, Monday is first day of week */
	    v = range(0, (*format == 'U') ? tmx_wnum0 : tmx_wnum1, 53);
	    FMT('0', 2, "d", v);
	    continue;

	  case 'u':	/* weekday, Monday == 1, 1 - 7 */
	    v = range(1, tmx_cwday, 7);
	    FMT('0', 1, "d", v);
	    continue;

	  case 'V':	/* week of year according ISO 8601 */
	    v = range(1, tmx_cweek, 53);
	    FMT('0', 2, "d", v);
	    continue;

	  case 'v':
	    STRFTIME("%e-%b-%Y");
	    continue;

	  case 'w':	/* weekday, Sunday == 0, 0 - 6 */
	    v = range(0, tmx_wday, 6);
	    FMT('0', 1, "d", v);
	    continue;

	  case 'X':	/* appropriate time representation */
	    STRFTIME("%H:%M:%S");
	    continue;

	  case 'x':	/* appropriate date representation */
	    STRFTIME("%m/%d/%y");
	    continue;

	  case 'Z':	/* time zone name or abbreviation */
	    if (flags & BIT_OF(CHCASE)) {
		flags &= ~(BIT_OF(UPPER) | BIT_OF(CHCASE));
		flags |= BIT_OF(LOWER);
	    }
	    {
		char *zone = tmx_zone;
		if (zone == NULL)
		    tp = "";
		else
		    tp = zone;
		i = strlen(tp);
	    }
	    break;

	  case 'z':	/* offset from UTC */
	    {
		long off, aoff;
		int hl, hw;

		off = tmx_offset;
		aoff = off;
		if (aoff < 0)
		    aoff = -off;

		if ((aoff / 3600) < 10)
		    hl = 1;
		else
		    hl = 2;
		hw = 2;
		if (flags & BIT_OF(LEFT) && hl == 1)
		    hw = 1;

		switch (colons) {
		  case 0: /* %z -> +hhmm */
		    precision = precision <= (3 + hw) ? hw : precision - 3;
		    NEEDS(precision + 3);
		    break;

		  case 1: /* %:z -> +hh:mm */
		    precision = precision <= (4 + hw) ? hw : precision - 4;
		    NEEDS(precision + 4);
		    break;

		  case 2: /* %::z -> +hh:mm:ss */
		    precision = precision <= (7 + hw) ? hw : precision - 7;
		    NEEDS(precision + 7);
		    break;

		  case 3: /* %:::z -> +hh[:mm[:ss]] */
		    {
			if (aoff % 3600 == 0) {
			    precision = precision <= (1 + hw) ?
				hw : precision - 1;
			    NEEDS(precision + 3);
			}
			else if (aoff % 60 == 0) {
			    precision = precision <= (4 + hw) ?
				hw : precision - 4;
			    NEEDS(precision + 4);
			}
			else {
			    precision = precision <= (7 + hw) ?
				hw : precision - 7;
			    NEEDS(precision + 7);
			}
		    }
		    break;

		  default:
		    format--;
		    goto unknown;
		}
		if (padding == ' ' && precision > hl) {
		    i = snprintf(s, endp - s, "%*s", precision - hl, "");
		    precision = hl;
		    if (i < 0) goto err;
		    s += i;
		}
		if (off < 0) {
		    off = -off;
		    *s++ = '-';
		} else {
		    *s++ = '+';
		}
		i = snprintf(s, endp - s, "%.*ld", precision, off / 3600);
		if (i < 0) goto err;
		s += i;
		off = off % 3600;
		if (colons == 3 && off == 0)
		    continue;
		if (1 <= colons)
		    *s++ = ':';
		i = snprintf(s, endp - s, "%02d", (int)(off / 60));
		if (i < 0) goto err;
		s += i;
		off = off % 60;
		if (colons == 3 && off == 0)
		    continue;
		if (2 <= colons) {
		    *s++ = ':';
		    i = snprintf(s, endp - s, "%02d", (int)off);
		    if (i < 0) goto err;
		    s += i;
		}
	    }
	    continue;

	  case '+':
	    STRFTIME("%a %b %e %H:%M:%S %Z %Y");
	    continue;

	  case 'E':
	    /* POSIX locale extensions, ignored for now */
	    flags |= BIT_OF(LOCALE_E);
	    if (*(format + 1) && strchr("cCxXyY", *(format + 1)))
		goto again;
	    goto unknown;
	  case 'O':
	    /* POSIX locale extensions, ignored for now */
	    flags |= BIT_OF(LOCALE_O);
	    if (*(format + 1) && strchr("deHkIlmMSuUVwWy", *(format + 1)))
		goto again;
	    goto unknown;

	  case ':':
	    flags |= BIT_OF(COLONS);
	    {
		size_t l = strspn(format, ":");
		format += l;
		if (*format == 'z') {
		    colons = l;
		    format--;
		    goto again;
		}
		format -= l;
	    }
	    goto unknown;

	  case '_':
	    FLAG_FOUND();
	    padding = ' ';
	    goto again;

	  case '-':
	    FLAG_FOUND();
	    flags |= BIT_OF(LEFT);
	    goto again;

	  case '^':
	    FLAG_FOUND();
	    flags |= BIT_OF(UPPER);
	    goto again;

	  case '#':
	    FLAG_FOUND();
	    flags |= BIT_OF(CHCASE);
	    goto again;

	  case '0':
	    FLAG_FOUND();
	    padding = '0';
	  case '1':  case '2': case '3': case '4':
	  case '5': case '6':  case '7': case '8': case '9':
	    {
		char *e;
		precision = (int)strtoul(format, &e, 10);
		format = e - 1;
		goto again;
	    }

	  case '%':
	    FILL_PADDING(1);
	    *s++ = '%';
	    continue;

	  default:
	  unknown:
	    i = format - sp + 1;
	    tp = sp;
	    precision = -1;
	    flags = 0;
	    padding = 0;
	    colons = 0;
	    break;
	}
	if (i) {
	    FILL_PADDING(i);
	    memcpy(s, tp, i);
	    switch (flags & (BIT_OF(UPPER) | BIT_OF(LOWER))) {
	      case BIT_OF(UPPER):
		upcase(s, i);
		break;
	      case BIT_OF(LOWER):
		downcase(s, i);
		break;
	    }
	    s += i;
	}
    }
    if (s >= endp) {
	goto err;
    }
    if (*format == '\0') {
	*s = '\0';
	return (s - start);
    }
    return 0;
}