Ejemplo n.º 1
0
int main (int argc, char *argv[])
{
  // open the output data stream
  QTextStream out(stdout, IO_WriteOnly);
  
  const char* header =
    "Content-type: text/html; charset=iso-8859-1\n\n"
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
    "<HTML>\n"
    "  <HEAD>\n"
    "    <TITLE>ShowEQ Item Display</TITLE>\n"
    "    <style type=\"text/css\">\n"
    "      <!--\n"
    "          table { border: black 2px solid }\n"
    "          td { border: black 1px solid }\n"
    "          th { border: black 1px solid }\n"
    "          span.head { color: black }\n"
    "          span.known1 { color: green }\n"
    "          span.known2 { color: blue }\n"
    "          span.varies { color: purple }\n"
    "          span.unknown { color: red }\n"
    "          b.warning { color: red }\n"
    "      -->\n"
    "    </style>\n" 
    "  </HEAD>\n"
    "  <BODY>\n";
  
  /* Print HTML header */
  out << header;
  
  const char* footer = 
    "  </BODY>\n"
    "</HTML>\n";
  
  // number of item to display
  QString itemNumber;
  
  // should binary data be displayed (default = false)
  bool displayBinaryData = false;
  
  // should the icon be displayed
  bool displayIcon = DISPLAY_ICONS;
  
  // CGI Convenience class
  CGI cgiconv;
  
  // process any CGI data
  cgiconv.processCGIData();
  
  // If there are form parameters use them
  if (cgiconv.getParamCount() != 0)
  {
    itemNumber = cgiconv.getParamValue("item");
    
    if (cgiconv.getParamValue("displayBinary") == "y")
      displayBinaryData = true;
    else if (cgiconv.getParamValue("displayBinary") == "n")
      displayBinaryData = false;
    
    if (cgiconv.getParamValue("showIcon") == "y")
      displayIcon = true;
    else if (cgiconv.getParamValue("hideIcon") == "y")
      displayIcon = false;
  }
  else if (argc == 2)
  {
    // use argument for item number
    itemNumber = argv[1];
    
  }
  else if (argc > 2)
  {
    out << "<H1>Error: " << argv[0] << " called with " << argc 
	<< " arguments!</H1>\n";
    out << "Format: " << argv[0] << "?<ItemID>\n";
    out << footer;
    exit(-1);
  }
  
  if (itemNumber.isNull())
    itemNumber = "";

  // check for browser type
  QString userAgent = cgiconv.getHTTPUserAgent();
  out << "    <!-- Output for UserAgent: " << userAgent << "-->\n";
  
  // beware Netscape4 style sheet brain death
  bool isNetscape4 = false;
  if ((userAgent.contains("Mozilla/4.") == 1) && 
      (userAgent.contains("MSIE") == 0))
    isNetscape4 = true;
  
  // display form to allow user to select an item or display the binary data
  out << "    <FORM method=\"POST\" action=\"" << cgiconv.getScriptName() 
      << "\">\n";
  
  if (isNetscape4)
    out << "      <TABLE border cellspacing=0 cellpadding=2>\n";
  else
    out << "      <TABLE cellspacing=0 cellpadding=2>\n";
  
  out <<
    "        <TR><TH>Item ID:</TH><TH>Binary Data</TH><TH>Icon</TH>"
    "<TD><INPUT type=\"reset\" value=\"Reset\"/></TD></TR>\n"
    "        <TR>\n";
  
  out << "          <TD><INPUT type=\"text\" name=\"item\" value=\"" 
      << itemNumber 
      << "\" size=\"5\"/></TD>\n";
  
  out << 
    "          <TD>"
    "<INPUT type=\"checkbox\" name=\"displayBinary\" value=\"y\"";
  
  if (displayBinaryData)
    out << " checked";
  out << "/>Display</TD>\n";
  
  out << 
    "          <TD>";
  
  if (displayIcon)
    out << "<INPUT type=\"checkbox\" name=\"hideIcon\" value=\"y\" unchecked>"
	<< "Hide</TD>\n";
  else
    out << "<INPUT type=\"hidden\" name=\"hideIcon\" value=\"y\">"
	<< "<INPUT type=\"checkbox\" name=\"showIcon\" value=\"y\" unchecked>"
	<< "Show</TD>\n";
  
  
  // Submission button
  out << 
    "          <TD>"
    "<INPUT type=\"submit\" value=\"Search\"/></TD>\n";
  
  out << "        </TR>\n";
  out << "      </TABLE>\n";
  out << "    </FORM>\n";
  
  
  // if no item number was passed in, then just return
  if (itemNumber.isEmpty())
  {
    // ask the user to enter an ItemID
    out << "<H1>Please Enter an ItemID!</H1>\n";
    
    // close the document
    out << footer;
    
    return 0;
  }
  
  // convert the passed in item number to a short
  uint16_t currentItemNr = itemNumber.toShort();
  
  EQItemDB* itemDB = new EQItemDB;
  QString nameString;
  QString loreString;
  bool hasEntry = false;
  EQItemDBEntry* entry = NULL;
  
  hasEntry = itemDB->GetItemData(currentItemNr, &entry);
  
  out << "<H1>Information on ItemID: " << currentItemNr << "</H1>\n";
  
  if (hasEntry)
  {
    loreString = entry->GetLoreName();
    nameString = entry->GetName();
    
    if (displayIcon)
      out << "<P><IMG src=\"" << ICON_DIR << entry->GetIconNr() 
	  << ".png\" alt=\"Icon: " << entry->GetIconNr() << "\"/></P>";
    
    if (!nameString.isEmpty())
    {
      out << "<H2>" << nameString << "</H2>\n";
      out << "<P><B>Lore:</B> " << loreString << "<BR></P>\n";
    }
    else
    {
      out << "<H2>Lore: " << loreString << "</H2>\n";
    } 
    
    out << "<P>\n";
    time_t updated = entry->GetUpdated();
    out << "<B>Last Updated:</B> " << ctime(&updated) << "<BR>\n";
    out << "<B>Icon Number:</B> " << entry->GetIconNr() << "<BR>\n";
    out << "<B>Model:</B> " << entry->GetIdFile() << "<BR>\n";
    out << "<B>ItemType:</B> " << QString::number(entry->GetItemType())
	<< "<BR>\n";
    out << "<B>Weight:</B> " << (int)entry->GetWeight() << "<BR>\n";
    out << "<B>Flags:</B> ";
    if (entry->IsBook())
      out << " BOOK";
    if (entry->IsContainer())
      out << " CONTAINER";
    if (entry->GetNoDrop() == 0)
      out << " NO-DROP";
    if (entry->GetNoRent() == 0)
      out << " NO-RENT";
    if (entry->GetMagic() == 1)
      out << " MAGIC";
    if (loreString[0] == '*')
      out << " LORE";
    else if (loreString[0] == '&')
      out << " SUMMONED";
    else if (loreString[0] == '#')
      out << " ARTIFACT";
    else if (loreString[0] == '~')
      out << " PENDING-LORE";

    out << "<BR>\n";
    out << "<B>Size:</B> " << size_name(entry->GetSize()) << "<BR>\n";
    out << "<B>Slots:</B> " << print_slot(entry->GetSlots()) << "<BR>\n";
    out << "<B>Base Price:</B> " << reformatMoney(entry->GetCost()) 
	<< "<BR>\n";
    if (entry->GetSTR())
      out << "<B>Str:</B> " << (int)entry->GetSTR() << "<BR>\n";
    if (entry->GetSTA())
      out << "<B>Sta:</B> " << (int)entry->GetSTA() << "<BR>\n";
    if (entry->GetCHA())
      out << "<B>Cha:</B> " << (int)entry->GetCHA() << "<BR>\n";
    if (entry->GetDEX())
      out << "<B>Dex:</B> " << (int)entry->GetDEX() << "<BR>\n";
    if (entry->GetINT())
      out << "<B>Int:</B> " << (int)entry->GetINT() << "<BR>\n";
    if (entry->GetAGI())
      out << "<B>Agi:</B> " << (int)entry->GetAGI() << "<BR>\n";
    if (entry->GetWIS())
      out << "<B>Wis:</B> " << (int)entry->GetWIS() << "<BR>\n";
    if (entry->GetMR())
      out << "<B>Magic:</B> " << (int)entry->GetMR() << "<BR>\n";
    if (entry->GetFR())
      out << "<B>Fire:</B> " << (int)entry->GetFR() << "<BR>\n";
    if (entry->GetCR())
      out << "<B>Cold:</B> " << (int)entry->GetCR() << "<BR>\n";
    if (entry->GetDR())
      out << "<B>Disease:</B> " << (int)entry->GetDR() << "<BR>\n";
    if (entry->GetPR())
      out << "<B>Poison:</B> " << (int)entry->GetPR() << "<BR>\n";
    if (entry->GetHP())
      out << "<B>HP:</B> " << (int)entry->GetHP() << "<BR>\n";
    if (entry->GetMana())
      out << "<B>Mana:</B> " << (int)entry->GetMana() << "<BR>\n";
    if (entry->GetAC())
      out << "<B>AC:</B> " << (int)entry->GetAC() << "<BR>\n";
    if (entry->GetLight())
      out << "<B>Light:</B> " << (int)entry->GetLight() << "<BR>\n";
    if (entry->GetDelay())
      out << "<B>Delay:</B> " << (int)entry->GetDelay() << "<BR>\n";
    
    if (entry->GetDamage())
    {
      out << "<B>Damage:</B> " << (int)entry->GetDamage() << "<BR>\n";
      QString qsTemp = print_skill (entry->GetSkill());
      out << "<B>Skill:</B> ";
      
      if (qsTemp.find("U0x") == -1)
	out << qsTemp << "<BR>\n";
      else
	out << "Unknown (ID: " << qsTemp << ")<BR>\n";
    }
    
    if (entry->GetRange())
      out << "<B>Range:</B> " << (int)entry->GetRange() << "<BR>\n";
    
    if (entry->GetMaterial())
    {
      out << "<B>Material:</B> " << QString::number(entry->GetMaterial(), 16)
	  << " (" << print_material (entry->GetMaterial()) << ")<BR>\n";
      
      out << "<B>Color:</B> " << QString::number(entry->GetColor(), 16) << "<BR>\n";
      
      out << ((entry->GetColor())  ?
	      (QString("<TABLE><TR><TD bgcolor=\"#%1\">").arg(entry->GetColor(), 6, 16)) :
	      ("<TABLE><TR><TD bgcolor=\"#ffffff\">"))
	  << "&nbsp;&nbsp;###&nbsp;SAMPLE&nbsp;###&nbsp;&nbsp</TD></TR></TABLE>\n";
    }
    else
      out << "<B>Material:</B> 0 (None)<BR>\n";

    if (entry->GetStackable() != -1)
      out << "<B>Stackable:</B> " 
	  << ((entry->GetStackable() == 1) ? "yes" : "no?") << "<BR>\n";

    if (entry->GetEffectType() != -1)
      out << "<B>Effect Type:</B> " 
	  << entry->GetEffectTypeString() << "<BR>\n";
    if (entry->GetSpellId() != ITEM_SPELLID_NOSPELL)
    {
      out << "<B>Spell Effect:</B> " << spell_name (entry->GetSpellId()) 
	  << "<BR>\n";
      if (entry->GetLevel())
	out << "<B>Casting Level:</B> " << (int)entry->GetLevel() << "<BR>\n";
      if (entry->GetCharges())
      {
	out << "<B>Charges:</B> ";
	
	if (entry->GetCharges() == -1)
	  out << "Unlimited<BR>\n";
	else
	  out << (int)entry->GetCharges() << "<BR>\n";
      }
      if (entry->GetCastTime())
	out << "<B>Casting Time:</B> " << (int)entry->GetCastTime() 
	    << "<BR>\n";
    }
    out << "<B>Class:</B> " << print_classes (entry->GetClasses()) << "<BR>\n";
    out << "<B>Race:</B> " << print_races (entry->GetRaces()) << "<BR>\n";
    if (entry->GetSkillModId())
      out << "<B>Skill Modifier:</B> " << skill_name(entry->GetSkillModId())
	  << " " << (int)entry->GetSkillModPercent() << "% <BR>\n";
    if (entry->IsContainer())
    {
      if (entry->GetNumSlots())
        out << "<B>Container Slots:</B> " << (int)entry->GetNumSlots() 
	    << "<BR>\n";
      if (entry->GetSizeCapacity())
        out << "<B>Size Capacity:</B> " << size_name(entry->GetSizeCapacity())
	    << "<BR>\n";
      if (entry->GetWeightReduction())
        out << "<B>% Weight Reduction:</B> " << (int)entry->GetWeightReduction()
	    << "<BR>\n";
    }
    out << "</P>\n";
  }
  
  int size = 0;
  
  if (displayBinaryData)
  {
    time_t updated;
    char* rawData = NULL;
    size = itemDB->GetItemRawData(currentItemNr, updated, &rawData);

    if ((size > 0) && (rawData != NULL))
    {
      out << "<P><B>Raw data: (" << size << " octets) last updated: " 
	  << ctime(&updated) << "</B></P>\n";
      out << "</P>";
      out << "<PRE>\n";
      printdata (out, size, rawData);
      out << "</PRE>\n";
      delete [] rawData;
    }
  }

  if (!hasEntry && nameString.isEmpty() && loreString.isEmpty() &&
      (size == 0))
    out << "<P>Item " << currentItemNr << " not found</P>\n";

  // close the document with the footer
  out << footer;

  // delete DB entry 
  delete entry;

  // shutdown the ItemDB instance
  itemDB->Shutdown();

  // delete the ItemDB instance
  delete itemDB;

  return 0;
}
Ejemplo n.º 2
0
//获取文件属性并打印
void display_attribute(struct stat *buf, char *path)
{
    char time[32];
    struct passwd *psd;
    struct group *grp;

    //获取并打印文件类型
    if (S_ISLNK(buf->st_mode)) {
        printf("l");
    } else if (S_ISREG(buf->st_mode)) {
        printf("-");
    } else if (S_ISDIR(buf->st_mode)) {
        printf("d");
    } else if (S_ISCHR(buf->st_mode)) {
        printf("c");
    } else if (S_ISBLK(buf->st_mode)) {
        printf("b");
    } else if (S_ISFIFO(buf->st_mode)) {
        printf("f");
    } else if (S_ISSOCK(buf->st_mode)) {
        printf("s");
    }
    //获取所有者的权限
    if (buf->st_mode & S_IRUSR) {
        printf("r");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IWUSR) {
        printf("w");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IXUSR) {
        printf("x");
    } else {
        printf("-");
    }
    //获取组权限
    if (buf->st_mode & S_IRGRP) {
        printf("r");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IWGRP) {
        printf("w");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IXGRP) {
        printf("x");
    } else {
        printf("-");
    }
    //获取其他用户权限
    if (buf->st_mode & S_IROTH) {
        printf("r");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IWOTH) {
        printf("w");
    } else {
        printf("-");
    }
    if (buf->st_mode & S_IXOTH) {
        printf("x");
    } else {
        printf("-");
    }
    printf(" ");

    printf("%5lu ", buf->st_nlink);    //打印文件连接数

    //根据uid,gid获取用户名和组名
    psd = getpwuid(buf->st_uid);
    grp = getgrgid(buf->st_gid);
    printf("%-s\t", psd -> pw_name);
    printf("%-s\t", grp -> gr_name);

    printf("%10ld ", buf->st_size);    //打印文件大小

    strcpy(time, ctime(&buf -> st_mtime));
    time[(strlen(time)) - 1] = '\0';
    printf("%s ", time);             //打印时间
    printf("%s\n", path);             //打印文件名
}
Ejemplo n.º 3
0
/* XXX THIS SHOULD BE IN SYSTEM !!!! */
void
erl_crash_dump_v(char *file, int line, char* fmt, va_list args)
{
#ifdef ERTS_SMP
    ErtsThrPrgrData tpd_buf; /* in case we aren't a managed thread... */
#endif
    int fd;
    size_t envsz;
    time_t now;
    char env[21]; /* enough to hold any 64-bit integer */
    size_t dumpnamebufsize = MAXPATHLEN;
    char dumpnamebuf[MAXPATHLEN];
    char* dumpname;
    int secs;
    int env_erl_crash_dump_seconds_set = 1;
    int i;

    if (ERTS_SOMEONE_IS_CRASH_DUMPING)
	return;

#ifdef ERTS_SMP
    /* Order all managed threads to block, this has to be done
       first to guarantee that this is the only thread to generate
       crash dump. */
    erts_thr_progress_fatal_error_block(&tpd_buf);

#ifdef ERTS_SYS_SUSPEND_SIGNAL
    /*
     * We suspend all scheduler threads so that we can dump some
     * data about the currently running processes and scheduler data.
     * We have to be very very careful when doing this as the schedulers
     * could be anywhere.
     */
    for (i = 0; i < erts_no_schedulers; i++) {
        erts_tid_t tid = ERTS_SCHEDULER_IX(i)->tid;
        if (!erts_equal_tids(tid,erts_thr_self()))
            sys_thr_suspend(tid);
    }

#endif

    /* Allow us to pass certain places without locking... */
    erts_smp_atomic32_set_mb(&erts_writing_erl_crash_dump, 1);
    erts_smp_tsd_set(erts_is_crash_dumping_key, (void *) 1);

#else /* !ERTS_SMP */
    erts_writing_erl_crash_dump = 1;
#endif /* ERTS_SMP */

    envsz = sizeof(env);
    /* ERL_CRASH_DUMP_SECONDS not set
     * if we have a heart port, break immediately
     * otherwise dump crash indefinitely (until crash is complete)
     * same as ERL_CRASH_DUMP_SECONDS = 0
     * - do not write dump
     * - do not set an alarm
     * - break immediately
     *
     * ERL_CRASH_DUMP_SECONDS = 0
     * - do not write dump
     * - do not set an alarm
     * - break immediately
     *
     * ERL_CRASH_DUMP_SECONDS < 0
     * - do not set alarm
     * - write dump until done
     *
     * ERL_CRASH_DUMP_SECONDS = S (and S positive)
     * - Don't dump file forever
     * - set alarm (set in sys)
     * - write dump until alarm or file is written completely
     */
	
    if (erts_sys_getenv__("ERL_CRASH_DUMP_SECONDS", env, &envsz) != 0) {
	env_erl_crash_dump_seconds_set = 0;
	secs = -1;
    } else {
	env_erl_crash_dump_seconds_set = 1;
	secs = atoi(env);
    }

    if (secs == 0) {
	return;
    }

    /* erts_sys_prepare_crash_dump returns 1 if heart port is found, otherwise 0
     * If we don't find heart (0) and we don't have ERL_CRASH_DUMP_SECONDS set
     * we should continue writing a dump
     *
     * beware: secs -1 means no alarm
     */

    if (erts_sys_prepare_crash_dump(secs) && !env_erl_crash_dump_seconds_set ) {
	return;
    }

    if (erts_sys_getenv__("ERL_CRASH_DUMP",&dumpnamebuf[0],&dumpnamebufsize) != 0)
	dumpname = "erl_crash.dump";
    else
	dumpname = &dumpnamebuf[0];
    
    erts_fprintf(stderr,"\nCrash dump is being written to: %s...", dumpname);

    fd = open(dumpname,O_WRONLY | O_CREAT | O_TRUNC,0640);
    if (fd < 0)
	return; /* Can't create the crash dump, skip it */
    time(&now);
    erts_fdprintf(fd, "=erl_crash_dump:0.3\n%s", ctime(&now));

    if (file != NULL)
       erts_fdprintf(fd, "The error occurred in file %s, line %d\n", file, line);

    if (fmt != NULL && *fmt != '\0') {
	erts_fdprintf(fd, "Slogan: ");
	erts_vfdprintf(fd, fmt, args);
    }
    erts_fdprintf(fd, "System version: ");
    erts_print_system_version(fd, NULL, NULL);
#if ERTS_SAVED_COMPILE_TIME
    erts_fdprintf(fd, "%s\n", "Compiled: " ERLANG_COMPILE_DATE);
#endif

    erts_fdprintf(fd, "Taints: ");
    erts_print_nif_taints(fd, NULL);
    erts_fdprintf(fd, "Atoms: %d\n", atom_table_size());

#ifdef USE_THREADS
    /* We want to note which thread it was that called erts_exit */
    if (erts_get_scheduler_data()) {
        erts_fdprintf(fd, "Calling Thread: scheduler:%d\n",
                      erts_get_scheduler_data()->no);
    } else {
        if (!erts_thr_getname(erts_thr_self(), dumpnamebuf, MAXPATHLEN))
            erts_fdprintf(fd, "Calling Thread: %s\n", dumpnamebuf);
        else
            erts_fdprintf(fd, "Calling Thread: %p\n", erts_thr_self());
    }
#else
    erts_fdprintf(fd, "Calling Thread: scheduler:1\n");
#endif

#if defined(ERTS_HAVE_TRY_CATCH)

    /*
     * erts_print_scheduler_info is not guaranteed to be safe to call
     * here for all schedulers as we may have suspended a scheduler
     * in the middle of updating the STACK_TOP and STACK_START
     * variables and thus when scanning the stack we could get
     * segmentation faults. We protect against this very unlikely
     * scenario by using the ERTS_SYS_TRY_CATCH.
     */
    for (i = 0; i < erts_no_schedulers; i++) {
        ERTS_SYS_TRY_CATCH(
            erts_print_scheduler_info(fd, NULL, ERTS_SCHEDULER_IX(i)),
            erts_fdprintf(fd, "** crashed **\n"));
    }
#endif

#ifdef ERTS_SMP

#ifdef ERTS_SYS_SUSPEND_SIGNAL

    /* We resume all schedulers so that we are in a known safe state
       when we write the rest of the crash dump */
    for (i = 0; i < erts_no_schedulers; i++) {
        erts_tid_t tid = ERTS_SCHEDULER_IX(i)->tid;
        if (!erts_equal_tids(tid,erts_thr_self()))
	    sys_thr_resume(tid);
    }
#endif

    /*
     * Wait for all managed threads to block. If all threads haven't blocked
     * after a minute, we go anyway and hope for the best...
     *
     * We do not release system again. We expect an exit() or abort() after
     * dump has been written.
     */
    erts_thr_progress_fatal_error_wait(60000);
    /* Either worked or not... */
#endif

#ifndef ERTS_HAVE_TRY_CATCH
    /* This is safe to call here, as all schedulers are blocked */
    for (i = 0; i < erts_no_schedulers; i++) {
        erts_print_scheduler_info(fd, NULL, ERTS_SCHEDULER_IX(i));
    }
#endif
    
    info(fd, NULL); /* General system info */
    if (erts_ptab_initialized(&erts_proc))
	process_info(fd, NULL); /* Info about each process and port */
    db_info(fd, NULL, 0);
    erts_print_bif_timer_info(fd, NULL);
    distribution_info(fd, NULL);
    erts_fdprintf(fd, "=loaded_modules\n");
    loaded(fd, NULL);
    erts_dump_fun_entries(fd, NULL);
    erts_deep_process_dump(fd, NULL);
    erts_fdprintf(fd, "=atoms\n");
    dump_atoms(fd, NULL);

    /* Keep the instrumentation data at the end of the dump */
    if (erts_instr_memory_map || erts_instr_stat) {
	erts_fdprintf(fd, "=instr_data\n");

	if (erts_instr_stat) {
	    erts_fdprintf(fd, "=memory_status\n");
	    erts_instr_dump_stat_to_fd(fd, 0);
	}
	if (erts_instr_memory_map) {
	    erts_fdprintf(fd, "=memory_map\n");
	    erts_instr_dump_memory_map_to_fd(fd);
	}
    }

    erts_fdprintf(fd, "=end\n");
    close(fd);
    erts_fprintf(stderr,"done\n");
}
Ejemplo n.º 4
0
void
copy(int prompt, FILE *fin)
{
	FILE *fout, *f;
	char s[200], t[200], s1[200], *r, *tod;
	char nm[100];
	int *p;
	time_t tval;
	int nmatch = 0;

	if (subdir[0] == 0)
		snprintf(subdir, sizeof subdir, "%s/%s", _PATH_LLIB, sname);
	for (;;) {
		if (pgets(s, sizeof s, prompt, fin) == 0) {
			if (fin == stdin) {
				/* fprintf(stderr, "Don't type control-D\n"); */
				/* this didn't work out very well */
				wrapup(1);	/* ian */
				continue;
			} else
				break;
		}
		trim(s);
		/* change the sequence %s to lesson directory */
		/* if needed */
		for (r = s; *r; r++)
			if (*r == '%') {
				snprintf(s1, sizeof s1, s,
				    subdir, subdir, subdir);
				strlcpy(s, s1, sizeof s);
				break;
			}
		r = wordb(s, t);
		p = action(t);
		/* some actions done only once per script */
		if (p && *p == ONCE) {
			if (wrong) {	/* we are on 2nd time */
				scopy(fin, NULL);
				continue;
			}
			strlcpy(s, r, sizeof s);
			r = wordb(s, t);
			p = action(t);
		}
		if (p == 0) {
			if (comfile >= 0) {
				write(comfile, s, strlen(s));
				write(comfile, "\n", 1);
			}
			else {
				signal(SIGINT, SIG_IGN);
				status = mysys(s);
				signal(SIGINT, signal_intrpt);
			}
			if (incopy) {
				fprintf(incopy, "%s\n", s);
				strlcpy(last, s, sizeof last);
			}
			continue;
		}
		switch (*p) {
		case READY:
			if (incopy && r) {
				fprintf(incopy, "%s\n", r);
				strlcpy(last, r, sizeof last);
			}
			return;
		case PRINT:
			if (wrong)
				scopy(fin, NULL);	/* don't repeat msg */
			else if (r)
				list(r);
			else
				scopy(fin, stdout);
			break;
		case NOP:
			break;
		case MATCH:
			if (nmatch > 0)	/* we have already passed */
				scopy(fin, NULL);
			/* did we pass this time? */
			else if ((status = strcmp(r, last)) == 0) {
				nmatch++;
				scopy(fin, stdout);
			} else
				scopy(fin, NULL);
			break;
		case BAD:
			if (strcmp(r, last) == 0)
				scopy(fin, stdout);
			else
				scopy(fin, NULL);
			break;
		case SUCCEED:
			scopy(fin, (status == 0) ? stdout : NULL);
			break;
		case FAIL:
			scopy(fin, (status != 0) ? stdout : NULL);
			break;
		case CREATE:
			fout = fopen(r, "w");
			scopy(fin, fout);
			fclose(fout);
			break;
		case CMP:
			status = cmp(r);	/* contains two file names */
			break;
		case MV:
			snprintf(nm, sizeof nm, "%s/L%s.%s", subdir, todo, r);
			fcopy(r, nm);
			break;
		case USER:
		case NEXT:
			more = 1;
			return;
		case COPYIN:
			incopy = fopen(".copy", "w");
			break;
		case UNCOPIN:
			fclose(incopy);
			incopy = NULL;
			break;
		case COPYOUT:
			maktee();
			break;
		case UNCOPOUT:
			untee();
			break;
		case PIPE:
			comfile = makpipe();
			break;
		case UNPIPE:
			close(comfile);
			wait(0);
			comfile = -1;
			break;
		case YES:
		case NO:
			if (incopy) {
				fprintf(incopy, "%s\n", s);
				strlcpy(last, s, sizeof last);
			}
			return;
		case WHERE:
			printf("You are in lesson %s\n", todo);
			fflush(stdout);
			break;
		case BYE:
			more = 0;
			return;
		case CHDIR:
			printf("cd not allowed\n");
			fflush(stdout);
			break;
		case LEARN:
			printf("You are already in learn.\n");
			fflush(stdout);
			break;
		case LOG:
			if (!logging)
				break;
			if (logfile[0] == 0) {
				snprintf(logfile, sizeof logfile,
				    "%s/log/%s", direct, sname);
			}
			f = fopen((r ? r : logfile), "a");
			if (f == NULL)
				break;
			time(&tval);
			tod = ctime(&tval);
			tod[24] = 0;
			fprintf(f, "%s L%-6s %s %2d %s\n", tod,
			    todo, status? "fail" : "pass", speed, pwline);
			fclose(f);
			break;
		}
	}
	return;
}
Ejemplo n.º 5
0
void update_id( D_MOBILE *dMob, I_ID *id )
{
   id->last_modified = ctime( &current_time );
   id->modified_by = strdup( dMob->name );
   return;
}
Ejemplo n.º 6
0
Archivo: local.c Proyecto: corecode/dma
int
deliver_local(struct qitem *it)
{
	char fn[PATH_MAX+1];
	char line[1000];
	const char *sender;
	const char *newline = "\n";
	size_t linelen;
	int tries = 0;
	int mbox;
	int error;
	int hadnl = 0;
	off_t mboxlen;
	time_t now = time(NULL);

	error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr);
	if (error < 0 || (size_t)error >= sizeof(fn)) {
		syslog(LOG_NOTICE, "local delivery deferred: %m");
		return (1);
	}

retry:
	/* wait for a maximum of 100s to get the lock to the file */
	do_timeout(100, 0);

	/* don't use O_CREAT here, because we might be running as the wrong user. */
	mbox = open_locked(fn, O_WRONLY|O_APPEND);
	if (mbox < 0) {
		int e = errno;

		do_timeout(0, 0);

		switch (e) {
		case EACCES:
		case ENOENT:
			/*
			 * The file does not exist or we can't access it.
			 * Call dma-mbox-create to create it and fix permissions.
			 */
			if (tries > 0 || create_mbox(it->addr) != 0) {
				syslog(LOG_ERR, "local delivery deferred: can not create `%s'", fn);
				return (1);
			}
			++tries;
			goto retry;

		case EINTR:
			syslog(LOG_NOTICE, "local delivery deferred: can not lock `%s'", fn);
			break;

		default:
			syslog(LOG_NOTICE, "local delivery deferred: can not open `%s': %m", fn);
			break;
		}
		return (1);
	}
	do_timeout(0, 0);

	mboxlen = lseek(mbox, 0, SEEK_END);

	/* New mails start with \nFrom ...., unless we're at the beginning of the mbox */
	if (mboxlen == 0)
		newline = "";

	/* If we're bouncing a message, claim it comes from MAILER-DAEMON */
	sender = it->sender;
	if (strcmp(sender, "") == 0)
		sender = "MAILER-DAEMON";

	if (fseek(it->mailf, 0, SEEK_SET) != 0) {
		syslog(LOG_NOTICE, "local delivery deferred: can not seek: %m");
		goto out;
	}

	error = snprintf(line, sizeof(line), "%sFrom %s %s", newline, sender, ctime(&now));
	if (error < 0 || (size_t)error >= sizeof(line)) {
		syslog(LOG_NOTICE, "local delivery deferred: can not write header: %m");
		goto out;
	}
	if (write(mbox, line, error) != error)
		goto wrerror;

	while (!feof(it->mailf)) {
		if (fgets(line, sizeof(line), it->mailf) == NULL)
			break;
		linelen = strlen(line);
		if (linelen == 0 || line[linelen - 1] != '\n') {
			syslog(LOG_CRIT, "local delivery failed: corrupted queue file");
			snprintf(errmsg, sizeof(errmsg), "corrupted queue file");
			error = -1;
			goto chop;
		}

		/*
		 * mboxro processing:
		 * - escape lines that start with "From " with a > sign.
		 * - be reversible by escaping lines that contain an arbitrary
		 *   number of > signs, followed by "From ", i.e. />*From / in regexp.
		 * - strict mbox processing only requires escaping after empty lines,
		 *   yet most MUAs seem to relax this requirement and will treat any
		 *   line starting with "From " as the beginning of a new mail.
		 */
		if ((!MBOX_STRICT || hadnl) &&
		    strncmp(&line[strspn(line, ">")], "From ", 5) == 0) {
			const char *gt = ">";

			if (write(mbox, gt, 1) != 1)
				goto wrerror;
			hadnl = 0;
		} else if (strcmp(line, "\n") == 0) {
			hadnl = 1;
		} else {
			hadnl = 0;
		}
		if ((size_t)write(mbox, line, linelen) != linelen)
			goto wrerror;
	}
	close(mbox);
	return (0);

wrerror:
	syslog(LOG_ERR, "local delivery failed: write error: %m");
	error = 1;
chop:
	if (ftruncate(mbox, mboxlen) != 0)
		syslog(LOG_WARNING, "error recovering mbox `%s': %m", fn);
out:
	close(mbox);
	return (error);
}
Ejemplo n.º 7
0
/* XXX THIS SHOULD BE IN SYSTEM !!!! */
void
erl_crash_dump_v(char *file, int line, char* fmt, va_list args)
{
#ifdef ERTS_SMP
    ErtsThrPrgrData tpd_buf; /* in case we aren't a managed thread... */
#endif
    int fd;
    time_t now;
    size_t dumpnamebufsize = MAXPATHLEN;
    char dumpnamebuf[MAXPATHLEN];
    char* dumpname;

    if (ERTS_SOMEONE_IS_CRASH_DUMPING)
	return;

#ifdef ERTS_SMP
    /*
     * Wait for all managed threads to block. If all threads haven't blocked
     * after a minute, we go anyway and hope for the best...
     *
     * We do not release system again. We expect an exit() or abort() after
     * dump has been written.
     */
    erts_thr_progress_fatal_error_block(60000, &tpd_buf);
    /* Either worked or not... */

    /* Allow us to pass certain places without locking... */
    erts_smp_atomic32_set_mb(&erts_writing_erl_crash_dump, 1);
    erts_smp_tsd_set(erts_is_crash_dumping_key, (void *) 1);
#else
    erts_writing_erl_crash_dump = 1;
#endif

    erts_sys_prepare_crash_dump();

    if (erts_sys_getenv_raw("ERL_CRASH_DUMP",&dumpnamebuf[0],&dumpnamebufsize) != 0)
	dumpname = "erl_crash.dump";
    else
	dumpname = &dumpnamebuf[0];

    fd = open(dumpname,O_WRONLY | O_CREAT | O_TRUNC,0640);
    if (fd < 0) 
	return; /* Can't create the crash dump, skip it */
    
    time(&now);
    erts_fdprintf(fd, "=erl_crash_dump:0.1\n%s", ctime(&now));

    if (file != NULL)
       erts_fdprintf(fd, "The error occurred in file %s, line %d\n", file, line);

    if (fmt != NULL && *fmt != '\0') {
	erts_fdprintf(fd, "Slogan: ");
	erts_vfdprintf(fd, fmt, args);
    }
    erts_fdprintf(fd, "System version: ");
    erts_print_system_version(fd, NULL, NULL);
    erts_fdprintf(fd, "%s\n", "Compiled: " ERLANG_COMPILE_DATE);
    erts_fdprintf(fd, "Taints: ");
    erts_print_nif_taints(fd, NULL);
    erts_fdprintf(fd, "Atoms: %d\n", atom_table_size());
    info(fd, NULL); /* General system info */
    if (erts_proc.tab)
	process_info(fd, NULL); /* Info about each process and port */
    db_info(fd, NULL, 0);
    erts_print_bif_timer_info(fd, NULL);
    distribution_info(fd, NULL);
    erts_fdprintf(fd, "=loaded_modules\n");
    loaded(fd, NULL);
    erts_dump_fun_entries(fd, NULL);
    erts_deep_process_dump(fd, NULL);
    erts_fdprintf(fd, "=atoms\n");
    dump_atoms(fd, NULL);

    /* Keep the instrumentation data at the end of the dump */
    if (erts_instr_memory_map || erts_instr_stat) {
	erts_fdprintf(fd, "=instr_data\n");

	if (erts_instr_stat) {
	    erts_fdprintf(fd, "=memory_status\n");
	    erts_instr_dump_stat_to_fd(fd, 0);
	}
	if (erts_instr_memory_map) {
	    erts_fdprintf(fd, "=memory_map\n");
	    erts_instr_dump_memory_map_to_fd(fd);
	}
    }

    erts_fdprintf(fd, "=end\n");
    close(fd);
    erts_fprintf(stderr,"\nCrash dump was written to: %s\n", dumpname);
}
Ejemplo n.º 8
0
/*
 * Dump the contents of a journal file.
 * @fn: journal filename to query.
 *
 * Each time mds restarts, it writes log entries starting from the very
 * first slot of the log.  Anyway, the function dumps all log entries,
 * some of them may be from previous incarnations of the MDS.
 */
void
sl_journal_dump(const char *fn)
{
	int i, ntotal, nmagic, nchksum, nformat, ndump, first = 1;
	uint32_t slot, highest_slot = -1, lowest_slot = -1;
	uint64_t chksum, highest_xid = 0, lowest_xid = 0;
	struct psc_journal_enthdr *pje;
	struct psc_journal_hdr *pjh;
	struct psc_journal *pj;
	struct stat statbuf;
	unsigned char *jbuf;
	ssize_t nb, pjhlen;
	time_t ts;

	ntotal = nmagic = nchksum = nformat = ndump = 0;

	pj = PSCALLOC(sizeof(*pj));

	strlcpy(pj->pj_name, pfl_basename(fn), sizeof(pj->pj_name));

	pj->pj_fd = open(fn, O_RDWR | O_DIRECT);
	if (pj->pj_fd == -1)
		psc_fatal("failed to open journal %s", fn);
	if (fstat(pj->pj_fd, &statbuf) == -1)
		psc_fatal("failed to stat journal %s", fn);

	/*
	 * O_DIRECT may impose alignment restrictions so align the
	 * buffer and perform I/O in multiples of file system block
	 * size.
	 */
	pjhlen = PSC_ALIGN(sizeof(*pjh), statbuf.st_blksize);
	pjh = psc_alloc(pjhlen, PAF_PAGEALIGN);
	nb = pread(pj->pj_fd, pjh, pjhlen, 0);
	if (nb != pjhlen)
		psc_fatal("failed to read journal header");

	pj->pj_hdr = pjh;
	if (pjh->pjh_magic != PJH_MAGIC)
		psc_fatalx("journal header has a bad magic number "
		    "%#"PRIx64, pjh->pjh_magic);

	if (pjh->pjh_version != PJH_VERSION)
		psc_fatalx("journal header has an invalid version "
		    "number %d", pjh->pjh_version);

	psc_crc64_init(&chksum);
	psc_crc64_add(&chksum, pjh, offsetof(struct psc_journal_hdr,
	    pjh_chksum));
	psc_crc64_fini(&chksum);

	if (pjh->pjh_chksum != chksum)
		psc_fatalx("journal header has an invalid checksum "
		    "value %"PSCPRIxCRC64" vs %"PSCPRIxCRC64,
		    pjh->pjh_chksum, chksum);

	if (S_ISREG(statbuf.st_mode) && statbuf.st_size !=
	    (off_t)(pjhlen + pjh->pjh_nents * PJ_PJESZ(pj)))
		psc_fatalx("size of the journal log %"PSCPRIdOFFT"d does "
		    "not match specs in its header", statbuf.st_size);

	if (pjh->pjh_nents % pjh->pjh_readsize)
		psc_fatalx("number of entries %d is not a multiple of the "
		    "readsize %d", pjh->pjh_nents, pjh->pjh_readsize);

	ts = pjh->pjh_timestamp;

	printf("%s:\n"
	    "  version: %u\n"
	    "  entry size: %u\n"
	    "  number of entries: %u\n"
	    "  batch read size: %u\n"
	    "  entry start offset: %"PRId64"\n"
	    "  format time: %s"
	    "  uuid: %"PRIx64"\n"
	    "  %8s %3s %12s %12s  %s\n",
	    fn, pjh->pjh_version, PJ_PJESZ(pj), pjh->pjh_nents,
	    pjh->pjh_readsize, pjh->pjh_start_off,
	    ctime(&ts), pjh->pjh_fsuuid,
	    "idx", "type", "xid", "txg", "details");

	jbuf = psc_alloc(PJ_PJESZ(pj) * pj->pj_hdr->pjh_readsize,
	    PAF_PAGEALIGN);
	for (slot = 0; slot < pjh->pjh_nents;
	    slot += pjh->pjh_readsize) {
		nb = pread(pj->pj_fd, jbuf, PJ_PJESZ(pj) *
		    pjh->pjh_readsize, PJ_GETENTOFF(pj, slot));
		if (nb != PJ_PJESZ(pj) * pjh->pjh_readsize)
			warn("failed to read %d log entries at slot %d",
			    pjh->pjh_readsize, slot);

		for (i = 0; i < pjh->pjh_readsize; i++) {
			ntotal++;
			pje = (void *)&jbuf[PJ_PJESZ(pj) * i];
			if (pje->pje_magic != PJE_MAGIC) {
				nmagic++;
				warnx("journal slot %d has a bad magic"
				    "number", slot + i);
				continue;
			}

			/*
			 * If we hit a new entry that is never used, we
			 * assume that the rest of the journal is never
			 * used.
			 */
			if (pje->pje_type == PJE_FORMAT) {
				nformat = nformat + pjh->pjh_nents -
				    (slot + i);
				goto done;
			}

			psc_crc64_init(&chksum);
			psc_crc64_add(&chksum, pje, offsetof(
			    struct psc_journal_enthdr, pje_chksum));
			psc_crc64_add(&chksum, pje->pje_data,
			    pje->pje_len);
			psc_crc64_fini(&chksum);

			if (pje->pje_chksum != chksum) {
				nchksum++;
				warnx("journal slot %d has a corrupt "
				    "checksum", slot + i);
				goto done;
			}
			ndump++;
			if (verbose)
				sl_journal_dump_entry(slot + i, pje);
			if (first) {
				first = 0;
				highest_xid = lowest_xid = pje->pje_xid;
				highest_slot = lowest_slot = slot + i;
				continue;
			}
			if (highest_xid < pje->pje_xid) {
				highest_xid = pje->pje_xid;
				highest_slot = slot + i;
			}
			if (lowest_xid > pje->pje_xid) {
				lowest_xid = pje->pje_xid;
				lowest_slot = slot + i;
			}
		}

	}

 done:
	if (close(pj->pj_fd) == -1)
		printf("failed closing journal %s", fn);

	psc_free(jbuf, PAF_PAGEALIGN, PJ_PJESZ(pj));
	PSCFREE(pj);

	printf("----------------------------------------------\n"
	    "%8d slot(s) scanned\n"
	    "%8d in use\n"
	    "%8d formatted\n"
	    "%8d bad magic\n"
	    "%8d bad checksum(s)\n"
	    "lowest transaction ID=%#"PRIx64" (slot=%d)\n"
	    "highest transaction ID=%#"PRIx64" (slot=%d)\n",
	    ntotal, ndump, nformat, nmagic, nchksum,
	    lowest_xid, lowest_slot,
	    highest_xid, highest_slot);
}
Ejemplo n.º 9
0
int
cray_setup (uid_t uid, char *username, const char *command)
{
	extern struct udb *getudb();
	extern char *setlimits();

	int err;			/* error return */
	time_t system_time;		/* current system clock */
	time_t expiration_time;		/* password expiration time */
	int maxattempts;		/* maximum no. of failed login attempts */
	int SecureSys;			/* unicos security flag */
	int minslevel = 0;		/* system minimum security level */
	int i, j;
	int valid_acct = -1;		/* flag for reading valid acct */
	char acct_name[MAXACID] = { "" }; /* used to read acct name */
	struct jtab jtab;		/* Job table struct */
	struct udb ue;			/* udb entry for logging-in user */
	struct udb *up;			/* pointer to UDB entry */
	struct secstat secinfo;		/* file  security attributes */
	struct servprov init_info;	/* used for sesscntl() call */
	int jid;			/* job ID */
	int pid;			/* process ID */
	char *sr;			/* status return from setlimits() */
	char *ttyn = NULL;		/* ttyname or command name*/
	char hostname[MAXHOSTNAMELEN];
	/* passwd stuff for ia_user */
	passwd_t pwdacm, pwddialup, pwdudb, pwdwal, pwddce;
	ia_user_ret_t uret;		/* stuff returned from ia_user */
	ia_user_t usent;		/* ia_user main structure */
	int ia_rcode;			/* ia_user return code */
	ia_failure_t fsent;		/* ia_failure structure */
	ia_failure_ret_t fret;		/* ia_failure return stuff */
	ia_success_t ssent;		/* ia_success structure */
	ia_success_ret_t sret;		/* ia_success return stuff */
	int ia_mlsrcode;		/* ia_mlsuser return code */
	int secstatrc;			/* [f]secstat return code */

	if (SecureSys = (int)sysconf(_SC_CRAY_SECURE_SYS)) {
		getsysv(&sysv, sizeof(struct sysv));
		minslevel = sysv.sy_minlvl;
		if (getusrv(&usrv) < 0)
			fatal("getusrv() failed, errno = %d", errno);
	}
	hostname[0] = '\0';
	strlcpy(hostname,
	   (char *)get_canonical_hostname(options.use_dns),
	   MAXHOSTNAMELEN);
	/*
	 *  Fetch user's UDB entry.
	 */
	getsysudb();
	if ((up = getudbnam(username)) == UDB_NULL)
		fatal("cannot fetch user's UDB entry");

	/*
	 *  Prevent any possible fudging so perform a data
	 *  safety check and compare the supplied uid against
	 *  the udb's uid.
	 */
	if (up->ue_uid != uid)
		fatal("IA uid missmatch");
	endudb();

	if ((jid = getjtab(&jtab)) < 0) {
		debug("getjtab");
		return(-1);
	}
	pid = getpid();
	ttyn = ttyname(0);
	if (SecureSys) {
		if (ttyn != NULL)
			secstatrc = secstat(ttyn, &secinfo);
		else
			secstatrc = fsecstat(1, &secinfo);

		if (secstatrc == 0)
			debug("[f]secstat() successful");
		else
			fatal("[f]secstat() error, rc = %d", secstatrc);
	}
	if ((ttyn == NULL) && ((char *)command != NULL))
		ttyn = (char *)command;
	/*
	 *  Initialize all structures to call ia_user
	 */
	usent.revision = 0;
	usent.uname = username;
	usent.host = hostname;
	usent.ttyn = ttyn;
	usent.caller = IA_SSHD; 
	usent.pswdlist = &pwdacm;
	usent.ueptr = &ue;
	usent.flags = IA_INTERACTIVE | IA_FFLAG;
	pwdacm.atype = IA_SECURID;
	pwdacm.pwdp = NULL;
	pwdacm.next = &pwdudb;

	pwdudb.atype = IA_UDB;
	pwdudb.pwdp = NULL;
	pwdudb.next = &pwddce;

	pwddce.atype = IA_DCE;
	pwddce.pwdp = NULL;
	pwddce.next = &pwddialup;

	pwddialup.atype = IA_DIALUP;
	pwddialup.pwdp = NULL;
	/* pwddialup.next = &pwdwal; */
	pwddialup.next = NULL;

	pwdwal.atype = IA_WAL;
	pwdwal.pwdp = NULL;
	pwdwal.next = NULL;

	uret.revision = 0;
	uret.pswd = NULL;
	uret.normal = 0;

	ia_rcode = ia_user(&usent, &uret);
	switch (ia_rcode) {
	/*
	 *  These are acceptable return codes from ia_user()
	 */
	case IA_UDBWEEK:        /* Password Expires in 1 week */
		expiration_time = ue.ue_pwage.time + ue.ue_pwage.maxage;
		printf ("WARNING - your current password will expire %s\n",
		ctime((const time_t *)&expiration_time));
		break;
	case IA_UDBEXPIRED:
		if (ttyname(0) != NULL) {
			/* Force a password change */
			printf("Your password has expired; Choose a new one.\n");
			execl("/bin/passwd", "passwd", username, 0);
			exit(9);
			}
		break;
	case IA_NORMAL:         /* Normal Return Code */
		break;
	case IA_BACKDOOR:
		/* XXX: can we memset it to zero here so save some of this */
		strlcpy(ue.ue_name, "root", sizeof(ue.ue_name));
		strlcpy(ue.ue_dir, "/", sizeof(ue.ue_dir));
		strlcpy(ue.ue_shell, "/bin/sh", sizeof(ue.ue_shell));

		ue.ue_passwd[0] = '\0';
		ue.ue_age[0] = '\0';
		ue.ue_comment[0] = '\0';
		ue.ue_loghost[0] = '\0';
		ue.ue_logline[0] = '\0';

		ue.ue_uid = -1;
		ue.ue_nice[UDBRC_INTER] = 0;

		for (i = 0; i < MAXVIDS; i++)
			ue.ue_gids[i] = 0;

		ue.ue_logfails = 0;
		ue.ue_minlvl = ue.ue_maxlvl = ue.ue_deflvl = minslevel;
		ue.ue_defcomps = 0;
		ue.ue_comparts = 0;
		ue.ue_permits = 0;
		ue.ue_trap = 0;
		ue.ue_disabled = 0;
		ue.ue_logtime = 0;
		break;
	case IA_CONSOLE:        /* Superuser not from Console */
	case IA_TRUSTED:	/* Trusted user */
		if (options.permit_root_login > PERMIT_NO)
			break;	/* Accept root login */
	default:
	/*
	 *  These are failed return codes from ia_user()
	 */
		switch (ia_rcode) 
		{
		case IA_BADAUTH:
			printf("Bad authorization, access denied.\n");
			break;
		case IA_DISABLED:
			printf("Your login has been disabled. Contact the system ");
			printf("administrator for assistance.\n");
			break;
		case IA_GETSYSV:
			printf("getsysv() failed - errno = %d\n", errno);
			break;
		case IA_MAXLOGS:
			printf("Maximum number of failed login attempts exceeded.\n");
			printf("Access denied.\n");
			break;
		case IA_UDBPWDNULL:
			if (SecureSys)
				printf("NULL Password not allowed on MLS systems.\n");
			break;
		default:
			break;
		}

		/*
		 *  Authentication failed.
		 */
		printf("sshd: Login incorrect, (0%o)\n",
		    ia_rcode-IA_ERRORCODE);

		/*
		 *  Initialize structure for ia_failure
		 *  which will exit.
		 */
		fsent.revision = 0;
		fsent.uname = username;
		fsent.host = hostname;
		fsent.ttyn = ttyn;
		fsent.caller = IA_SSHD;
		fsent.flags = IA_INTERACTIVE;
		fsent.ueptr = &ue;
		fsent.jid = jid;
		fsent.errcode = ia_rcode;
		fsent.pwdp = uret.pswd;
		fsent.exitcode = 1;

		fret.revision = 0;
		fret.normal = 0;

		/*
		*  Call ia_failure because of an IA failure.
		*  There is no return because ia_failure exits.
		*/
		ia_failure(&fsent, &fret);

		exit(1); 
	}

	ia_mlsrcode = IA_NORMAL;
	if (SecureSys) {
		debug("calling ia_mlsuser()");
		ia_mlsrcode = ia_mlsuser(&ue, &secinfo, &usrv, NULL, 0);
	}
	if (ia_mlsrcode != IA_NORMAL) {
		printf("sshd: Login incorrect, (0%o)\n",
		    ia_mlsrcode-IA_ERRORCODE);
		/*
		 *  Initialize structure for ia_failure
		 *  which will exit.
		 */
		fsent.revision = 0;
		fsent.uname = username;
		fsent.host = hostname;
		fsent.ttyn = ttyn;
		fsent.caller = IA_SSHD;
		fsent.flags = IA_INTERACTIVE;
		fsent.ueptr = &ue;
		fsent.jid  = jid;
		fsent.errcode = ia_mlsrcode;
		fsent.pwdp = uret.pswd;
		fsent.exitcode = 1;
		fret.revision = 0;
		fret.normal = 0;

		/*
		 *  Call ia_failure because of an IA failure.
		 *  There is no return because ia_failure exits.
		 */
		ia_failure(&fsent,&fret);
		exit(1); 
	}

	/* Provide login status information */
	if (options.print_lastlog && ue.ue_logtime != 0) {
		printf("Last successful login was : %.*s ", 19,
		    (char *)ctime(&ue.ue_logtime));

		if (*ue.ue_loghost != '\0') {
			printf("from %.*s\n", sizeof(ue.ue_loghost),
			    ue.ue_loghost);
		} else {
			printf("on %.*s\n", sizeof(ue.ue_logline),
			    ue.ue_logline);
		}

		if (SecureSys && (ue.ue_logfails != 0)) {
			printf("  followed by %d failed attempts\n",
			    ue.ue_logfails);
		}
	}

	/*
	 * Call ia_success to process successful I/A.
	 */
	ssent.revision = 0;
	ssent.uname = username;
	ssent.host = hostname;
	ssent.ttyn = ttyn;
	ssent.caller = IA_SSHD;
	ssent.flags = IA_INTERACTIVE;
	ssent.ueptr = &ue;
	ssent.jid = jid;
	ssent.errcode = ia_rcode;
	ssent.us = NULL;
	ssent.time = 1;	/* Set ue_logtime */

	sret.revision = 0;
	sret.normal = 0;

	ia_success(&ssent, &sret);

	/*
	 * Query for account, iff > 1 valid acid & askacid permbit
	 */
	if (((ue.ue_permbits & PERMBITS_ACCTID) ||
	    (ue.ue_acids[0] >= 0) && (ue.ue_acids[1] >= 0)) &&
	    ue.ue_permbits & PERMBITS_ASKACID) {
		if (ttyname(0) != NULL) {
			debug("cray_setup: ttyname true case, %.100s", ttyname);
			while (valid_acct == -1) {
				printf("Account (? for available accounts)"
				    " [%s]: ", acid2nam(ue.ue_acids[0]));
				fgets(acct_name, MAXACID, stdin);
				switch (acct_name[0]) {
				case EOF:
					exit(0);
					break;
				case '\0':
					valid_acct = ue.ue_acids[0];
					strlcpy(acct_name, acid2nam(valid_acct), MAXACID);
					break;
				case '?':
					/* Print the list 3 wide */
					for (i = 0, j = 0; i < MAXVIDS; i++) {
						if (ue.ue_acids[i] == -1) {
							printf("\n");
							break;
						}
						if (++j == 4) {
							j = 1;
							printf("\n");
						}
						printf(" %s",
						    acid2nam(ue.ue_acids[i]));
					}
					if (ue.ue_permbits & PERMBITS_ACCTID) {
						printf("\"acctid\" permbit also allows"
						    " you to select any valid "
						    "account name.\n");
					}
					printf("\n");
					break;
				default:
					valid_acct = nam2acid(acct_name);
					if (valid_acct == -1) 
						printf(
						    "Account id not found for"
						    " account name \"%s\"\n\n",
						    acct_name);
					break;
				}
				/*
				 * If an account was given, search the user's
				 * acids array to verify they can use this account.
				 */
				if ((valid_acct != -1) &&
				    !(ue.ue_permbits & PERMBITS_ACCTID)) {
					for (i = 0; i < MAXVIDS; i++) {
						if (ue.ue_acids[i] == -1)
							break;
						if (valid_acct == ue.ue_acids[i])
							break;
					}
					if (i == MAXVIDS ||
					    ue.ue_acids[i] == -1) {
						fprintf(stderr, "Cannot set"
						    " account name to "
						    "\"%s\", permission "
						    "denied\n\n", acct_name);
						valid_acct = -1;
					}
				}
			}
		} else {
			/*
			 * The client isn't connected to a terminal and can't
			 * respond to an acid prompt.  Use default acid.
			 */
			debug("cray_setup: ttyname false case, %.100s",
			    ttyname);
			valid_acct = ue.ue_acids[0];
		}
	} else {
		/*
		 * The user doesn't have the askacid permbit set or
		 * only has one valid account to use.
		 */
		valid_acct = ue.ue_acids[0];
	}
	if (acctid(0, valid_acct) < 0) {
		printf ("Bad account id: %d\n", valid_acct);
		exit(1);
	}

	/* 
	 * Now set shares, quotas, limits, including CPU time for the 
	 * (interactive) job and process, and set up permissions 
	 * (for chown etc), etc.
	 */
	if (setshares(ue.ue_uid, valid_acct, printf, 0, 0)) {
		printf("Unable to give %d shares to <%s>(%d/%d)\n",
		    ue.ue_shares, ue.ue_name, ue.ue_uid, valid_acct);
		exit(1);
	}

	sr = setlimits(username, C_PROC, pid, UDBRC_INTER);
	if (sr != NULL) {
		debug("%.200s", sr);
		exit(1);
	}
	sr = setlimits(username, C_JOB, jid, UDBRC_INTER);
	if (sr != NULL) {
		debug("%.200s", sr);
		exit(1);
	}
	/*
	 * Place the service provider information into
	 * the session table (Unicos) or job table (Unicos/mk).
	 * There exist double defines for the job/session table in
	 * unicos/mk (jtab.h) so no need for a compile time switch.
	 */
	memset(&init_info, '\0', sizeof(init_info));
	init_info.s_sessinit.si_id = URM_SPT_LOGIN;
	init_info.s_sessinit.si_pid = getpid();
	init_info.s_sessinit.si_sid = jid;
	sesscntl(0, S_SETSERVPO, (int)&init_info);

	/*
	 * Set user and controlling tty security attributes.
	 */
	if (SecureSys) {
		if (setusrv(&usrv) == -1) {
			debug("setusrv() failed, errno = %d",errno);
			exit(1);
		}
	}

	return (0);
}
Ejemplo n.º 10
0
void repeat_refresh() {
    today = ctime(time())[4..9];
    call_out((:repeat_refresh:),86400);
}
Ejemplo n.º 11
0
void refresh() {
    today = ctime(time())[4..9];
}
Ejemplo n.º 12
0
/* This procedure will dump the configuration data into an organized format,
   optionally into a file. Between the dumped data one may find the current
   date of the test and the output and input file name. For understand these
   lines, go through the printed strings. It can't be hard. */
void dump_config(FILE* fp, const parameter_t* par) 
{
  time_t current_time = time(NULL); /* just a dummy variable for timing */
  char temp[100]; /* for temporary strings */

  fprintf(fp, "-+- CONFIGURATION PARAMETERS\n");
  fprintf(fp, " +- Date: %s", ctime(&current_time));
  fprintf(fp, " +- Input File: %s\n", par->ifname);

  if (par->output_file)
    fprintf(fp, " +- Output File: %s.data \n", par->ofhint);
  else
    fprintf(fp, " +- Output File: [redirected to standard output]\n");

  fprintf(fp, " +- Output Information: ");
  if (par->dump_rings) fprintf(fp, "Rings\n");
  else if (par->dump_digis) fprintf(fp, "Digis\n");
  else if (par->dump_uniform_digis) fprintf(fp, "Uniform Digis\n");
  else fprintf(fp, "Uniform Rois\n");

  /* The type of dumped information and normalization */
  if (! par->dump_digis ) {
    fprintf(fp, " +- Uniformizing Selection: %s\n",
	    layer2string(&par->layer_flags,temp));
    if (! par->dump_uniform_digis ) {
      fprintf(fp, " +- Printing Selection: %s\n",
	      layer2string(&par->print_flags,temp));
      fprintf(fp, " +- Normalization: %s\n",
	      normalization2string(&par->normalization,temp));

      if ( normal_is_weighted_all(&par->normalization) ||
	   normal_is_weighted_seg(&par->normalization) ) {
	int i;
	fprintf(fp, " +- Stop Rings (Weighted Norm.): ");
	for (i=0; i<par->config_weighted.nlayers; ++i)
	  fprintf(fp, "%d ", par->config_weighted.last2norm[i]);
	fprintf(fp, "\n");
      }

      if ( par->max_radius > 0 )
	fprintf(fp, " +- Maximum normalization radius: %e\n", par->max_radius);
    }
  }

  /* The event accouting */
  fprintf(fp, " +- Event number dumping: %s\n", 
	  (par->dump_eventno)?"Yes":"No" );

  /* The event number filename */
  if (par->eventno_file && par->dump_eventno) {
    if (par->evfp != par->ofp)
      fprintf(fp, " +- Event-number File: %s.eventno \n", par->ofhint); 
    else
      fprintf(fp, " +- Event-number File: %s.data \n", par->ofhint);
  }

  /* The event number comment string, if it exists */
  if (strcmp(par->event_comment_str, "") != 0 )
    fprintf(fp, " +- Event number comment string: %s\n", 
	    par->event_comment_str);

  /* What types of energy are going to be printed */
  fprintf(fp, " +- Energy printing: %s\n", 
	  edump2string(&par->dump_energy,temp));

  /* The energy filename */
  if (par->energy_file && par->dump_energy) {
    if (par->efp != par->ofp)
      fprintf(fp, " +- Energy File: %s.energy \n", par->ofhint); 
    else 
      fprintf(fp, " +- Energy File: %s.data \n", par->ofhint);
  }

  /* The energy comment string, if it exists */
  if (strcmp(par->edump_comment_str, "") != 0 )
    fprintf(fp, " +- Energy comment string: %s\n", par->edump_comment_str);

  fprintf(fp, " +- Output Format: ");
  if (par->format_snns) {
    fprintf(fp, "SNNS\n");
    fprintf(fp, " +- Particle Type for SNNS targets: ");
    if (par->particle == JET) fprintf(fp, "Jet\n");
    else fprintf(fp, "Electron\n");
  }
  else fprintf(fp, "Raw\n");

  if (par->process_all_rois)
    fprintf(fp, " +- Processing: All Events\n");
  else
    fprintf(fp, " +- Processing: Event %ld, RoI %ld\n", 
	    par->event_no, par->roi_no);
  
  fprintf(fp, " +- Verbose output: %s\n", (par->verbose)?"YES":"NO");

  if (par->run_fast)
    fprintf(fp, " +- Fast Processing: YES (using obstacks)\n");
  else
    fprintf(fp, " +- Fast Processing: NO (using common files)\n");

  fprintf(fp, " +- Number of events per DB read in: %ld", par->load_events);
  fprintf(fp, " (total no. of events could be less)\n");

  fprintf(fp, "==========================================\n");

  /* close the configuration file pointer, so, no need to do it
     afterwards. This can only be done *IF* the pointer is *NOT* a pointer to
     stdout or to a common output file! */
  if (fp != stdout || fp != par->ofp) fclose(fp);
  
}
Ejemplo n.º 13
0
void linphone_gtk_call_log_update(GtkWidget *w){
	GtkTreeView *v=GTK_TREE_VIEW(linphone_gtk_get_widget(w,"logs_view"));
	GtkTreeStore *store;
	const MSList *logs;
	GtkTreeSelection *select;
	GtkWidget *notebook=linphone_gtk_get_widget(w,"viewswitch");
	gint nb;

	store=(GtkTreeStore*)gtk_tree_view_get_model(v);
	if (store==NULL){
		store=gtk_tree_store_new(3,GDK_TYPE_PIXBUF,G_TYPE_STRING,G_TYPE_POINTER,G_TYPE_STRING);
		gtk_tree_view_set_model(v,GTK_TREE_MODEL(store));
		g_object_unref(G_OBJECT(store));
		fill_renderers(GTK_TREE_VIEW(linphone_gtk_get_widget(w,"logs_view")));
		select=gtk_tree_view_get_selection(v);
		gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE);
		g_signal_connect_swapped(G_OBJECT(select),"changed",(GCallback)call_log_selection_changed,v);
		g_signal_connect(G_OBJECT(notebook),"focus-tab",(GCallback)linphone_gtk_call_log_reset_missed_call,NULL);
		g_signal_connect(G_OBJECT(v),"button-press-event",(GCallback)linphone_gtk_call_log_button_pressed,NULL);
//		gtk_button_set_image(GTK_BUTTON(linphone_gtk_get_widget(w,"call_back_button")),
//		                     create_pixmap (linphone_gtk_get_ui_config("callback_button","status-green.png")));
	}
	nb=linphone_core_get_missed_calls_count(linphone_gtk_get_core());
	if(nb > 0)
		linphone_gtk_call_log_display_missed_call(nb);
	gtk_tree_store_clear (store);

	for (logs=linphone_core_get_call_logs(linphone_gtk_get_core());logs!=NULL;logs=logs->next){
		LinphoneCallLog *cl=(LinphoneCallLog*)logs->data;
		GtkTreeIter iter, iter2;
		LinphoneAddress *la=linphone_call_log_get_dir(cl)==LinphoneCallIncoming ? linphone_call_log_get_from(cl) : linphone_call_log_get_to(cl);
		char *addr= linphone_address_as_string(la);
		const char *display;
		gchar *logtxt, *headtxt, *minutes, *seconds;
		gchar quality[20];
		const char *status=NULL;
		gchar *start_date=NULL;
		LinphoneFriend *lf=NULL;
		int duration=linphone_call_log_get_duration(cl);
		time_t start_date_time=linphone_call_log_get_start_date(cl);
		
#if GLIB_CHECK_VERSION(2,26,0)
		if (start_date_time){
			GDateTime *dt=g_date_time_new_from_unix_local(start_date_time);
			start_date=g_date_time_format(dt,"%c");
			g_date_time_unref(dt);
		}
#else
		start_date=g_strdup(ctime(&start_date_time));
#endif
		lf=linphone_core_get_friend_by_address(linphone_gtk_get_core(),addr);
		if(lf != NULL){
			if ((display=linphone_address_get_display_name(linphone_friend_get_address(lf)))) {
				/*update display name from friend*/
				linphone_address_set_display_name(la,display);
			}
		} else {
			display=linphone_address_get_display_name(la);
		}
		if (display==NULL){
			display=linphone_address_get_username (la);
			if (display==NULL){
				display=linphone_address_get_domain (la);
			}
		}

		if (linphone_call_log_get_quality(cl)!=-1){
			snprintf(quality,sizeof(quality),"%.1f",linphone_call_log_get_quality(cl));
		}else snprintf(quality,sizeof(quality)-1,"%s",_("n/a"));
		switch(linphone_call_log_get_status(cl)){
			case LinphoneCallAborted:
				status=_("Aborted");
			break;
			case LinphoneCallMissed:
				status=_("Missed");
			break;
			case LinphoneCallDeclined:
				status=_("Declined");
			break;
			default:
			break;
		}
		minutes=g_markup_printf_escaped(
			ngettext("%i minute", "%i minutes", duration/60),
			duration/60);
		seconds=g_markup_printf_escaped(
			ngettext("%i second", "%i seconds", duration%60),
			duration%60);
		if (status==NULL) {
				headtxt=g_markup_printf_escaped(_("<big><b>%s</b></big>\t%s"),display,start_date ? start_date : "");
				logtxt=g_markup_printf_escaped(
				_("<small><i>%s</i>\t" 
				  "<i>Quality: %s</i></small>\n%s\t%s\t"),
				addr, quality, minutes, seconds);
		} else {
			headtxt=g_markup_printf_escaped(_("<big><b>%s</b></big>\t%s"),display,start_date ? start_date : "");
			logtxt=g_markup_printf_escaped(
			_("<small><i>%s</i></small>\t"
				"\n%s"),addr, status);
		}
		g_free(minutes);
		g_free(seconds);
		if (start_date) g_free(start_date);
		gtk_tree_store_append (store,&iter,NULL);

		GdkPixbuf *incoming = create_pixbuf("call_status_incoming.png");
		GdkPixbuf *outgoing = create_pixbuf("call_status_outgoing.png");
		gtk_tree_store_set (store,&iter,
		               0, linphone_call_log_get_dir(cl)==LinphoneCallOutgoing ? outgoing : incoming,
		               1, headtxt,2,cl,-1);
		gtk_tree_store_append (store,&iter2,&iter);
		gtk_tree_store_set (store,&iter2,1,logtxt,-1);
		ms_free(addr);
		g_free(logtxt);
		g_free(headtxt);
	}
}
Ejemplo n.º 14
0
static void MonLogSymbolicValue(EvalContext *ctx, const char *handle, Item *stream,
                                 Attributes a, const Promise *pp, PromiseResult *result)
{
 char value[CF_BUFSIZE], sdate[CF_MAXVARSIZE], filename[CF_BUFSIZE], *v;
 int count = 1, found = false, match_count = 0;
 Item *ip, *match = NULL, *matches = NULL;
 time_t now = time(NULL);
 FILE *fout;
 
 if (stream == NULL)
    {
    Log(LOG_LEVEL_VERBOSE, "No stream to measure");
    return;
    }
 
 Log(LOG_LEVEL_VERBOSE, "Locate and log sample ...");
 
 for (ip = stream; ip != NULL; ip = ip->next)
    {
    if (ip->name == NULL)
       {
       continue;
       }
    
    if (count == a.measure.select_line_number)
       {
       Log(LOG_LEVEL_VERBOSE, "Found line %d by number...", count);
       found = true;
       match_count = 1;
       match = ip;
       
       if (a.measure.extraction_regex)
          {
          Log(LOG_LEVEL_VERBOSE, "Now looking for a matching extractor \"%s\"", a.measure.extraction_regex);
          strncpy(value, ExtractFirstReference(a.measure.extraction_regex, match->name), CF_MAXVARSIZE - 1);
          Log(LOG_LEVEL_INFO, "Extracted value \"%s\" for promise \"%s\"", value, handle);
          AppendItem(&matches, value, NULL);
          
          }
       break;
       }
    
    if (a.measure.select_line_matching && StringMatchFull(a.measure.select_line_matching, ip->name))
       {
       Log(LOG_LEVEL_VERBOSE, "Found line %d by pattern...", count);
       found = true;
       match = ip;
       match_count++;
       
       if (a.measure.extraction_regex)
          {
          Log(LOG_LEVEL_VERBOSE, "Now looking for a matching extractor \"%s\"", a.measure.extraction_regex);
          strncpy(value, ExtractFirstReference(a.measure.extraction_regex, match->name), CF_MAXVARSIZE - 1);
          Log(LOG_LEVEL_INFO, "Extracted value \"%s\" for promise \"%s\"", value, handle);
          AppendItem(&matches, value, NULL);
          }
       }
    
    count++;
    }
 
 if (!found)
    {
    cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Promiser '%s' found no matching line.", pp->promiser);
    *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
    return;
    }
 
 if (match_count > 1)
    {
    Log(LOG_LEVEL_INFO, "Warning: %d lines matched the line_selection \"%s\"- matching to last", match_count,
        a.measure.select_line_matching);
    }
 
 switch (a.measure.data_type)
    {
    case CF_DATA_TYPE_COUNTER:
        Log(LOG_LEVEL_VERBOSE, "Counted %d for %s", match_count, handle);
        snprintf(value, CF_MAXVARSIZE, "%d", match_count);
        break;
        
    case CF_DATA_TYPE_STRING_LIST:
        v = ItemList2CSV(matches);
        snprintf(value, CF_BUFSIZE, "%s", v);
        free(v);
        break;
        
    default:
        snprintf(value, CF_BUFSIZE, "%s", matches->name);
    }
 
 DeleteItemList(matches);
 
 if (a.measure.history_type && strcmp(a.measure.history_type, "log") == 0)
    {
    snprintf(filename, CF_BUFSIZE, "%s%cstate%c%s_measure.log", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR, handle);
    
    if ((fout = fopen(filename, "a")) == NULL)
       {
       cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to open the output log \"%s\"", filename);
       *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
       PromiseRef(LOG_LEVEL_ERR, pp);
       return;
       }
    
    strncpy(sdate, ctime(&now), CF_MAXVARSIZE - 1);
    if (Chop(sdate, CF_EXPANDSIZE) == -1)
       {
       Log(LOG_LEVEL_ERR, "Chop was called on a string that seemed to have no terminator");
       }
    
    fprintf(fout, "%s,%ld,%s\n", sdate, (long) now, value);
    Log(LOG_LEVEL_VERBOSE, "Logging: %s,%s to %s", sdate, value, filename);
    
    fclose(fout);
    }
 else                        // scalar or static
    {
    CF_DB *dbp;
    char id[CF_MAXVARSIZE];
    
    if (!OpenDB(&dbp, dbid_static))
       {
       return;
       }
    
    snprintf(id, CF_MAXVARSIZE - 1, "%s:%d", handle, a.measure.data_type);
    WriteDB(dbp, id, value, strlen(value) + 1);
    CloseDB(dbp);
    }
}
Ejemplo n.º 15
0
int
main(int argc, const char *const argv[], const char *const envp[])
{
    ifmon_t *ifmons;
    char **ifnames;
    int nifs;
    int ret;
    int flags;
    int ch;
    double delta;
    double dtxb;
    double drxb;
    double dtxp;
    double drxp;
    int i;

    if ( 2 > argc ) {
        _usage(argv[0]);
    }
    /* Get interfaces */
    nifs = argc - 1;
    ifnames = malloc(sizeof(char *) * nifs);
    if ( NULL == ifnames ) {
        perror("malloc()");
        return EXIT_FAILURE;
    }
    ifmons = malloc(sizeof(ifmon_t) * nifs);
    if ( NULL == ifmons ) {
        perror("malloc()");
        return EXIT_FAILURE;
    }
    for ( i = 0; i < nifs; i++ ) {
        ifnames[i] = strdup(argv[i+1]);
        if ( NULL == ifnames[i] ) {
            perror("strdup()");
            return EXIT_FAILURE;
        }
        if ( NULL == ifmon_init(&ifmons[i], ifnames[i]) ) {
            /* Error */
            fprintf(stderr, "Error: ifname=%s\n", ifnames[i]);
            return EXIT_FAILURE;
        }
    }

#if WITH_CURSES
    /* curses */
    if ( NULL == initscr() ) {
        fprintf(stderr, "initscr(): Cannot initialize screen\n");
        return EXIT_FAILURE;
    }
    cbreak();
    noecho();
    scrollok(stdscr, FALSE);
    move(0, 0);
#endif

    /* Set stdin as non-blocking */
    flags = fcntl(STDIN_FILENO, F_GETFL, 0);
    if ( -1 == flags ) {
        flags = 0;
    }
    fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);

    for ( ;; ) {
#if WITH_CURSES
        ch = getch();
        if ( 'q' == ch ) {
            break;
        }
#endif

        for ( i = 0; i < nifs; i++ ) {
            ret = ifmon_update(&ifmons[i]);
            if ( 0 != ret ) {
                /* Error */
                break;
            }
        }

#if WITH_CURSES
        clear();
#endif

#if WITH_CURSES
        time_t timer;
        time(&timer);

        /*
          struct tm *tm;
          tm = localtime(&timer);
         */

        /*printw("Time: %.6f\n", );*/
        printw("Interface statistics\n%s\n", ctime(&timer));
        printw("                       pkts/s                    kbps\n");
        printw("                   TX          RX            TX          RX\n");
#endif
        for ( i = 0; i < nifs; i++ ) {
            delta = ifmons[i].curstat.time - ifmons[i].prevstat.time;
            dtxp = ifmons[i].curstat.total_pkts.tx
                - ifmons[i].prevstat.total_pkts.tx;
            drxp = ifmons[i].curstat.total_pkts.rx
                - ifmons[i].prevstat.total_pkts.rx;
            dtxb = ifmons[i].curstat.total_bytes.tx
                - ifmons[i].prevstat.total_bytes.tx;
            drxb = ifmons[i].curstat.total_bytes.rx
                - ifmons[i].prevstat.total_bytes.rx;
#if WITH_CURSES
            printw("%-8.8s: %11.02lf %11.02lf   %11.02lf %11.02lf\n",
                   ifnames[i], dtxp/delta, drxp/delta,
                   8*dtxb/delta/1000, 8*drxb/delta/1000);
#else
            printf("%-8.8s: %11.02lf %11.02lf   %11.02lf %11.02lf\n",
                   ifnames[i], dtxp/delta, drxp/delta,
                   8*dtxb/delta/1000, 8*drxb/delta/1000);
#endif
        }

#if 0
        printw("Time: %.6f (%.6f)\n",
               ifmon.curstat.time, ifmon.curstat.time - ifmon.prevstat.time);
        printw("\tTX: %15llu pkts\tRX: %15llu pkts\n",
               ifmon.curstat.total_pkts.tx - ifmon.prevstat.total_pkts.tx,
               ifmon.curstat.total_pkts.rx - ifmon.prevstat.total_pkts.rx);
        printw("\tTX: %15llu bytes\tRX: %15llu bytes\n",
               ifmon.curstat.total_bytes.tx - ifmon.prevstat.total_bytes.tx,
               ifmon.curstat.total_bytes.rx - ifmon.prevstat.total_bytes.rx);
#endif

#if WITH_CURSES
        refresh();
#endif
        sleep(1);
    }

#if WITH_CURSES
    /* End curses */
    endwin();
#endif

    return 0;
}
Ejemplo n.º 16
0
/*
 * Print
 *  sysname: time: mesg
 * on /sys/log/logname.
 * If cons or log file can't be opened, print on the system console, too.
 */
void
syslog(int cons, const char *logname, const char *fmt, ...)
{
	char buf[1024];
	char *ctim, *p;
	va_list arg;
	int n;
	Dir *d;
	char err[ERRMAX];

	err[0] = '\0';
	errstr(err, sizeof err);
	lock(&sl);

	/*
	 *  paranoia makes us stat to make sure a fork+close
	 *  hasn't broken our fd's
	 */
	d = dirfstat(sl.fd);
	if(sl.fd < 0 || sl.name == nil || strcmp(sl.name, logname) != 0 ||
	   !eqdirdev(d, sl.d)){
		free(sl.name);
		sl.name = strdup(logname);
		if(sl.name == nil)
			cons = 1;
		else{
			free(sl.d);
			sl.d = nil;
			_syslogopen();
			if(sl.fd < 0)
				cons = 1;
			else
				sl.d = dirfstat(sl.fd);
		}
	}
	free(d);
	if(cons){
		d = dirfstat(sl.consfd);
		if(sl.consfd < 0 || !eqdirdev(d, sl.consd)){
			free(sl.consd);
			sl.consd = nil;
			sl.consfd = open("#c/cons", OWRITE|OCEXEC);
			if(sl.consfd >= 0)
				sl.consd = dirfstat(sl.consfd);
		}
		free(d);
	}

	if(fmt == nil){
		unlock(&sl);
		return;
	}

	ctim = ctime(time(0));
	p = buf + snprint(buf, sizeof(buf)-1, "%s ", sysname());
	strncpy(p, ctim+4, 15);
	p += 15;
	*p++ = ' ';
	errstr(err, sizeof err);
	va_start(arg, fmt);
	p = vseprint(p, buf+sizeof(buf)-1, fmt, arg);
	va_end(arg);
	*p++ = '\n';
	n = p - buf;

	if(sl.fd >= 0){
		seek(sl.fd, 0, 2);
		write(sl.fd, buf, n);
	}

	if(cons && sl.consfd >=0)
		write(sl.consfd, buf, n);

	unlock(&sl);
}
void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
	const struct ether_header *ethernet;  /* The ethernet header [1] */
	const struct sniff_ip *ip;              /* The IP header */
	const struct sniff_tcp *tcp;    
	ethernet=(struct ether_header*)pkt_data;        /* The TCP header */
	u_char *ptr;
	int size_ip;
	int size_tcp;
	int size_udp;
	int i;
	if(count==1)
	{
	printf("Start time and date of the capture is: %s\n",ctime(&header->ts.tv_sec)); 
	start=header->ts.tv_sec;
	}	
	end=header->ts.tv_sec;
	ethtype[p]=ntohs(ethernet->ether_type);
	p++;
	ip = (struct sniff_ip*)(pkt_data + 14);
	size_ip = IP_HL(ip)*4;
	if(size_ip==8 || size_ip==32 || size_ip==0)
	{
	size[count]=header->len;
	count++;
	return;
	}
	
	size[count]=header->len;
	fprintf(stdout,"source: %s \n",ether_ntoa((struct ether_header*)ethernet->ether_shost));
    	fprintf(stdout,"dest: %s \n",ether_ntoa((struct ether_header*)ethernet->ether_dhost));
	tcp = (struct sniff_tcp*)(pkt_data + 14 + size_ip);
	size_tcp = TH_OFF(tcp)*4;
	struct udphdr *udph = (struct udphdr*)(pkt_data + 14 + size_ip);
	
	if (size_ip==0) 
	{

		ip = (struct sniff_ip*)(pkt_data + 12+14);
		
		fprintf(stdout," prot %u \n ",ip->ip_p);
		//ipdst[to]=inet_ntoa(ip->ip_src);
		//printf("       To: %s\n", ipdst[to]);
		//printf("       To: %s\n", inet_ntoa(ip->ip_src));
		
		ip = (struct sniff_ip*)(pkt_data + 12);
		//ipsrc[to]=inet_ntoa(ip->ip_dst);
		//printf("       From ipsrc: %s\n",ipsrc[to]);
		
		//to++;
		count++;	
		printf("packet number is %d\n",count);	
				
		return;
	}
	
	/* print source and destination IP addresses */
	else
	{
		if(ip->ip_p==6)
		{
		tsport[p]=ntohs(tcp->th_sport);
		printf("   Src port: %d\n",tsport[p]);
		p++;
		printf("   Dst port: %d\n", ntohs(tcp->th_dport));
			if((tcp->th_flags & TH_ACK)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			ack++;
			}
			if((tcp->th_flags & TH_RST)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			rst++;
			}
			if((tcp->th_flags & TH_SYN)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			syn++;
			}
			if((tcp->th_flags & TH_PUSH)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			psh++;
			}
			if((tcp->th_flags & TH_FIN)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			fin++;
			}
			if((tcp->th_flags & TH_URG)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			urg++;
			}
			if((tcp->th_flags & TH_ECE)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			ece++;
			}
			if((tcp->th_flags & TH_CWR)!=0)
			{
			//printf("flag %X\n",tcp->th_flags);
			cwr++;
			}
		//printf("   Flag: RST\n");
		}
				
		if(ip->ip_p==17)
		{
		printf("   Src port: %d\n", ntohs(udph->uh_sport));
		printf("   Dst port: %d\n", ntohs(udph->uh_dport));
		//printf("   checksum %X\n", ntohs(udph->uh_len));
		printf("   length %d\n",ntohs(udph->uh_ulen));
		}
	
	proto[p]=ip->ip_p;
	p1++;
	ipsrc[to]=inet_ntoa(ip->ip_src);
	//to++;
	
	//
	to++;
	ipdst[to]=inet_ntoa(ip->ip_dst);
	printf("       To : %s\n", ipdst[to]);
	count++;
	
	
	printf("packet number is %d\n",count);
	
	}
	
}
Ejemplo n.º 18
0
int
main(int argc, char *argv[])
{
	bool newrc, already;
	int rcfirst = 0;		/* first message to print (from .rc) */
	int rcback = 0;			/* amount to back off of rcfirst */
	int firstmsg = 0, nextmsg = 0, lastmsg = 0;
	int blast = 0;
	struct stat buf;		/* stat to check access of bounds */
	FILE *bounds;
	char *cp;

#ifdef UNBUFFERED
	setbuf(stdout, NULL);
#endif
	setlocale(LC_ALL, "");

	time(&t);
	if (setuid(uid = getuid()) != 0)
		err(1, "setuid failed");
	ruptible = (signal(SIGINT, SIG_IGN) == SIG_DFL);
	if (ruptible)
		signal(SIGINT, SIG_DFL);

	argc--, argv++;
	while (argc > 0) {
		if (isdigit(argv[0][0])) {	/* starting message # */
			rcfirst = atoi(argv[0]);
		}
		else if (isdigit(argv[0][1])) {	/* backward offset */
			rcback = atoi( &( argv[0][1] ) );
		}
		else {
			ptr = *argv;
			while (*ptr) switch (*ptr++) {

			case '-':
				break;

			case 'c':
				if (uid != SUPERUSER && uid != DAEMON)
					errx(1,
				"only the super-user can use the c flag");
				clean = YES;
				break;

			case 'f':		/* silently */
				hush = YES;
				break;

			case 'h':		/* headers only */
				hdrs = YES;
				break;

			case 'l':		/* local msgs only */
				locomode = YES;
				break;

			case 'o':		/* option to save last message */
				lastcmd = YES;
				break;

			case 'p':		/* pipe thru 'more' during long msgs */
				use_pager = YES;
				break;

			case 'q':		/* query only */
				qopt = YES;
				break;

			case 's':		/* sending TO msgs */
				send_msg = YES;
				break;

			default:
				usage();
			}
		}
		argc--, argv++;
	}

	/*
	 * determine current message bounds
	 */
	snprintf(fname, sizeof(fname), "%s/%s", _PATH_MSGS, BOUNDS);

	/*
	 * Test access rights to the bounds file
	 * This can be a little tricky.  if(send_msg), then
	 * we will create it.  We assume that if(send_msg),	
	 * then you have write permission there.
	 * Else, it better be there, or we bail.
	 */
	if (send_msg != YES) {
		if (stat(fname, &buf) < 0) {
			if (hush != YES) {
				err(errno, "%s", fname);
			} else {
				exit(1);
			}
		}
	}
	bounds = fopen(fname, "r");

	if (bounds != NULL) {
		fscanf(bounds, "%d %d\n", &firstmsg, &lastmsg);
		fclose(bounds);
		blast = lastmsg;	/* save upper bound */
	}

	if (clean)
		keep = t - (rcback? rcback : NDAYS) DAYS;

	if (clean || bounds == NULL) {	/* relocate message bounds */
		struct dirent *dp;
		struct stat stbuf;
		bool seenany = NO;
		DIR	*dirp;

		dirp = opendir(_PATH_MSGS);
		if (dirp == NULL)
			err(errno, "%s", _PATH_MSGS);

		firstmsg = 32767;
		lastmsg = 0;

		for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){
			cp = dp->d_name;
			int i = 0;

			if (dp->d_ino == 0)
				continue;
			if (dp->d_namlen == 0)
				continue;

			if (clean)
				snprintf(inbuf, sizeof(inbuf), "%s/%s", _PATH_MSGS, cp);

			while (isdigit(*cp))
				i = i * 10 + *cp++ - '0';
			if (*cp)
				continue;	/* not a message! */

			if (clean) {
				if (stat(inbuf, &stbuf) != 0)
					continue;
				if (stbuf.st_mtime < keep
				    && stbuf.st_mode&S_IWRITE) {
					unlink(inbuf);
					continue;
				}
			}

			if (i > lastmsg)
				lastmsg = i;
			if (i < firstmsg)
				firstmsg = i;
			seenany = YES;
		}
		closedir(dirp);

		if (!seenany) {
			if (blast != 0)	/* never lower the upper bound! */
				lastmsg = blast;
			firstmsg = lastmsg + 1;
		}
		else if (blast > lastmsg)
			lastmsg = blast;

		if (!send_msg) {
			bounds = fopen(fname, "w");
			if (bounds == NULL)
				err(errno, "%s", fname);
			chmod(fname, CMODE);
			fprintf(bounds, "%d %d\n", firstmsg, lastmsg);
			fclose(bounds);
		}
	}

	if (send_msg) {
		/*
		 * Send mode - place msgs in _PATH_MSGS
		 */
		bounds = fopen(fname, "w");
		if (bounds == NULL)
			err(errno, "%s", fname);

		nextmsg = lastmsg + 1;
		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, nextmsg);
		newmsg = fopen(fname, "w");
		if (newmsg == NULL)
			err(errno, "%s", fname);
		chmod(fname, CMODE);

		fprintf(bounds, "%d %d\n", firstmsg, nextmsg);
		fclose(bounds);

		sending = YES;
		if (ruptible)
			signal(SIGINT, onintr);

		if (isatty(fileno(stdin))) {
			ptr = getpwuid(uid)->pw_name;
			printf("Message %d:\nFrom %s %sSubject: ",
				nextmsg, ptr, ctime(&t));
			fflush(stdout);
			fgets(inbuf, sizeof inbuf, stdin);
			putchar('\n');
			fflush(stdout);
			fprintf(newmsg, "From %s %sSubject: %s\n",
				ptr, ctime(&t), inbuf);
			blankline = seensubj = YES;
		}
		else
			blankline = seensubj = NO;
		for (;;) {
			fgets(inbuf, sizeof inbuf, stdin);
			if (feof(stdin) || ferror(stdin))
				break;
			blankline = (blankline || (inbuf[0] == '\n'));
			seensubj = (seensubj || (!blankline && (strncmp(inbuf, "Subj", 4) == 0)));
			fputs(inbuf, newmsg);
		}
#ifdef OBJECT
		if (!seensubj) {
			printf("NOTICE: Messages should have a Subject field!\n");
#ifdef REJECT
			unlink(fname);
#endif
			exit(1);
		}
#endif
		exit(ferror(stdin));
	}
	if (clean)
		exit(0);

	/*
	 * prepare to display messages
	 */
	totty = (isatty(fileno(stdout)) != 0);
	use_pager = use_pager && totty;

	if ((cp = getenv("HOME")) == NULL || *cp == '\0') {
		fprintf(stderr, "Error, no home directory!\n");
		exit(1);
	}
	snprintf(fname, sizeof(fname), "%s/%s", cp, MSGSRC);
	msgsrc = fopen(fname, "r");
	if (msgsrc) {
		newrc = NO;
		fscanf(msgsrc, "%d\n", &nextmsg);
		fclose(msgsrc);
		if (nextmsg > lastmsg+1) {
			printf("Warning: bounds have been reset (%d, %d)\n",
				firstmsg, lastmsg);
			truncate(fname, (off_t)0);
			newrc = YES;
		}
		else if (!rcfirst)
			rcfirst = nextmsg - rcback;
	}
	else
		newrc = YES;
	msgsrc = fopen(fname, "r+");
	if (msgsrc == NULL)
		msgsrc = fopen(fname, "w");
	if (msgsrc == NULL)
		err(errno, "%s", fname);
	if (rcfirst) {
		if (rcfirst > lastmsg+1) {
			printf("Warning: the last message is number %d.\n",
				lastmsg);
			rcfirst = nextmsg;
		}
		if (rcfirst > firstmsg)
			firstmsg = rcfirst;	/* don't set below first msg */
	}
	if (newrc) {
		nextmsg = firstmsg;
		rewind(msgsrc);
		fprintf(msgsrc, "%d\n", nextmsg);
		fflush(msgsrc);
	}

#ifdef V7
	if (totty) {
		struct winsize win;
		if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1)
			Lpp = win.ws_row;
		if (Lpp <= 0) {
			if (tgetent(inbuf, getenv("TERM")) <= 0
			    || (Lpp = tgetnum("li")) <= 0) {
				Lpp = NLINES;
			}
		}
	}
#endif
	Lpp -= 6;	/* for headers, etc. */

	already = NO;
	prevmsg = firstmsg;
	printing = YES;
	if (ruptible)
		signal(SIGINT, onintr);

	/*
	 * Main program loop
	 */
	for (msg = firstmsg; msg <= lastmsg; msg++) {

		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, msg);
		newmsg = fopen(fname, "r");
		if (newmsg == NULL)
			continue;

		gfrsub(newmsg);		/* get From and Subject fields */
		if (locomode && !local) {
			fclose(newmsg);
			continue;
		}

		if (qopt) {	/* This has to be located here */
			printf("There are new messages.\n");
			exit(0);
		}

		if (already && !hdrs)
			putchar('\n');

		/*
		 * Print header
		 */
		if (totty)
			signal(SIGTSTP, onsusp);
		(void) setjmp(tstpbuf);
		already = YES;
		nlines = 2;
		if (seenfrom) {
			printf("Message %d:\nFrom %s %s", msg, from, date);
			nlines++;
		}
		if (seensubj) {
			printf("Subject: %s", subj);
			nlines++;
		}
		else {
			if (seenfrom) {
				putchar('\n');
				nlines++;
			}
			while (nlines < 6
			    && fgets(inbuf, sizeof inbuf, newmsg)
			    && inbuf[0] != '\n') {
				fputs(inbuf, stdout);
				nlines++;
			}
		}

		lct = linecnt(newmsg);
		if (lct)
			printf("(%d%sline%s) ", lct, seensubj? " " : " more ",
			    (lct == 1) ? "" : "s");

		if (hdrs) {
			printf("\n-----\n");
			fclose(newmsg);
			continue;
		}

		/*
		 * Ask user for command
		 */
		if (totty)
			ask(lct? MORE : (msg==lastmsg? NOMORE : NEXT));
		else
			inbuf[0] = 'y';
		if (totty)
			signal(SIGTSTP, SIG_DFL);
cmnd:
		in = inbuf;
		switch (*in) {
			case 'x':
				/* FALLTHROUGH */
			case 'X':
				exit(0);
				/* NOTREACHED */

			case 'q':
				/* FALLTHROUGH */
			case 'Q':
				quitit = YES;
				printf("--Postponed--\n");
				exit(0);
				/* NOTREACHED */

			case 'n':
				/* FALLTHROUGH */
			case 'N':
				if (msg >= nextmsg) sep = "Flushed";
				prevmsg = msg;
				break;

			case 'p':
				/* FALLTHROUGH */
			case 'P':
				use_pager = (*in++ == 'p');
				/* FALLTHROUGH */
			case '\n':
				/* FALLTHROUGH */
			case 'y':
			default:
				if (*in == '-') {
					msg = prevmsg-1;
					sep = "replay";
					break;
				}
				if (isdigit(*in)) {
					msg = next(in);
					sep = in;
					break;
				}

				prmesg(nlines + lct + (seensubj? 1 : 0));
				prevmsg = msg;

		}

		printf("--%s--\n", sep);
		sep = "-";
		if (msg >= nextmsg) {
			nextmsg = msg + 1;
			rewind(msgsrc);
			fprintf(msgsrc, "%d\n", nextmsg);
			fflush(msgsrc);
		}
		if (newmsg)
			fclose(newmsg);
		if (quitit)
			break;
	}

	/*
	 * Make sure .rc file gets updated
	 */
	if (--msg >= nextmsg) {
		nextmsg = msg + 1;
		rewind(msgsrc);
		fprintf(msgsrc, "%d\n", nextmsg);
		fflush(msgsrc);
	}
	if (already && !quitit && lastcmd && totty) {
		/*
		 * save or reply to last message?
		 */
		msg = prevmsg;
		ask(NOMORE);
		if (inbuf[0] == '-' || isdigit(inbuf[0]))
			goto cmnd;
	}
	if (!(already || hush || qopt))
		printf("No new messages.\n");
	exit(0);
	/* NOTREACHED */
}
Ejemplo n.º 19
0
int main(int argc, char **argv, char **env){
#else
int main(int argc, char **argv){
#endif
	int result;
	int error=FALSE;
	char *buffer=NULL;
	int display_license=FALSE;
	int display_help=FALSE;
	int c=0;
	struct tm *tm;
	time_t now;
	char datestring[256];



#ifdef HAVE_GETOPT_H
	int option_index=0;
	static struct option long_options[]=
	{
		{"help",no_argument,0,'h'},
		{"version",no_argument,0,'V'},
		{"license",no_argument,0,'V'},
		{"verify-config",no_argument,0,'v'},
		{"daemon",no_argument,0,'d'},
		{"test-scheduling",no_argument,0,'s'},
		{"dont-verify-objects",no_argument,0,'o'},
		{"dont-verify-paths",no_argument,0,'x'},
		{"precache-objects",no_argument,0,'p'},
		{"use-precached-objects",no_argument,0,'u'},
		{0,0,0,0}
	};
#endif

	/* make sure we have the correct number of command line arguments */
	if(argc<2)
		error=TRUE;


	/* get all command line arguments */
	while(1){

#ifdef HAVE_GETOPT_H
		c=getopt_long(argc,argv,"+hVvdsoxpu",long_options,&option_index);
#else
		c=getopt(argc,argv,"+hVvdsoxpu");
#endif

		if(c==-1 || c==EOF)
			break;

		switch(c){
			
		case '?': /* usage */
		case 'h':
			display_help=TRUE;
			break;

		case 'V': /* version */
			display_license=TRUE;
			break;

		case 'v': /* verify */
			verify_config=TRUE;
			break;

		case 's': /* scheduling check */
			test_scheduling=TRUE;
			break;

		case 'd': /* daemon mode */
			daemon_mode=TRUE;
			break;

		case 'o': /* don't verify objects */
			/*
			verify_object_relationships=FALSE;
			*/
			break;

		case 'x': /* don't verify circular paths */
			verify_circular_paths=FALSE;
			break;

		case 'p': /* precache object config */
			precache_objects=TRUE;
			break;

		case 'u': /* use precached object config */
			use_precached_objects=TRUE;
			break;

		default:
			break;
		        }

	        }

	/* make sure we have the right combination of arguments */
	if(precache_objects==TRUE && (test_scheduling==FALSE && verify_config==FALSE)){
		error=TRUE;
		display_help=TRUE;
	        }

#ifdef DEBUG_MEMORY
	mtrace();
#endif

	if(daemon_mode==FALSE){
		printf("\nNagios Core %s\n",PROGRAM_VERSION);
		printf("Copyright (c) 2009 Nagios Core Development Team and Community Contributors\n");
		printf("Copyright (c) 1999-2009 Ethan Galstad\n");
		printf("Last Modified: %s\n",PROGRAM_MODIFICATION_DATE);
		printf("License: GPL\n\n");
		printf("Website: http://www.nagios.org\n");
	        }

	/* just display the license */
	if(display_license==TRUE){

		printf("This program is free software; you can redistribute it and/or modify\n");
		printf("it under the terms of the GNU General Public License version 2 as\n");
		printf("published by the Free Software Foundation.\n\n");
		printf("This program is distributed in the hope that it will be useful,\n");
		printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
		printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
		printf("GNU General Public License for more details.\n\n");
		printf("You should have received a copy of the GNU General Public License\n");
		printf("along with this program; if not, write to the Free Software\n");
		printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");

		exit(OK);
	        }

	/* make sure we got the main config file on the command line... */
	if(optind>=argc)
		error=TRUE;

	/* if there are no command line options (or if we encountered an error), print usage */
	if(error==TRUE || display_help==TRUE){

		printf("Usage: %s [options] <main_config_file>\n",argv[0]);
		printf("\n");
		printf("Options:\n");
		printf("\n");
		printf("  -v, --verify-config          Verify all configuration data\n");
		printf("  -s, --test-scheduling        Shows projected/recommended check scheduling and other\n");
		printf("                               diagnostic info based on the current configuration files.\n");
		/*printf("  -o, --dont-verify-objects    Don't verify object relationships - USE WITH CAUTION!\n");*/
		printf("  -x, --dont-verify-paths      Don't check for circular object paths - USE WITH CAUTION!\n");
		printf("  -p, --precache-objects       Precache object configuration - use with -v or -s options\n");
		printf("  -u, --use-precached-objects  Use precached object config file\n");
		printf("  -d, --daemon                 Starts Nagios in daemon mode, instead of as a foreground process\n");
		printf("\n");
		printf("Visit the Nagios website at http://www.nagios.org/ for bug fixes, new\n");
		printf("releases, online documentation, FAQs, information on subscribing to\n");
		printf("the mailing lists, and commercial support options for Nagios.\n");
		printf("\n");

		exit(ERROR);
		}


	/* config file is last argument specified */
	config_file=(char *)strdup(argv[optind]);
	if(config_file==NULL){
		printf("Error allocating memory.\n");
		exit(ERROR);
	        }

	/* make sure the config file uses an absolute path */
	if(config_file[0]!='/'){

		/* save the name of the config file */
		buffer=(char *)strdup(config_file);

		/* reallocate a larger chunk of memory */
		config_file=(char *)realloc(config_file,MAX_FILENAME_LENGTH);
		if(config_file==NULL){
			printf("Error allocating memory.\n");
			exit(ERROR);
		        }

		/* get absolute path of current working directory */
		getcwd(config_file,MAX_FILENAME_LENGTH);

		/* append a forward slash */
		strncat(config_file,"/",1);
		config_file[MAX_FILENAME_LENGTH-1]='\x0';

		/* append the config file to the path */
		strncat(config_file,buffer,MAX_FILENAME_LENGTH-strlen(config_file)-1);
		config_file[MAX_FILENAME_LENGTH-1]='\x0';

		my_free(buffer);
	        }


	/* we're just verifying the configuration... */
	if(verify_config==TRUE){

		/* reset program variables */
		reset_variables();

		printf("Reading configuration data...\n");

		/* read in the configuration files (main config file, resource and object config files) */
		if((result=read_main_config_file(config_file))==OK){

			printf("   Read main config file okay...\n");

			/* drop privileges */
			if((result=drop_privileges(nagios_user,nagios_group))==ERROR)
				printf("   Failed to drop privileges.  Aborting.");
			else{
				/* read object config files */
				if((result=read_all_object_data(config_file))==OK)
					printf("   Read object config files okay...\n");
				else
					printf("   Error processing object config files!\n");
				}
		        }
		else
			printf("   Error processing main config file!\n\n");

		printf("\n");

		/* there was a problem reading the config files */
		if(result!=OK){

			/* if the config filename looks fishy, warn the user */
			if(!strstr(config_file,"nagios.cfg")){
				printf("\n***> The name of the main configuration file looks suspicious...\n");
				printf("\n");
				printf("     Make sure you are specifying the name of the MAIN configuration file on\n");
				printf("     the command line and not the name of another configuration file.  The\n");
				printf("     main configuration file is typically '/usr/local/nagios/etc/nagios.cfg'\n");
	                        }

			printf("\n***> One or more problems was encountered while processing the config files...\n");
			printf("\n");
			printf("     Check your configuration file(s) to ensure that they contain valid\n");
			printf("     directives and data defintions.  If you are upgrading from a previous\n");
			printf("     version of Nagios, you should be aware that some variables/definitions\n");
			printf("     may have been removed or modified in this version.  Make sure to read\n");
			printf("     the HTML documentation regarding the config files, as well as the\n");
			printf("     'Whats New' section to find out what has changed.\n\n");
		        }

		/* the config files were okay, so run the pre-flight check */
		else{

			printf("Running pre-flight check on configuration data...\n\n");

			/* run the pre-flight check to make sure things look okay... */
			result=pre_flight_check();

			if(result==OK)
				printf("\nThings look okay - No serious problems were detected during the pre-flight check\n");
			else{
				printf("\n***> One or more problems was encountered while running the pre-flight check...\n");
				printf("\n");
				printf("     Check your configuration file(s) to ensure that they contain valid\n");
				printf("     directives and data defintions.  If you are upgrading from a previous\n");
				printf("     version of Nagios, you should be aware that some variables/definitions\n");
				printf("     may have been removed or modified in this version.  Make sure to read\n");
				printf("     the HTML documentation regarding the config files, as well as the\n");
				printf("     'Whats New' section to find out what has changed.\n\n");
			        }
		        }

		/* clean up after ourselves */
		cleanup();

		/* free config_file */
		my_free(config_file);

		/* exit */
		exit(result);
	        }


	/* we're just testing scheduling... */
	else if(test_scheduling==TRUE){

		/* reset program variables */
		reset_variables();

		/* read in the configuration files (main config file and all host config files) */
		result=read_main_config_file(config_file);

		/* drop privileges */
		if(result==OK)
			if((result=drop_privileges(nagios_user,nagios_group))==ERROR)
				printf("Failed to drop privileges.  Aborting.");

		/* read object config files */
		if(result==OK)
			result=read_all_object_data(config_file);

		/* read initial service and host state information */
		if(result==OK){
			initialize_retention_data(config_file);
			read_initial_state_information();
			}

		if(result!=OK)
			printf("***> One or more problems was encountered while reading configuration data...\n");

		/* run the pre-flight check to make sure everything looks okay */
		if(result==OK){
			if((result=pre_flight_check())!=OK)
				printf("***> One or more problems was encountered while running the pre-flight check...\n");
			}

		if(result==OK){

			/* initialize the event timing loop */
			init_timing_loop();

			/* display scheduling information */
			display_scheduling_info();

			if(precache_objects==TRUE){
				printf("\n");
				printf("OBJECT PRECACHING\n");
				printf("-----------------\n");
				printf("Object config files were precached.\n");
				}
		        }

#undef TEST_TIMEPERIODS
#ifdef TEST_TIMEPERIODS
		/* DO SOME TIMEPERIOD TESTING - ADDED 08/11/2009 */
		time_t now, pref_time, valid_time;
		timeperiod *tp;
		tp=find_timeperiod("247_exclusion");
		time(&now);
		pref_time=now;
		get_next_valid_time(pref_time,&valid_time,tp);
		printf("=====\n");
		printf("CURRENT:   %lu = %s",(unsigned long)now,ctime(&now));
		printf("PREFERRED: %lu = %s",(unsigned long)pref_time,ctime(&pref_time));
		printf("NEXT:      %lu = %s",(unsigned long)valid_time,ctime(&valid_time));
		printf("=====\n");
#endif

		/* clean up after ourselves */
		cleanup();

		/* exit */
		exit(result);
	        }


	/* else start to monitor things... */
	else{

		/* keep monitoring things until we get a shutdown command */
		do{

			/* reset program variables */
			reset_variables();

			/* get PID */
			nagios_pid=(int)getpid();

			/* read in the configuration files (main and resource config files) */
			result=read_main_config_file(config_file);

			/* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */
			/* get program (re)start time and save as macro */
			program_start=time(NULL);
			my_free(macro_x[MACRO_PROCESSSTARTTIME]);
			asprintf(&macro_x[MACRO_PROCESSSTARTTIME],"%lu",(unsigned long)program_start);

			/* open debug log */
			open_debug_log();

			/* drop privileges */
			if(drop_privileges(nagios_user,nagios_group)==ERROR){

				logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR,TRUE,"Failed to drop privileges.  Aborting.");

				cleanup();
				exit(ERROR);
			        }

#ifdef USE_EVENT_BROKER
			/* initialize modules */
			neb_init_modules();
			neb_init_callback_list();
#endif

			/* this must be logged after we read config data, as user may have changed location of main log file */
			logit(NSLOG_PROCESS_INFO,TRUE,"Nagios %s starting... (PID=%d)\n",PROGRAM_VERSION,(int)getpid());

			/* log the local time - may be different than clock time due to timezone offset */
			now=time(NULL);
			tm=localtime(&now);
			strftime(datestring,sizeof(datestring),"%a %b %d %H:%M:%S %Z %Y",tm);
			asprintf(&buffer,"Local time is %s\n",datestring);
			write_to_logs_and_console(buffer,NSLOG_PROCESS_INFO,TRUE);
			my_free(buffer);

			/* write log version/info */
			write_log_file_info(NULL);

#ifdef USE_EVENT_BROKER
			/* load modules */
			neb_load_all_modules();

			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_PRELAUNCH,NEBFLAG_NONE,NEBATTR_NONE,NULL);
#endif

			/* read in all object config data */
			if(result==OK)
				result=read_all_object_data(config_file);

			/* there was a problem reading the config files */
			if(result!=OK)
				logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR,TRUE,"Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)",(int)getpid());

			else{

				/* run the pre-flight check to make sure everything looks okay*/
				if((result=pre_flight_check())!=OK)
					logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR,TRUE,"Bailing out due to errors encountered while running the pre-flight check.  Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n",(int)getpid());
				}

			/* an error occurred that prevented us from (re)starting */
			if(result!=OK){
				
				/* if we were restarting, we need to cleanup from the previous run */
				if(sigrestart==TRUE){

					/* clean up the status data */
					cleanup_status_data(config_file,TRUE);

					/* shutdown the external command worker thread */
					shutdown_command_file_worker_thread();

					/* close and delete the external command file FIFO */
					close_command_file();

					/* cleanup embedded perl interpreter */
					if(embedded_perl_initialized==TRUE)
						deinit_embedded_perl();
					}

#ifdef USE_EVENT_BROKER
				/* send program data to broker */
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN,NEBFLAG_PROCESS_INITIATED,NEBATTR_SHUTDOWN_ABNORMAL,NULL);
#endif
				cleanup();
				exit(ERROR);
				}



			/* initialize embedded Perl interpreter */
			/* NOTE 02/15/08 embedded Perl must be initialized if compiled in, regardless of whether or not its enabled in the config file */
			/* It compiled it, but not initialized, Nagios will segfault in readdir() calls, as libperl takes this function over */
			if(embedded_perl_initialized==FALSE){
/*				if(enable_embedded_perl==TRUE){*/
#ifdef EMBEDDEDPERL
				init_embedded_perl(env);
#else
				init_embedded_perl(NULL);
#endif
				embedded_perl_initialized=TRUE;
/*					}*/
			        }

		        /* handle signals (interrupts) */
			setup_sighandler();


#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_START,NEBFLAG_NONE,NEBATTR_NONE,NULL);
#endif

			/* enter daemon mode (unless we're restarting...) */
			if(daemon_mode==TRUE && sigrestart==FALSE){

				result=daemon_init();

				/* we had an error daemonizing, so bail... */
				if(result==ERROR){
					logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR,TRUE,"Bailing out due to failure to daemonize. (PID=%d)",(int)getpid());

#ifdef USE_EVENT_BROKER
					/* send program data to broker */
					broker_program_state(NEBTYPE_PROCESS_SHUTDOWN,NEBFLAG_PROCESS_INITIATED,NEBATTR_SHUTDOWN_ABNORMAL,NULL);
#endif
					cleanup();
					exit(ERROR);
					}

				asprintf(&buffer,"Finished daemonizing... (New PID=%d)\n",(int)getpid());
				write_to_all_logs(buffer,NSLOG_PROCESS_INFO);
				my_free(buffer);

				/* get new PID */
				nagios_pid=(int)getpid();
			        }

			/* open the command file (named pipe) for reading */
			result=open_command_file();
			if(result!=OK){

				logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR,TRUE,"Bailing out due to errors encountered while trying to initialize the external command file... (PID=%d)\n",(int)getpid());

#ifdef USE_EVENT_BROKER
				/* send program data to broker */
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN,NEBFLAG_PROCESS_INITIATED,NEBATTR_SHUTDOWN_ABNORMAL,NULL);
#endif
				cleanup();
				exit(ERROR);
		                }

		        /* initialize status data unless we're starting */
			if(sigrestart==FALSE)
				initialize_status_data(config_file);

			/* read initial service and host state information  */
			initialize_retention_data(config_file);
			read_initial_state_information();

			/* initialize comment data */
			initialize_comment_data(config_file);
			
			/* initialize scheduled downtime data */
			initialize_downtime_data(config_file);
			
			/* initialize performance data */
			initialize_performance_data(config_file);

		        /* initialize the event timing loop */
			init_timing_loop();
			
			/* initialize check statistics */
			init_check_stats();

			/* check for updates */
			check_for_nagios_updates(FALSE,TRUE);

			/* update all status data (with retained information) */
			update_all_status_data();

			/* log initial host and service state */
			log_host_states(INITIAL_STATES,NULL);
			log_service_states(INITIAL_STATES,NULL);

			/* reset the restart flag */
			sigrestart=FALSE;

#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART,NEBFLAG_NONE,NEBATTR_NONE,NULL);
#endif

			/* get event start time and save as macro */
			event_start=time(NULL);
			my_free(macro_x[MACRO_EVENTSTARTTIME]);
			asprintf(&macro_x[MACRO_EVENTSTARTTIME],"%lu",(unsigned long)event_start);

		        /***** start monitoring all services *****/
			/* (doesn't return until a restart or shutdown signal is encountered) */
			event_execution_loop();

			/* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */
			/* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */
			/* did we catch a signal? */
			if(caught_signal==TRUE){

				if(sig_id==SIGHUP)
					asprintf(&buffer,"Caught SIGHUP, restarting...\n");
				else if(sig_id!=SIGSEGV)
					asprintf(&buffer,"Caught SIG%s, shutting down...\n",sigs[sig_id]);

				write_to_all_logs(buffer,NSLOG_PROCESS_INFO);
				my_free(buffer);
				}

#ifdef USE_EVENT_BROKER
			/* send program data to broker */
			broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND,NEBFLAG_NONE,NEBATTR_NONE,NULL);
			if(sigshutdown==TRUE)
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN,NEBFLAG_USER_INITIATED,NEBATTR_SHUTDOWN_NORMAL,NULL);
			else if(sigrestart==TRUE)
				broker_program_state(NEBTYPE_PROCESS_RESTART,NEBFLAG_USER_INITIATED,NEBATTR_RESTART_NORMAL,NULL);
#endif

			/* save service and host state information */
			save_state_information(FALSE);
			cleanup_retention_data(config_file);

			/* clean up performance data */
			cleanup_performance_data(config_file);

			/* clean up the scheduled downtime data */
			cleanup_downtime_data(config_file);

			/* clean up the comment data */
			cleanup_comment_data(config_file);

			/* clean up the status data unless we're restarting */
			if(sigrestart==FALSE)
				cleanup_status_data(config_file,TRUE);

			/* close and delete the external command file FIFO unless we're restarting */
			if(sigrestart==FALSE){
				shutdown_command_file_worker_thread();
				close_command_file();
				}

			/* cleanup embedded perl interpreter */
			if(sigrestart==FALSE)
				deinit_embedded_perl();

			/* shutdown stuff... */
			if(sigshutdown==TRUE){

				/* make sure lock file has been removed - it may not have been if we received a shutdown command */
				if(daemon_mode==TRUE)
					unlink(lock_file);

				/* log a shutdown message */
				logit(NSLOG_PROCESS_INFO,TRUE,"Successfully shutdown... (PID=%d)\n",(int)getpid());
 			        }

			/* clean up after ourselves */
			cleanup();

			/* close debug log */
			close_debug_log();

	                }while(sigrestart==TRUE && sigshutdown==FALSE);

		/* free misc memory */
		my_free(config_file);
	        }

	return OK;
	}
Ejemplo n.º 20
0
int main(int argc,char **argv)
{
  FILE *fptr;
  struct stat statbuf;
  char *cpt;
  int chara;
  unsigned int linelen;
  unsigned int searchlen;
  unsigned int line_no;
  int first_line_no;
  bool put_title;
  unsigned int tries;
  unsigned int m;
  unsigned int n;
  unsigned int p;
  bool case_sens;
  int curr_arg;
  bool show_title;
  bool line_numbers;
  unsigned int string_arg;
  bool show_search_string;
  bool put_search_string;
  bool reverse;
  bool put_line;
  bool bStdin;
  bool ss_specified;
  bool t_specified;
  bool l_specified;
  bool bHex;
  bool bChop;
  unsigned int chop;
  bool bOffset;
  int nibbles[2];
  int which_nib;
  unsigned int num_special_chars;
  int bDateTime;
  int bWindow;
  int window;
  int bDebug;
  int last_grepped_line;
  struct pair special_chars[MAX_SPECIAL_CHARS];
  char buf[3];

  case_sens = false;
  ss_specified = false;
  t_specified = false;
  l_specified = false;
  reverse = false;
  bHex = false;
  bChop = false;
  bOffset = false;
  num_special_chars = 0;
  bDateTime = false;
  bWindow = false;
  bDebug = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (argv[curr_arg][0] != '-')
      break;

    if (!strcmp(argv[curr_arg],"-c"))
      case_sens = true;
    else if (!strcmp(argv[curr_arg],"-ss")) {
      show_search_string = true;
      ss_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-t")) {
      show_title = true;
      t_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-l")) {
      line_numbers = true;
      l_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-nss")) {
      show_search_string = false;
      ss_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-nt")) {
      show_title = false;
      t_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-nl")) {
      line_numbers = false;
      l_specified = true;
    }
    else if (!strcmp(argv[curr_arg],"-rev"))
      reverse = true;
    else if (!strcmp(argv[curr_arg],"-hex"))
      bHex = true;
    else if (!strncmp(argv[curr_arg],"-chop",5)) {
      bChop = true;
      sscanf(&argv[curr_arg][5],"%u",&chop);
    }
    else if (!strcmp(argv[curr_arg],"-off")) {
      bOffset = true;
      line_numbers = false;
      l_specified = true;
    }
    else if (!strncmp(argv[curr_arg],"-special_char",13)) {
      if (num_special_chars == MAX_SPECIAL_CHARS) {
        printf("num_special_chars may not exceed %d\n",MAX_SPECIAL_CHARS);
        return 1;
      }

      buf[0] = argv[curr_arg][13];
      buf[1] = argv[curr_arg][14];
      buf[2] = 0;

      sscanf(buf,"%x",&special_chars[num_special_chars].val1);
      sscanf(&argv[curr_arg][15],"%c",&special_chars[num_special_chars++].val2);
    }
    else if (!strcmp(argv[curr_arg],"-datetime"))
      bDateTime = true;
    else if (!strncmp(argv[curr_arg],"-window",7)) {
      bWindow = true;
      sscanf(&argv[curr_arg][7],"%u",&window);
    }
    else if (!strcmp(argv[curr_arg],"-dbg"))
      bDebug = true;
    else
      break;
  }

  if (curr_arg == argc) {
    printf(usage);
    return 2;
  }

  string_arg = curr_arg;

  if (bHex) {
    case_sens = true;
    searchlen = strlen(argv[string_arg]);

    if (searchlen % 2) {
      printf("hex string must have an even number of hex digits\n");
      return 3;
    }

    m = 0;

    for (n = 0; n < searchlen; n++) {
      which_nib = n % 2;

      if ((nibbles[which_nib] = get_nib(argv[string_arg][n])) == -1) {
        printf("illegal hex string\n");
        return 4;
      }

      if (which_nib)
        argv[string_arg][m++] = (nibbles[0] << 4) + nibbles[1];
    }

    argv[string_arg][m] = 0;
  }
  else if (num_special_chars || !case_sens) {
    for (n = 0; (chara = argv[string_arg][n]); n++) {
      for (p = 0; p < num_special_chars; p++) {
        if (chara == special_chars[p].val2) {
          argv[string_arg][n] = (char)special_chars[p].val1;
          break;
        }
      }

      if (!case_sens) {
        if ((chara >= 'A') && (chara <= 'Z'))
          argv[string_arg][n] = (char)(chara - 'A' + 'a');
      }
    }
  }

  searchlen = strlen(argv[string_arg]);

  if (!strcmp(argv[string_arg],"doublequote")) {
    argv[string_arg][0] = '"';
    searchlen = 1;
  }

  curr_arg++;

  if (curr_arg == argc) {
    bStdin = true;

    if (!ss_specified)
      show_search_string = false;

    /*if (!t_specified)*/
      show_title = false;

    if (!l_specified)
      line_numbers = false;
  }
  else {
    if (argc - curr_arg == 1) {
      /* if wildcard expansion failed, exit with no error message */
      for (n = 0; (chara = argv[curr_arg][n]); n++) {
        if (chara == '*')
          return 5;
      }
    }

    bStdin = false;

    if (!ss_specified) {
      if (argc - string_arg > 2)
        show_search_string = true;
      else
        show_search_string = false;
    }

    if (!t_specified) {
      if (argc - string_arg > 2)
        show_title = true;
      else
        show_title = false;
    }

    if (!l_specified)
      line_numbers = true;
  }

  if ((line = (char *)malloc(MAX_LINE_LEN)) == NULL) {
    printf("malloc of %u bytes failed\n",MAX_LINE_LEN);
    return 6;
  }

  if (show_search_string)
    put_search_string = false;

  /* start of argument loop: */
  for ( ; ; ) {

  if (bStdin)
    fptr = stdin;
  else {
    if ((fptr = fopen(argv[curr_arg],"r")) == NULL) {
      printf(couldnt_open,argv[curr_arg]);
      curr_arg++;

      if (curr_arg == argc)
        break;

      continue;
    }

    if (stat(argv[curr_arg],&statbuf)) {
      printf(couldnt_get_status,argv[curr_arg]);
      curr_arg++;

      if (curr_arg == argc)
        break;

      continue;
    }
  }

  if (show_title)
    put_title = false;

  if (bOffset)
    first_line_no = -1;

  line_no = 0;
  last_grepped_line = -1;

  for ( ; ; ) {
    GetLine(fptr,line,&linelen,MAX_LINE_LEN);

    if (feof(fptr)) {
      if (!bStdin) {
        if (show_title && put_title)
          putchar(0x0a);

        fclose(fptr);
      }

      break;
    }

    line_no++;

    if (bDebug)
      printf(dbg_fmt_str,line_no,line);

    put_line = false;

    if (linelen < searchlen) {
      if (reverse)
        put_line = true;
    }
    else {
      tries = linelen - searchlen + 1;

      for (m = 0; m < tries; m++) {
        for (n = 0; n < searchlen; n++) {
          chara = line[m+n];

          if (!case_sens)
            if ((chara >= 'A') && (chara <= 'Z'))
              chara -= 'A' - 'a';

          if (chara != argv[string_arg][n])
            break;
        }

        if (n == searchlen)
          break;
      }

      if (n == searchlen) {
        if (!reverse)
          put_line = true;
      }
      else if (reverse)
        put_line = true;
    }

    if (put_line && bWindow)
      last_grepped_line = line_no;

    if (bWindow && (last_grepped_line != -1)) {
      if (line_no < last_grepped_line + window)
        put_line = 1;
    }

    if (put_line) {
      if (show_search_string) {
        if (!put_search_string) {
          printf("search string: %s\n\n",argv[string_arg]);
          put_search_string = true;
        }
      }

      if (show_title) {
        if (!put_title) {
          if (bDateTime) {
            cpt = ctime(&statbuf.st_mtime);
            cpt[strlen(cpt) - 1] = 0;
            sprintf(exp_title,"%s %s",cpt,argv[curr_arg]);
          }
          else
            strcpy(exp_title,argv[curr_arg]);

          printf("%s\n",exp_title);

          for (n = strlen(exp_title); (n); n--)
            putchar('=');

          putchar(0x0a);

          put_title = true;
        }
      }

      if (bChop)
        line[chop] = 0;

      if (line_numbers)
        printf(fmt_str,line_no,line);
      else if (bOffset) {
        if (first_line_no == -1) {
          printf(fmt_str,0,line);
          first_line_no = line_no;
        }
        else
          printf(fmt_str,line_no - first_line_no,line);
      }
      else
        printf("%s\n",line);
    }
  }

  if (bStdin)
    break;
  else {
    curr_arg++;

    if (curr_arg == argc)
      break;
  }

  /* end of argument loop: */
  }

  free(line);

  return 0;
}
Ejemplo n.º 21
0
int orte_iof_base_write_output(orte_process_name_t *name, orte_iof_tag_t stream,
                                unsigned char *data, int numbytes,
                               orte_iof_write_event_t *channel)
{
    char starttag[ORTE_IOF_BASE_TAG_MAX], endtag[ORTE_IOF_BASE_TAG_MAX], *suffix;
    orte_iof_write_output_t *output;
    int i, j, k, starttaglen, endtaglen, num_buffered;
    bool endtagged;
    char qprint[10];

    OPAL_OUTPUT_VERBOSE((1, orte_iof_base.iof_output,
                         "%s write:output setting up to write %d bytes to %s for %s on fd %d",
                         ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), numbytes,
                         (ORTE_IOF_STDIN & stream) ? "stdin" : ((ORTE_IOF_STDOUT & stream) ? "stdout" : ((ORTE_IOF_STDERR & stream) ? "stderr" : "stddiag")),
                         ORTE_NAME_PRINT(name), 
                         (NULL == channel) ? -1 : channel->fd));

    /* setup output object */
    output = OBJ_NEW(orte_iof_write_output_t);
    
    /* write output data to the corresponding tag */
    if (ORTE_IOF_STDIN & stream) {
        /* copy over the data to be written */
        if (0 < numbytes) {
            /* don't copy 0 bytes - we just need to pass
             * the zero bytes so the fd can be closed
             * after it writes everything out
             */
            memcpy(output->data, data, numbytes);
        }
        output->numbytes = numbytes;
        goto process;
    } else if (ORTE_IOF_STDOUT & stream) {
        /* write the bytes to stdout */
        suffix = "stdout";
    } else if (ORTE_IOF_STDERR & stream) {
        /* write the bytes to stderr */
        suffix = "stderr";
    } else if (ORTE_IOF_STDDIAG & stream) {
        /* write the bytes to stderr */
        suffix = "stddiag";
    } else {
        /* error - this should never happen */
        ORTE_ERROR_LOG(ORTE_ERR_VALUE_OUT_OF_BOUNDS);
        OPAL_OUTPUT_VERBOSE((1, orte_iof_base.iof_output,
                             "%s stream %0x", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), stream));
        return ORTE_ERR_VALUE_OUT_OF_BOUNDS;
    }

    /* if this is to be xml tagged, create a tag with the correct syntax - we do not allow
     * timestamping of xml output
     */
    if (orte_xml_output) {
        snprintf(starttag, ORTE_IOF_BASE_TAG_MAX, "<%s rank=\"%s\">", suffix, ORTE_VPID_PRINT(name->vpid));
        snprintf(endtag, ORTE_IOF_BASE_TAG_MAX, "</%s>", suffix);
        goto construct;
    }
    
    /* if we are to timestamp output, start the tag with that */
    if (orte_timestamp_output) {
        time_t mytime;
        char *cptr;
        /* get the timestamp */
        time(&mytime);
        cptr = ctime(&mytime);
        cptr[strlen(cptr)-1] = '\0';  /* remove trailing newline */
        
        if (orte_tag_output) {
            /* if we want it tagged as well, use both */
            snprintf(starttag, ORTE_IOF_BASE_TAG_MAX, "%s[%s,%s]<%s>:",
                     cptr, ORTE_LOCAL_JOBID_PRINT(name->jobid),
                     ORTE_VPID_PRINT(name->vpid), suffix);
        } else {
            /* only use timestamp */
            snprintf(starttag, ORTE_IOF_BASE_TAG_MAX, "%s<%s>:", cptr, suffix);
        }
        /* no endtag for this option */
        memset(endtag, '\0', ORTE_IOF_BASE_TAG_MAX);
        goto construct;
    }
    
    if (orte_tag_output) {
        snprintf(starttag, ORTE_IOF_BASE_TAG_MAX, "[%s,%s]<%s>:",
                 ORTE_LOCAL_JOBID_PRINT(name->jobid),
                 ORTE_VPID_PRINT(name->vpid), suffix);
        /* no endtag for this option */
        memset(endtag, '\0', ORTE_IOF_BASE_TAG_MAX);
        goto construct;
    }
    
    /* if we get here, then the data is not to be tagged - just copy it
     * and move on to processing
     */
    if (0 < numbytes) {
        /* don't copy 0 bytes - we just need to pass
         * the zero bytes so the fd can be closed
         * after it writes everything out
         */
        memcpy(output->data, data, numbytes);
    }
    output->numbytes = numbytes;
    goto process;

construct:
    starttaglen = strlen(starttag);
    endtaglen = strlen(endtag);
    endtagged = false;
    /* start with the tag */
    for (j=0, k=0; j < starttaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
        output->data[k++] = starttag[j];
    }        
    /* cycle through the data looking for <cr>
     * and replace those with the tag
     */
    for (i=0; i < numbytes && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; i++) {
        if (orte_xml_output) {
            if ('&' == data[i]) {
                if (k+5 >= ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                    ORTE_ERROR_LOG(ORTE_ERR_OUT_OF_RESOURCE);
                    goto process;
                }
                snprintf(qprint, 10, "&amp;");
                for (j=0; j < (int)strlen(qprint) && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                    output->data[k++] = qprint[j];
                }
            } else if ('<' == data[i]) {
                if (k+4 >= ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                    ORTE_ERROR_LOG(ORTE_ERR_OUT_OF_RESOURCE);
                    goto process;
                }
                snprintf(qprint, 10, "&lt;");
                for (j=0; j < (int)strlen(qprint) && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                    output->data[k++] = qprint[j];
                }
            } else if ('>' == data[i]) {
                if (k+4 >= ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                    ORTE_ERROR_LOG(ORTE_ERR_OUT_OF_RESOURCE);
                    goto process;
                }
                snprintf(qprint, 10, "&gt;");
                for (j=0; j < (int)strlen(qprint) && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                    output->data[k++] = qprint[j];
                }
            } else if (data[i] < 32 || data[i] > 127) {
                /* this is a non-printable character, so escape it too */
                if (k+7 >= ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                    ORTE_ERROR_LOG(ORTE_ERR_OUT_OF_RESOURCE);
                    goto process;
                }
                snprintf(qprint, 10, "&#%03d;", (int)data[i]);
                for (j=0; j < (int)strlen(qprint) && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                    output->data[k++] = qprint[j];
                }
                /* if this was a \n, then we also need to break the line with the end tag */
                if ('\n' == data[i] && (k+endtaglen+1) < ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                    /* we need to break the line with the end tag */
                    for (j=0; j < endtaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX-1; j++) {
                        output->data[k++] = endtag[j];
                    }
                    /* move the <cr> over */
                    output->data[k++] = '\n';
                    /* if this isn't the end of the data buffer, add a new start tag */
                    if (i < numbytes-1 && (k+starttaglen) < ORTE_IOF_BASE_TAGGED_OUT_MAX) {
                        for (j=0; j < starttaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                            output->data[k++] = starttag[j];
                            endtagged = false;
                        }
                    } else {
                        endtagged = true;
                    }
                }
            } else {
                output->data[k++] = data[i];
            }
        } else {
            if ('\n' == data[i]) {
                /* we need to break the line with the end tag */
                for (j=0; j < endtaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX-1; j++) {
                    output->data[k++] = endtag[j];
                }
                /* move the <cr> over */
                output->data[k++] = '\n';
                /* if this isn't the end of the data buffer, add a new start tag */
                if (i < numbytes-1) {
                    for (j=0; j < starttaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX; j++) {
                        output->data[k++] = starttag[j];
                        endtagged = false;
                    }
                } else {
                    endtagged = true;
                }
            } else {
                output->data[k++] = data[i];
            }
        }
    }
    if (!endtagged) {
        /* need to add an endtag */
        for (j=0; j < endtaglen && k < ORTE_IOF_BASE_TAGGED_OUT_MAX-1; j++) {
            output->data[k++] = endtag[j];
        }
        output->data[k++] = '\n';
    }
    output->numbytes = k;
    
process:
    /* add this data to the write list for this fd */
    opal_list_append(&channel->outputs, &output->super);

    /* record how big the buffer is */
    num_buffered = opal_list_get_size(&channel->outputs);
    
    /* is the write event issued? */
    if (!channel->pending) {
        /* issue it */
        OPAL_OUTPUT_VERBOSE((1, orte_iof_base.iof_output,
                             "%s write:output adding write event",
                             ORTE_NAME_PRINT(ORTE_PROC_MY_NAME)));
        opal_event_add(channel->ev, 0);
        channel->pending = true;
    }
    
    return num_buffered;
}
Ejemplo n.º 22
0
void formatEachField(My402SortElem *currentElem, My402Output *pOutput, long long *pBalance){

	//printf("\nPrint begins...");	
	int sign = 1;
	int i=0;
	int j=0;
	int count = 0;
	//store the balance that is printed
	char printDesc[25] = "\0"; //+1 for terminating char
	char printDate[16] = "\0"; //+1 for terminating char
	char temp[15] = {'\0'};
	char printAmount[15] = "\0"; //+1 for termiating char
	char printBalance[15] = "\0"; //+1 for terminating char	
	char *cTime = (char *)malloc(26*sizeof(char));
	memset(cTime, '\0', 26*sizeof(char));
	//FIXME: what if sizeof(unsigned int) = 2 bytes?	
	long long currentAmount = currentElem->transAmount; 
	//Porcess Amount
	if('-' == currentElem->transType){
		sign = -1;	
	}
	//Process Date
	cTime = ctime(&currentElem->transTime);
	while(cTime[i] != '\n'){
		
		if(! (i >= 10 && i<=18) ){
			printDate[j] = cTime[i];
			j++;
		}
		i++;
	}	
	printDate[15] = '\0';
	//printf("\n%s ", printDate);
	pOutput->printDate = printDate;
	//Porcess Description
	//printf("%s ", currentElem->transDesc);
	strncpy(printDesc, currentElem->transDesc,24);	
	//printf("\nstrlen-1 = %d",i);
	i=24;	
	while(printDesc[i] == '\0' && i>0){ //although not expecting i=0
		printDesc[i] = ' ';
		i--;	
	}	
	printDesc[24] = '\0';
	//printf("\nDesc%s.....",printDesc);	
	pOutput->printDesc = printDesc;	
	strncpy(printAmount,toCurrency((long long)currentElem->transAmount),14);
	i=0;
	count = 14-strlen(printAmount);
	while(i<count){ //although not expecting i=0
		temp[i] = ' ';
		i++;	
	}
	for(j=0;printAmount[j] != '\0'; j++,i++){
		//printf("\ninside amoun condition\n");	
		temp[i] = printAmount[j];
	}
	temp[14] = '\0';
	strncpy(printAmount,temp,14);
	printAmount[14] = '\0';
	if(sign == -1){
		strncpy(printAmount, representNegatives(printAmount),14);
	}
	printAmount[14] = '\0';
	pOutput->printAmount = printAmount;
	
	//Process Balance
	*pBalance = sign*currentAmount + *pBalance;
	strncpy(printBalance,toCurrency(*pBalance),14);
	//FIXME: add leading spaces	
	i=0;
	j=0;
	count = 14-strlen(printBalance);
	while(i<count){ //although not expecting i=0
		//printf("\ninside amoun condition\n");	
		temp[i] = ' ';
		i++;	
	}
	j=0;
	while(printBalance[j] != '\0'){
		temp[i++] = printBalance[j++];
	}
	temp[14] = '\0';	
	//printf("%s ", printBalance);
	strncpy(printBalance, temp, 14);
	printBalance[14] = '\0';	
	if(sign == -1){
		strncpy(printBalance, representNegatives(printBalance),14);
	}
	printBalance[14] = '\0';	
	pOutput->printBalance = printBalance;
	

}
Ejemplo n.º 23
0
main( int argc, char **argv, char **arg_environ )
{
	int		n;
	const char	*s;
	struct option	optv[N_OPTS];
	const char	*all = "all";
	int		anyhow = 0;
	int		status;

# ifdef OS_MAC
	InitGraf(&qd.thePort);
# endif

	argc--, argv++;

	if( ( n = getoptions( argc, argv, "d:j:f:gs:t:ano:qv", optv ) ) < 0 )
	{
	    printf( "\nusage: jam [ options ] targets...\n\n" );

            printf( "-a      Build all targets, even if they are current.\n" );
            printf( "-dx     Display (a)actions (c)causes (d)dependencies\n" );
	    printf( "        (m)make tree (x)commands (0-9) debug levels.\n" );
            printf( "-fx     Read x instead of Jambase.\n" );
	    printf( "-g      Build from newest sources first.\n" );
            printf( "-jx     Run up to x shell commands concurrently.\n" );
            printf( "-n      Don't actually execute the updating actions.\n" );
            printf( "-ox     Write the updating actions to file x.\n" );
            printf( "-q      Quit quickly as soon as a target fails.\n" );
	    printf( "-sx=y   Set variable x=y, overriding environment.\n" );
            printf( "-tx     Rebuild x, even if it is up-to-date.\n" );
            printf( "-v      Print the version of jam and exit.\n\n" );

	    exit( EXITBAD );
	}

	argc -= n, argv += n;

	/* Version info. */

	if( ( s = getoptval( optv, 'v', 0 ) ) )
	{
	    printf( "Jam %s. %s. ", VERSION, OSMINOR );
	    printf( "Copyright 1993-2002 Christopher Seiwald.\n" );

	    return EXITOK;
	}

	/* Pick up interesting options */

	if( ( s = getoptval( optv, 'n', 0 ) ) )
	    globs.noexec++, DEBUG_MAKE = DEBUG_MAKEQ = DEBUG_EXEC = 1; 

	if( ( s = getoptval( optv, 'q', 0 ) ) )
	    globs.quitquick = 1;

	if( ( s = getoptval( optv, 'a', 0 ) ) )
	    anyhow++;

	if( ( s = getoptval( optv, 'j', 0 ) ) )
	    globs.jobs = atoi( s );

	if( ( s = getoptval( optv, 'g', 0 ) ) )
	    globs.newestfirst = 1;

	/* Turn on/off debugging */

	for( n = 0; s = getoptval( optv, 'd', n ); n++ )
	{
	    int i = atoi( s );

	    /* First -d, turn off defaults. */

	    if( !n )
		DEBUG_MAKE = DEBUG_MAKEQ = DEBUG_EXEC = 0;

	    /* n turns on levels 1-n */
	    /* +n turns on level n */
	    /* c turns on named display c */

	    if( i < 0 || i >= DEBUG_MAX )
	    {
		printf( "Invalid debug level '%s'.\n", s );
	    }
	    else if( *s == '+' )
	    {
		globs.debug[i] = 1;
	    }
	    else if( i ) while( i )
	    {
		globs.debug[i--] = 1;
	    }
	    else while( *s ) switch( *s++ )
	    {
	    case 'a': DEBUG_MAKE = DEBUG_MAKEQ = 1; break;
	    case 'c': DEBUG_CAUSES = 1; break;
	    case 'd': DEBUG_DEPENDS = 1; break;
	    case 'm': DEBUG_MAKEPROG = 1; break;
	    case 'x': DEBUG_EXEC = 1; break;
	    case '0': break;
	    default: printf( "Invalid debug flag '%c'.\n", s[-1] );
	    }
	}

	/* Set JAMDATE first */

	{
	    char buf[ 128 ];
	    time_t clock;
	    time( &clock );
	    strcpy( buf, ctime( &clock ) );

	    /* Trim newline from date */

	    if( strlen( buf ) == 25 )
		buf[ 24 ] = 0;

	    var_set( "JAMDATE", list_new( L0, buf, 0 ), VAR_SET );
	}

	/* And JAMUNAME */
# if defined(unix) && !defined(__NeXT__)
	{
	    struct utsname u;

	    if( uname( &u ) >= 0 )
	    {
		LIST *l = L0;
		l = list_new( l, u.machine, 0 );
		l = list_new( l, u.version, 0 );
		l = list_new( l, u.release, 0 );
		l = list_new( l, u.nodename, 0 );
		l = list_new( l, u.sysname, 0 );
		var_set( "JAMUNAME", l, VAR_SET );
	    }
	}
# endif /* unix */

	/*
	 * Jam defined variables OS, OSPLAT
	 */

	var_defines( othersyms );

	/* load up environment variables */

	var_defines( (const char **)use_environ );

	/* Load up variables set on command line. */

	for( n = 0; s = getoptval( optv, 's', n ); n++ )
	{
	    const char *symv[2];
	    symv[0] = s;
	    symv[1] = 0;
	    var_defines( symv );
	}

	/* Initialize built-in rules */

	load_builtins();

	/* Parse ruleset */

	for( n = 0; s = getoptval( optv, 'f', n ); n++ )
	    parse_file( s );

	if( !n )
	    parse_file( "+" );

	status = yyanyerrors();

	/* Manually touch -t targets */

	for( n = 0; s = getoptval( optv, 't', n ); n++ )
	    touchtarget( s );

	/* If an output file is specified, set globs.cmdout to that */

	if( s = getoptval( optv, 'o', 0 ) )
	{
	    if( !( globs.cmdout = fopen( s, "w" ) ) )
	    {
		printf( "Failed to write to '%s'\n", s );
		exit( EXITBAD );
	    }
	    globs.noexec++;
	}

	/* Now make target */

	if( !argc )
	    status |= make( 1, &all, anyhow );
	else
	    status |= make( argc, (const char **)argv, anyhow );

	/* Widely scattered cleanup */

	var_done();
	donerules();
	donestamps();
	donestr();

	/* close cmdout */

	if( globs.cmdout )
	    fclose( globs.cmdout );

	return status ? EXITBAD : EXITOK;
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{

	int sockfd;
	struct sockaddr_un cliaddr,servaddr;
	char tmp[100];
	char vm[100];

	char buf[100],buf1[100];//send message server
	int f=0;//flag for rediscovery

	struct hostent *he,*he1;
	struct in_addr a;
	char *servsunpath;

	time_t ticks;

	char buff1[400],buff2[400],buff3[400];

	int n;//for recv from

	fd_set rset;
	struct timeval tv;
	int maxfd=0;
	int retval;
	int count=0;

	char *message1,*addr1;
	int *portno1;

	struct hwa_info	*hwa, *hwahead;
	struct sockaddr	*sa,*sa1;
	char   *ptr;
	char vmname[20];
	int    i, prflag;

	printf("\n");

	gethostname(vmname,sizeof(vmname));

	sockfd=socket(AF_LOCAL,SOCK_DGRAM,0);
	if(sockfd<0)
	{
		printf("socket creation error \n");
		exit(-1);
	}

	bzero(&servaddr,sizeof(servaddr));

	servaddr.sun_family=AF_LOCAL;
	strcpy(tmp,"/tmp/serv");
	strcpy(servaddr.sun_path,tmp);
	unlink(tmp);
	//if((bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr)))<0)
	if((bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))<0)
	{
		perror("Binding server: \n");
		exit(-1);
	}

	message1=(char *)malloc(400);
	addr1=(char *)malloc(400);
	portno1=(int *)malloc(sizeof(int));


	printf("Domain Socket Creation and Bind completed \n");
//	printf("Starting connection : \n");

	while(1)
	{
		bzero(buf,sizeof(buf));
		bzero(buff3,sizeof(buff3));
		bzero(buf1,sizeof(buf1));
		msg_recv(sockfd,message1,addr1,portno1);
		printf("Server received a message from the client: %s \n",message1);

		   he1=gethostbyaddr(addr1,strlen(addr1),AF_INET);
		   if(he1!=NULL)
		   {
			strcpy(buf1,he1->h_name);
			printf("Server at node %s responding to request from %s \n", vmname,buf1);//complete the statement
			ticks=time(NULL);
			snprintf(buf,sizeof(buf),"%.24s\r\n",ctime(&ticks));
			printf("value sending %s \n ",buf);
			strcpy(buff3,(char *)inet_ntoa(a));
			msg_send(sockfd,buff3,*portno1,buf,f);
		   }//	printf("this is in the msg_send function \n");

		   else
			   printf("gethostbyaddr returned null \n");
	}


} // main loop
Ejemplo n.º 25
0
void logprintf(int prio, const char *format_str, ...) {
	int save_errno = errno;
	va_list ap;

	if(filelog == 0 && shelllog == 0)
		return;

	if(loglevel >= prio) {
		if(lf == NULL && filelog == 1) {
			if((lf = fopen(logfile, "a+")) == NULL) {
				logprintf(LOG_WARNING, "could not open logfile %s", logfile);
			} else {
				gc_attach(log_gc);
			}
		}

		time_t current;
		char *currents;

		current=time(&current);
		currents=ctime(&current);

		if(filelog == 1 && lf != NULL && loglevel < LOG_DEBUG) {
			fprintf(lf,"[%15.15s] %s: ",currents+4, progname);
			va_start(ap, format_str);
			if(prio==LOG_WARNING)
				fprintf(lf,"WARNING: ");
			if(prio==LOG_ERR)
				fprintf(lf,"ERROR: ");
			if(prio==LOG_INFO)
				fprintf(lf, "INFO: ");
			if(prio==LOG_NOTICE)
				fprintf(lf, "NOTICE: ");
			vfprintf(lf, format_str, ap);
			fputc('\n',lf);
			fflush(lf);
			va_end(ap);
		}

		if(shelllog == 1) {

			fprintf(stderr, "[%15.15s] %s: ",currents+4, progname);
			va_start(ap, format_str);

			if(prio==LOG_WARNING)
				fprintf(stderr, "WARNING: ");
			if(prio==LOG_ERR)
				fprintf(stderr, "ERROR: ");
			if(prio==LOG_INFO)
				fprintf(stderr, "INFO: ");
			if(prio==LOG_NOTICE)
				fprintf(stderr, "NOTICE: ");
			if(prio==LOG_DEBUG)
				fprintf(stderr, "DEBUG: ");
			vfprintf(stderr, format_str, ap);
			fputc('\n',stderr);
			fflush(stderr);
			va_end(ap);
		}
	}
	errno = save_errno;
}
Ejemplo n.º 26
0
void
ppbuiltin(void)
{
	register int		c;
	register char*		p;
	register char*		a;

	int			n;
	int			op;
	char*			token;
	char*			t;
	long			number;
	long			onumber;
	struct ppinstk*		in;
	struct pplist*		list;
	struct ppsymbol*	sym;
	Sfio_t*			sp;

	number = pp.state;
	pp.state |= DISABLE|FILEPOP|NOSPACE;
	token = pp.token;
	p = pp.token = pp.tmpbuf;
	*(a = pp.args) = 0;
	if ((c = pplex()) != T_ID)
	{
		error(2, "%s: #(<identifier>...) expected", p);
		*p = 0;
	}
	switch (op = (int)hashget(pp.strtab, p))
	{
	case V_DEFAULT:
		n = 0;
		p = pp.token = pp.valbuf;
		if ((c = pplex()) == ',')
		{
			op = -1;
			c = pplex();
		}
		pp.state &= ~NOSPACE;
		for (;;)
		{
			if (!c)
			{
				error(2, "%s in #(...) argument", pptokchr(c));
				break;
			}
			if (c == '(') n++;
			else if (c == ')' && !n--) break;
			else if (c == ',' && !n && op > 0) op = 0;
			if (op) pp.token = pp.toknxt;
			c = pplex();
		}
		*pp.token = 0;
		pp.token = token;
		pp.state = number;
		break;
	case V_EMPTY:
		p = pp.valbuf;
		if ((c = pplex()) == ')') *p = '1';
		else
		{
			*p = '0';
			n = 0;
			for (;;)
			{
				if (!c)
				{
					error(2, "%s in #(...) argument", pptokchr(c));
					break;
				}
				if (c == '(') n++;
				else if (c == ')' && !n--) break;
				c = pplex();
			}
		}
		*(p + 1) = 0;
		pp.token = token;
		pp.state = number;
		break;
	case V_ITERATE:
		n = 0;
		pp.token = pp.valbuf;
		if ((c = pplex()) != T_ID || !(sym = ppsymref(pp.symtab, pp.token)) || !sym->macro || sym->macro->arity != 1 || (c = pplex()) != ',')
		{
			error(2, "#(%s <macro(x)>, ...) expected", p);
			for (;;)
			{
				if (!c)
				{
					error(2, "%s in #(...) argument", pptokchr(c));
					break;
				}
				if (c == '(') n++;
				else if (c == ')' && !n--) break;
				c = pplex();
			}
			*pp.valbuf = 0;
		}
		else while (c != ')')
		{
			p = pp.token;
			if (pp.token > pp.valbuf) *pp.token++ = ' ';
			STRCOPY(pp.token, sym->name, a);
			*pp.token++ = '(';
			if (!c || !(c = pplex()))
			{
				pp.token = p;
				error(2, "%s in #(...) argument", pptokchr(c));
				break;
			}
			pp.state &= ~NOSPACE;
			while (c)
			{
				if (c == '(') n++;
				else if (c == ')' && !n--) break;
				else if (c == ',' && !n) break;
				pp.token = pp.toknxt;
				c = pplex();
			}
			*pp.token++ = ')';
			pp.state |= NOSPACE;
		}
		p = pp.valbuf;
		pp.token = token;
		pp.state = number;
		break;
	default:
		pp.token = token;
		while (c != ')')
		{
			if (!c)
			{
				error(2, "%s in #(...) argument", pptokchr(c));
				break;
			}
			if ((c = pplex()) == T_ID && !*a)
				strcpy(a, pp.token);
		}
		pp.state = number;
		switch (op)
		{
		case V_ARGC:
			c = -1;
			for (in = pp.in; in; in = in->prev)
				if ((in->type == IN_MACRO || in->type == IN_MULTILINE) && (in->symbol->flags & SYM_FUNCTION))
				{
					c = *((unsigned char*)(pp.macp->arg[0] - 2));
					break;
				}
			sfsprintf(p = pp.valbuf, MAXTOKEN, "%d", c);
			break;
		case V_BASE:
			p = (a = strrchr(error_info.file, '/')) ? a + 1 : error_info.file;
			break;
		case V_DATE:
			if (!(p = pp.date))
			{
				time_t	tm;

				time(&tm);
				a = p = ctime(&tm) + 4;
				*(p + 20) = 0;
				for (p += 7; *p = *(p + 9); p++);
				pp.date = p = strdup(a);
			}
			break;
		case V_FILE:
			p = error_info.file;
			break;
		case V_LINE:
			sfsprintf(p = pp.valbuf, MAXTOKEN, "%d", error_info.line);
			break;
		case V_PATH:
			p = pp.path;
			break;
		case V_SOURCE:
			p = error_info.file;
			for (in = pp.in; in->prev; in = in->prev)
				if (in->prev->type == IN_FILE && in->file)
					p = in->file;
			break;
		case V_STDC:
			p = pp.valbuf;
			p[0] = ((pp.state & (COMPATIBILITY|TRANSITION)) || (pp.mode & (HOSTED|HOSTEDTRANSITION)) == (HOSTED|HOSTEDTRANSITION)) ? '0' : '1';
			p[1] = 0;
			break;
		case V_TIME:
			if (!(p = pp.time))
			{
				time_t	tm;

				time(&tm);
				p = ctime(&tm) + 11;
				*(p + 8) = 0;
				pp.time = p = strdup(p);
			}
			break;
		case V_VERSION:
			p = (char*)pp.version;
			break;
		case V_DIRECTIVE:
			pp.state |= NEWLINE;
			pp.mode |= RELAX;
			strcpy(p = pp.valbuf, "#");
			break;
		case V_GETENV:
			if (!(p = getenv(a))) p = "";
			break;
		case V_GETMAC:
			p = (sym = pprefmac(a, REF_NORMAL)) ? sym->macro->value : "";
			break;
		case V_GETOPT:
			sfsprintf(p = pp.valbuf, MAXTOKEN, "%ld", ppoption(a));
			break;
		case V_GETPRD:
			p = (list = (struct pplist*)hashget(pp.prdtab, a)) ? list->value : "";
			break;
		case V__PRAGMA:
			if ((c = pplex()) == '(')
			{
				number = pp.state;
				pp.state |= NOSPACE|STRIP;
				c = pplex();
				pp.state = number;
				if (c == T_STRING || c == T_WSTRING)
				{
					if (!(sp = sfstropen()))
						error(3, "temporary buffer allocation error");
					sfprintf(sp, "#%s %s\n", dirname(PRAGMA), pp.token);
					a = sfstruse(sp);
					if ((c = pplex()) == ')')
					{
						pp.state |= NEWLINE;
						PUSH_BUFFER(p, a, 1);
					}
					sfstrclose(sp);
				}
			}
			if (c != ')')
				error(2, "%s: (\"...\") expected", p);
			return;
		case V_FUNCTION:

#define BACK(a,p)	((a>p)?*--a:(number++?0:((p=pp.outbuf+PPBUFSIZ),(a=pp.outbuf+2*PPBUFSIZ),*--a)))
#define PEEK(a,p)	((a>p)?*(a-1):(number?0:*(pp.outbuf+2*PPBUFSIZ-1)))

			number = pp.outbuf != pp.outb;
			a = pp.outp;
			p = pp.outb;
			op = 0;
			while (c = BACK(a, p))
			{
				if (c == '"' || c == '\'')
				{
					op = 0;
					while ((n = BACK(a, p)) && n != c || PEEK(a, p) == '\\');
				}
				else if (c == '\n')
				{
					token = a;
					while (c = BACK(a, p))
						if (c == '\n')
						{
							a = token;
							break;
						}
						else if (c == '#' && PEEK(a, p) == '\n')
							break;
				}
				else if (c == ' ')
					/*ignore*/;
				else if (c == '{') /* '}' */
					op = 1;
				else if (op == 1)
				{
					if (c == ')')
					{
						op = 2;
						n = 1;
					}
					else
						op = 0;
				}
				else if (op == 2)
				{
					if (c == ')')
						n++;
					else if (c == '(' && !--n)
						op = 3;
				}
				else if (op == 3)
				{
					if (ppisidig(c))
					{
						for (t = p, token = a, onumber = number; ppisidig(PEEK(a, p)) && a >= p; BACK(a, p));
						p = pp.valbuf + 1;
						if (a > token)
						{
							for (; a < pp.outbuf+2*PPBUFSIZ; *p++ = *a++);
							a = pp.outbuf;
						}
						for (; a <= token; *p++ = *a++);
						*p = 0;
						p = pp.valbuf + 1;
						if (streq(p, "for") || streq(p, "if") || streq(p, "switch") || streq(p, "while"))
						{
							op = 0;
							p = t;
							number = onumber;
							continue;
						}
					}
					else
						op = 0;
					break;
				}
			}
			if (op == 3)
				p = strncpy(pp.funbuf, p, sizeof(pp.funbuf) - 1);
			else if (*pp.funbuf)
				p = pp.funbuf;
			else
				p = "__FUNCTION__";
			break;
		default:
			if (pp.builtin && (a = (*pp.builtin)(pp.valbuf, p, a)))
				p = a;
			break;
		}
		break;
	}
	if (strchr(p, MARK))
	{
		a = pp.tmpbuf;
		strcpy(a, p);
		c = p != pp.valbuf;
		p = pp.valbuf + c;
		for (;;)
		{
			if (p < pp.valbuf + MAXTOKEN - 2)
				switch (*p++ = *a++)
				{
				case 0:
					break;
				case MARK:
					*p++ = MARK;
					/*FALLTHROUGH*/
				default:
					continue;
				}
			break;
		}
		p = pp.valbuf + c;
	}
	if (p == pp.valbuf)
		PUSH_STRING(p);
	else
	{
		if (p == pp.valbuf + 1)
			*pp.valbuf = '"';
		else
		{
			if (strlen(p) > MAXTOKEN - 2)
				error(1, "%-.16s: builtin value truncated", p);
			sfsprintf(pp.valbuf, MAXTOKEN, "\"%-.*s", MAXTOKEN - 2, p);
		}
		PUSH_QUOTE(pp.valbuf, 1);
	}
}
Ejemplo n.º 27
0
/* Display info about an individual Erlang process */
void
print_process_info(int to, void *to_arg, Process *p)
{
    time_t approx_started;
    int garbing = 0;
    int running = 0;
    struct saved_calls *scb;
    erts_aint32_t state;

    /* display the PID */
    erts_print(to, to_arg, "=proc:%T\n", p->common.id);

    /* Display the state */
    erts_print(to, to_arg, "State: ");

    state = erts_smp_atomic32_read_acqb(&p->state);
    erts_dump_process_state(to, to_arg, state);
    if (state & ERTS_PSFLG_GC) {
        garbing = 1;
        running = 1;
    } else if (state & (ERTS_PSFLG_RUNNING
			| ERTS_PSFLG_DIRTY_RUNNING))
        running = 1;

    /*
     * If the process is registered as a global process, display the
     * registered name
     */
    if (p->common.u.alive.reg)
	erts_print(to, to_arg, "Name: %T\n", p->common.u.alive.reg->name);

    /*
     * Display the initial function name
     */
    erts_print(to, to_arg, "Spawned as: %T:%T/%bpu\n",
	       p->u.initial[INITIAL_MOD],
	       p->u.initial[INITIAL_FUN],
	       p->u.initial[INITIAL_ARI]);
    
    if (p->current != NULL) {
	if (running) {
	    erts_print(to, to_arg, "Last scheduled in for: ");
	} else {
	    erts_print(to, to_arg, "Current call: ");
	}
	erts_print(to, to_arg, "%T:%T/%bpu\n",
		   p->current[0],
		   p->current[1],
		   p->current[2]);
    }

    erts_print(to, to_arg, "Spawned by: %T\n", p->parent);
    approx_started = (time_t) p->approx_started;
    erts_print(to, to_arg, "Started: %s", ctime(&approx_started));
    ERTS_SMP_MSGQ_MV_INQ2PRIVQ(p);
    erts_print(to, to_arg, "Message queue length: %d\n", p->msg.len);

    /* display the message queue only if there is anything in it */
    if (!ERTS_IS_CRASH_DUMPING && p->msg.first != NULL && !garbing) {
	ErtsMessage* mp;
	erts_print(to, to_arg, "Message queue: [");
	for (mp = p->msg.first; mp; mp = mp->next)
	    erts_print(to, to_arg, mp->next ? "%T," : "%T", ERL_MESSAGE_TERM(mp));
	erts_print(to, to_arg, "]\n");
    }

    {
       int frags = 0;
       ErlHeapFragment *m = p->mbuf;
       while (m != NULL) {
	   frags++;
	   m = m->next;
       }
       erts_print(to, to_arg, "Number of heap fragments: %d\n", frags);
    }
    erts_print(to, to_arg, "Heap fragment data: %beu\n", MBUF_SIZE(p));

    scb = ERTS_PROC_GET_SAVED_CALLS_BUF(p);
    if (scb) {
       int i, j;

       erts_print(to, to_arg, "Last calls:");
       for (i = 0; i < scb->n; i++) {
	     erts_print(to, to_arg, " ");
	     j = scb->cur - i - 1;
	     if (j < 0)
		j += scb->len;
	     if (scb->ct[j] == &exp_send)
		erts_print(to, to_arg, "send");
	     else if (scb->ct[j] == &exp_receive)
		erts_print(to, to_arg, "'receive'");
	     else if (scb->ct[j] == &exp_timeout)
		   erts_print(to, to_arg, "timeout");
	     else
		 erts_print(to, to_arg, "%T:%T/%bpu\n",
			    scb->ct[j]->code[0],
			    scb->ct[j]->code[1],
			    scb->ct[j]->code[2]);
       }
       erts_print(to, to_arg, "\n");
    }

    /* display the links only if there are any*/
    if (ERTS_P_LINKS(p) || ERTS_P_MONITORS(p)) {
	PrintMonitorContext context = {1,to}; 
	erts_print(to, to_arg,"Link list: [");
	erts_doforall_links(ERTS_P_LINKS(p), &doit_print_link, &context);	
	erts_doforall_monitors(ERTS_P_MONITORS(p), &doit_print_monitor, &context);
	erts_print(to, to_arg,"]\n");
    }

    if (!ERTS_IS_CRASH_DUMPING) {

	/* and the dictionary */
	if (p->dictionary != NULL && !garbing) {
	    erts_print(to, to_arg, "Dictionary: ");
	    erts_dictionary_dump(to, to_arg, p->dictionary);
	    erts_print(to, to_arg, "\n");
	}
    }
    
    /* print the number of reductions etc */
    erts_print(to, to_arg, "Reductions: %beu\n", p->reds);

    erts_print(to, to_arg, "Stack+heap: %beu\n", p->heap_sz);
    erts_print(to, to_arg, "OldHeap: %bpu\n",
               (OLD_HEAP(p) == NULL) ? 0 : (OLD_HEND(p) - OLD_HEAP(p)) );
    erts_print(to, to_arg, "Heap unused: %bpu\n", (p->hend - p->htop));
    erts_print(to, to_arg, "OldHeap unused: %bpu\n",
	       (OLD_HEAP(p) == NULL) ? 0 : (OLD_HEND(p) - OLD_HTOP(p)) );
    erts_print(to, to_arg, "Memory: %beu\n", erts_process_memory(p, !0));

    if (garbing) {
	print_garb_info(to, to_arg, p);
    }
    
    if (ERTS_IS_CRASH_DUMPING) {
	erts_program_counter_info(to, to_arg, p);
    } else {
	erts_print(to, to_arg, "Stack dump:\n");
#ifdef ERTS_SMP
	if (!garbing)
#endif
	    erts_stack_dump(to, to_arg, p);
    }

    /* Display all states */
    erts_print(to, to_arg, "Internal State: ");
    erts_dump_extended_process_state(to, to_arg, state);
}
Ejemplo n.º 28
0
static STATUS _backup_dir_show(char *path)
{
    DIR* d;
    struct dirent* de;
    d = opendir(path);
    return_val_if_fail(d != NULL, RET_FAIL);

    int d_size = 0;
    int d_alloc = 10;
    return_val_if_fail(backup_menu != NULL, RET_FAIL);
    char** dirs = malloc(d_alloc * sizeof(char*));
    char** dirs_desc = malloc(d_alloc * sizeof(char*));
    return_val_if_fail(dirs != NULL, RET_FAIL);
    return_val_if_fail(dirs_desc != NULL, RET_FAIL);
    int z_size = 1;
    int z_alloc = 10;
    char** zips = malloc(z_alloc * sizeof(char*));
    char** zips_desc=malloc(z_alloc * sizeof(char*));
    return_val_if_fail(zips != NULL, RET_FAIL);
    return_val_if_fail(zips_desc != NULL, RET_FAIL);
    zips[0] = strdup("../");
    zips_desc[0]=strdup("../");

    while ((de = readdir(d)) != NULL) {
        int name_len = strlen(de->d_name);
        char de_path[PATH_MAX];
        snprintf(de_path, PATH_MAX, "%s/%s", path, de->d_name);
        struct stat st ;
        assert_if_fail(stat(de_path, &st) == 0);
        if (de->d_type == DT_DIR) {
            //skip "." and ".." entries
            if (name_len == 1 && de->d_name[0] == '.') continue;
            if (name_len == 2 && de->d_name[0] == '.' && 
                    de->d_name[1] == '.') continue;
            if (d_size >= d_alloc) {
                d_alloc *= 2;
                dirs = realloc(dirs, d_alloc * sizeof(char*));
                dirs_desc = realloc(dirs_desc, d_alloc * sizeof(char*));
            }
            dirs[d_size] = malloc(name_len + 2);
            dirs_desc[d_size] = malloc(64);
            strcpy(dirs[d_size], de->d_name);
            dirs[d_size][name_len ] = '\0';
            snprintf(dirs_desc[d_size], 64, "%s" ,ctime(&st.st_mtime));
            ++d_size;
        } else if (de->d_type == DT_REG && name_len >= 4 &&
                  strncasecmp(de->d_name + (name_len - 4), ".zip", 4) == 0) {
            if (z_size >= z_alloc) {
                z_alloc *= 2;
                zips = realloc(zips, z_alloc * sizeof(char*));
                zips_desc = realloc(zips_desc, z_alloc * sizeof(char*));
            }
            zips[z_size] = strdup(de->d_name);
            zips_desc[z_size] = malloc(64);
            snprintf(zips_desc[z_size], 64, "%s   %lldbytes" ,ctime(&st.st_mtime), st.st_size);
            z_size++;
        }
    }
    closedir(d);


    // append dirs to the zips list
    if (d_size + z_size + 1 > z_alloc) {
        z_alloc = d_size + z_size + 1;
        zips = realloc(zips, z_alloc * sizeof(char*));
        zips_desc = realloc(zips_desc, z_alloc * sizeof(char*));
    }
    memcpy(zips + z_size, dirs, d_size * sizeof(char *));
    memcpy(zips_desc + z_size, dirs_desc, d_size * sizeof(char*));
    free(dirs);
    z_size += d_size;
    zips[z_size] = NULL;
    zips_desc[z_size] = NULL;

   int result;
   int chosen_item = 0;
   do {
       chosen_item = miui_sdmenu(backup_menu->name, zips, zips_desc, z_size);
       return_val_if_fail(chosen_item >= 0, RET_FAIL);
       char * item = zips[chosen_item];
       int item_len = strlen(item);
       if ( chosen_item == 0) {
           //go up but continue browsing
           result = -1;
           break;
       } else {
           // select a zipfile
           // the status to the caller
           char new_path[PATH_MAX];
           strlcpy(new_path, path, PATH_MAX);
           strlcat(new_path, "/", PATH_MAX);
           strlcat(new_path, item, PATH_MAX);
           /*
            *nandroid_restore(backup_path, restore_boot, system, data, chache , sdext, wimax)
            */
           if (p_current != NULL && RET_YES == miui_confirm(3, p_current->name, p_current->desc, p_current->icon)) {
               backup_restore(new_path);
           }
           break;
       }
   } while(1);

   int i;
   for (i = 0; i < z_size; ++i) 
   {
       free(zips[i]);
       free(zips_desc[i]);
   }
   free(zips);
   return result;
}
Ejemplo n.º 29
0
int
schd_run_job_on(Job *job, Queue *destq, char *exechost, int set_comment)
  {
  char   *id = "schd_run_job_on";
  char    reason[128], tmp_word[20];
  char   *date;
  Queue  *srcq = NULL;
  int     ret = 0;
  int     local_errno = 0;

  /* Get the datestamp from 'ctime()'.  Remove the trailing '\n'. */
  date = ctime(&schd_TimeNow);
  date[strlen(date) - 1] = '\0';

  if (set_comment)
    {
    sprintf(reason, "Started on %s", date);

    if (job->flags & JFLAGS_PRIORITY)
      {
      strcat(reason, " (EXPRESS/high priority job)");
      }

    if (job->flags & JFLAGS_WAITING)
      {
      strcat(reason, " (long-waiting job)");
      }

    schd_comment_job(job, reason, JOB_COMMENT_REQUIRED);
    }

  /* If this is NOT a suspended job... */
  if (!(job->flags & JFLAGS_SUSPENDED))
    {

    /*
     * If a destination Queue is provided, and it is different from the
     * source queue, then ask PBS to move the job to that queue before
     * running it.
     */
    srcq = job->queue;

    /*
     * Move the job from its queue to the specified run queue.
     */

    if ((destq != NULL) && (strcmp(destq->qname, srcq->qname) != 0))
      {
      if (pbs_movejob_err(connector, job->jobid, destq->qname, NULL, &local_errno))
        {
        (void)sprintf(log_buffer, "move job %s to queue %s failed, %d",
                      job->jobid, destq->qname, local_errno);
        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER,
                   id, log_buffer);
        DBPRT(("%s: %s\n", id, log_buffer));
        return (-1);
        }

      schd_move_job_to(job, destq);
      }

    /*
    * Give the job handle (JOBID) to PBS to run.
    */
    if (pbs_runjob_err(connector, job->jobid, exechost, NULL, &local_errno))
      {
      (void)sprintf(log_buffer, "failed start job %s on queue %s@%s, %d",
                    job->jobid, destq->qname, exechost, local_errno);
      log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
      DBPRT(("%s: %s\n", id, log_buffer));

      /*
       * Running failed! Move the job back to the source queue (if
       * applicable) before returning. This prevents jobs being left
       * in execution queues.
       */

      if (srcq)
        {
        DBPRT(("Attempting to move job %s back to queue %s\n",
               job->jobid, srcq->qname));

        if (pbs_movejob_err(connector, job->jobid, srcq->qname, NULL, &local_errno))
          {
          (void)sprintf(log_buffer,
                        "failed to move job %s back to queue %s, %d",
                        job->jobid, srcq->qname, local_errno);
          log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id,
                     log_buffer);
          DBPRT(("%s: %s\n", id, log_buffer));
          }

        schd_move_job_to(job, srcq);
        }

      return (-1);
      }

    strcpy(tmp_word, "started");
    }
  else    /* it IS a suspended job */
    {

    schd_move_job_to(job, destq);
    ret = pbs_sigjob(connector, job->jobid, "resume", NULL);

    if (ret)
      {
      sprintf(log_buffer, "resume of job %s FAILED (%d)",
              job->jobid, ret);
      return (-1);
      }

    job->flags &= ~JFLAGS_SUSPENDED;

    strcpy(tmp_word, "resumed");
    }

  /* PBS accepted the job (and presumably will run it). Log the fact. */
  (void)sprintf(log_buffer, "job %s %s on %s@%s", job->jobid, tmp_word,
                destq->qname, exechost);

  log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

  DBPRT(("%s: %s\n", id, log_buffer));

  /*
   * Change the state of the local representation of the job to "Running".
   */
  job->state = 'R';

  /*
   * Account for the job on this queue's statistics.  'queued' will be
   * bumped up if the queued job was moved to a new destination queue.
   */

  job->queue->queued --;

  job->queue->running ++;

  /* The queue is no longer idle.  Unset the idle timer. */
  job->queue->idle_since = 0;

  return (0);    /* Job successfully started. */
  }
Ejemplo n.º 30
0
Archivo: Get.c Proyecto: aosm/ncftp
int DoGet(GetOptionsPtr gopt)
{
	int fd;
	int result;
	string local;
	long fileSize;
	time_t modifTime;
	int doReports;
	struct stat st;
	size_t restartPt;
	const char *mode = "w";
	time_t now;
	XferSpecPtr xp;

	if (gTransferType == 'A') {
		/* Have to set the type here, because GetDateAndSize() may
		 * use the SIZE command, and the result of that depends
		 * on the current transfer type setting.
		 */
		SETASCII;
	} else {
		SetType(gTransferType);
	}
	
	/* See if we can get some info about the file first. */
	fileSize = GetDateAndSize(gopt->rName, &modifTime);
	restartPt = SZ(0);
	doReports = 0;

	if (gopt->outputMode == kDumpToStdout) {
		fd = gStdout;
		STRNCPY(local, kLocalFileIsStdout);
		/* Don't have progress reports going if we're piping or
		 * dumping to the screen.
		 */
	} else {
		GetLocalName(gopt, local);
		if (stat(local, &st) == 0) {
			/* File exists on the local host.  We must decide whether
			 * we really want to fetch this file, since we might have
			 * it here already.  But when in doubt, we will go ahead
			 * and fetch the file.
			 */
			if (gopt->forceReget) {
				/* If the local file is smaller, then we
				 * should attempt to restart the transfer
				 * from where we left off.
				 */
				if ((st.st_size < fileSize) || (fileSize == kSizeUnknown)) {
					restartPt = SZ(st.st_size);
					mode = "a";
					DebugMsg("Manually continuing local file %s.", local);
				} else {
					PrintF("Already have %s with size %lu.\n", gopt->rName, fileSize);
					return (0);
				}
			} else if (!gopt->overwrite) {
				if (modifTime != kModTimeUnknown) {
					/* We know the date of the remote file. */
					DebugMsg("Local file %s has size %lu and is dated %s",
						local,
						(unsigned long) st.st_size,
						ctime(&st.st_mtime)
					);
					if (modifTime < st.st_mtime) {
						/* Remote file is older than existing local file. */
						PrintF("Already have %s.\n", gopt->rName);
						return (0);
					} else if (modifTime == st.st_mtime) {
						/* Remote file is same age. */
						if (fileSize != kSizeUnknown) {
							/* If the local file is smaller, then we
							 * should attempt to restart the transfer
							 * from where we left off, since we the remote
							 * file has the same date.
							 */
							if (st.st_size < fileSize) {
								restartPt = SZ(st.st_size);
								mode = "a";
							} else if (st.st_size == fileSize) {
								PrintF("Already have %s.\n", gopt->rName);
								return (0);
							} else {
								DebugMsg("Overwriting %s; local file has same date,\n",
									gopt->lName);
								DebugMsg("but local file is larger, so fetching remote version anyway.\n");
							}
						} else {
							DebugMsg("Overwriting %s; local file has same date,\n",
									gopt->lName);
							DebugMsg("but can't determine remote size, so fetching remote version anyway.\n");
						}
					} else {
						/* Remote file is more recent.  Fetch the
						 * whole file.
						 */
						DebugMsg("Overwriting %s; remote was newer.\n",
							gopt->lName);
					}
				} else {
					/* We don't know the date of the file.
					 * We won't be able to safely assume anything about
					 * the remote file.  It is legal to have a more
					 * recent remote file (which we don't know), with a
					 * smaller (or greater, or equal even) size.  We
					 * will just have to fetch it no matter what.
					 */
					DebugMsg("Overwriting %s; couldn't determine remote file date.\n",
						gopt->lName);
				}
			} else {
				DebugMsg("Explicitly overwriting %s.\n", gopt->lName);
			}
		} else {
			/* We don't have a local file with the same name as the remote,
			 * but we may also want to avoid doing the transfer of this
			 * file.  For example, this is where we check the remote
			 * file's date if we were told to only get files which are
			 * less than X days old.
			 */
			if (gopt->newer > 0) {
				time(&now);
				if (((unsigned long) now - (unsigned long) (gopt->newer * 86400)) > (unsigned long) modifTime) {
					DebugMsg("Skipping %s, older than %d days.\n",
						gopt->rName, gopt->newer);
					return (0);
				}
			}
		}
		if (*mode == 'w')
			fd = open(local, O_WRONLY | O_TRUNC | O_CREAT,
				S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
		else
			fd = open(local, O_WRONLY | O_APPEND | O_CREAT,
				S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
		if (fd < 0) {
			Error(kDoPerror, "Can't open local file %s.\n", local);
			return (-1);
		}
		doReports = gopt->doReports;
	}

	xp = InitXferSpec();
	xp->netMode = kNetReading;
	xp->outStream = fd;
	
	/* This group is needed for the progress reporting and logging stuff.
	 * Otherwise, it isn't that important.
	 */
	xp->doReports = doReports;
	xp->localFileName = local;
	xp->remoteFileName = gopt->rName;
	xp->expectedSize = fileSize;
	xp->startPoint = restartPt;
	xp->doUTime = gopt->doUTime;
	xp->remoteModTime = modifTime;
	
	if (gTransferType == 'A') {
		result = AsciiGet(xp);
	} else {		
		result = BinaryGet(xp);
	}

	if (fd != gStdout) {
		(void) close(fd);
		if ((result < 0) && (xp->bytesTransferred < 1L) && (*mode != 'a')) {
			/* An error occurred, and we didn't transfer anything,
			 * so remove empty file we just made.
			 */
			(void) UNLINK(local);
		} else {
			/* Restore the modifcation date of the new file to
			 * what it was on the remote host, if possible.
			 */
			SetLocalFileTimes(gopt->doUTime, modifTime, local);
		}
	}

	DoneWithXferSpec(xp);
	return (result);
}	/* DoGet */