Exemplo n.º 1
2
int main(void)
{
  // GetCurrentProcess cannot fail
  HANDLE hProcess = GetCurrentProcess();

  if (OpenProcessToken(hProcess, TOKEN_READ, &hProcess))
  {
    LUID seCreateSymbolicLinkPrivilege;

    if (LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &seCreateSymbolicLinkPrivilege))
    {
      DWORD length;

      printf("SeCreateSymbolicLinkPrivilege = %ld, %ld\n", seCreateSymbolicLinkPrivilege.HighPart, seCreateSymbolicLinkPrivilege.LowPart);

      if (!GetTokenInformation(hProcess, TokenPrivileges, NULL, 0, &length))
      {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
          TOKEN_PRIVILEGES* privileges = (TOKEN_PRIVILEGES*)malloc(length);
          if (GetTokenInformation(hProcess, TokenPrivileges, privileges, length, &length))
          {
            BOOL found = FALSE;
            DWORD count = privileges->PrivilegeCount;

            printf("User has %ld privileges\n", count);

            if (count > 0)
            {
              LUID_AND_ATTRIBUTES* privs = privileges->Privileges;
              while (count-- > 0 && !luid_eq(privs->Luid, seCreateSymbolicLinkPrivilege))
                privs++;
              found = (count > 0);
            }

            printf("User does%s have the SeCreateSymbolicLinkPrivilege\n", (found ? "" : "n't"));
          }
          else
          {
            fprintf(stderr, "Second GetTokenInformation failed\n");
          }

          free(privileges);
        }
        else
        {
          fprintf(stderr, "First GetTokenInformation failed\n");
        }
      }
      else
      {
        fprintf(stderr, "Impossible output from GetTokenInformation\n");
      }
    }
    else
    {
      fprintf(stderr, "LookupPrivilegeValue failed\n");
    }

    CloseHandle(hProcess);
  }
  else
  {
    fprintf(stderr, "OpenProcessToken failed\n");
  }

  LSA_HANDLE hPolicy;
  NTSTATUS r;
  LSA_OBJECT_ATTRIBUTES attributes = {0, NULL, NULL, 0, NULL, NULL};
  attributes.Length = sizeof(attributes);

  LUID seCreateSymbolicLinkPrivilege;

  if (LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &seCreateSymbolicLinkPrivilege))
  {
    // POLICY_LOOKUP_NAMES: LsaLookupNames2, LsaEnumerateAccountRights, LsaLookupSids, LsaAddAccountRights
    // POLICY_VIEW_LOCAL_INFORMATION: LsaEnumerateAccountsWithUserRight
    // Elevation: LsaEnumerateAccountRights, LsaEnumerateAccountsWithUserRight, LsaRemoveAccountRights, LsaAddAccountRights
    if (NT_SUCCESS(r = LsaOpenPolicy(NULL, &attributes, POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, &hPolicy)))
    {
      LSA_REFERENCED_DOMAIN_LIST* referencedDomains;
      LSA_TRANSLATED_SID2* sids;
      LSA_UNICODE_STRING name;
      name.Buffer = L"Users";
      name.Length = wcslen(name.Buffer) * sizeof(WCHAR);
      name.MaximumLength = name.Length + sizeof(WCHAR);
  
      if (NT_SUCCESS(r = LsaLookupNames2(hPolicy, LSA_LOOKUP_ISOLATED_AS_LOCAL, 1, &name, &referencedDomains, &sids)))
      {
        LSA_UNICODE_STRING* rights;
        ULONG count;
        LsaFreeMemory(referencedDomains);

        if (NT_SUCCESS(r = LsaEnumerateAccountRights(hPolicy, sids->Sid, &rights, &count)))
        {
          LSA_UNICODE_STRING* right = rights;
          printf("%ld right%s found\n", count, PLURAL(count));
          while (count-- > 0)
          {
            printf("  %.*S\n", right->Length / 2, right->Buffer);
            right++;
          }

          LsaFreeMemory(rights);

          LSA_ENUMERATION_INFORMATION* allSidsRaw;
          LSA_UNICODE_STRING lsaCreateSymbolicLinkPrivilege;
          lsaCreateSymbolicLinkPrivilege.Buffer = SE_CREATE_SYMBOLIC_LINK_NAME;
          lsaCreateSymbolicLinkPrivilege.Length = wcslen(lsaCreateSymbolicLinkPrivilege.Buffer) * sizeof(WCHAR);
          lsaCreateSymbolicLinkPrivilege.MaximumLength = lsaCreateSymbolicLinkPrivilege.Length + sizeof(WCHAR);
          if (NT_SUCCESS(r = LsaEnumerateAccountsWithUserRight(hPolicy, &lsaCreateSymbolicLinkPrivilege, (void**)&allSidsRaw, &count)))
          {
            LSA_ENUMERATION_INFORMATION* sid = allSidsRaw;
            PSID* allSids;
            PSID* p;
            PLSA_TRANSLATED_NAME names;
            ULONG i = count;

            printf("%ld SID%s found\n", count, PLURAL(count));
            p = allSids = (PSID*)malloc(count * sizeof(PSID));

            while (i-- > 0)
              *p++ = (sid++)->Sid;

            if (NT_SUCCESS(r = LsaLookupSids(hPolicy, count, allSids, &referencedDomains, &names)))
            {
              PLSA_TRANSLATED_NAME name = names;
              BOOL usersAssigned = FALSE;

              LsaFreeMemory(referencedDomains);

              while (count-- > 0)
              {
                LPTSTR sidString;
                USHORT len = name->Name.Length / 2;
                ConvertSidToStringSid(*allSids++, &sidString);
                printf("  %.*S (%S)\n", len, name->Name.Buffer, sidString);
                usersAssigned |= (len > 4 && !wcsncmp(L"Users", name->Name.Buffer, len));
                name++;
                LocalFree(sidString);
              }

              printf("Users had%s got SeCreateSymbolicLinkPrivilege\n", (usersAssigned ? "" : "n't"));
              if (usersAssigned)
              {
                if (!NT_SUCCESS(r = LsaRemoveAccountRights(hPolicy, sids->Sid, FALSE, &lsaCreateSymbolicLinkPrivilege, 1)))
                {
                  fprintf(stderr, "Lsa failed with code %x\n", r);
                }
              }
              else
              {
                if (!NT_SUCCESS(r = LsaAddAccountRights(hPolicy, sids->Sid, &lsaCreateSymbolicLinkPrivilege, 1)))
                {
                  fprintf(stderr, "LsaAddAccountRights failed with code %x\n", r);
                }
              }

              LsaFreeMemory(names);
            }
            else
            {
              fprintf(stderr, "LsaLookupSids2 failed with code %x\n", r);
            }
              
            LsaFreeMemory(allSidsRaw);
            free(allSids);
          }
          else
          {
            fprintf(stderr, "LsaEnumerateAccountsWithUserRight failed with code %x\n", r);
          }
        }
        else
        {
          fprintf(stderr, "LsaEnumerateAccountRights failed with code %x\n", r);
        }

        LsaFreeMemory(sids);
      }
      else
      {
        fprintf(stderr, "LsaLookupNames2 failed with code %x\n", r);
      }
  
      LsaClose(hPolicy);
    }
    else
    {
      fprintf(stderr, "LsaOpenPolicy failed with code %x\n", r);
    }
  }
  else
  {
    fprintf(stderr, "LookupPrivilegeValue failed\n");
  }
}
Exemplo n.º 2
0
StackIndex args_extract(const char* caller, Pointer args, int min, int max)
{
    StackIndex before = valuestack_top();

    // First process the mandatory args.
    for (int i = 0; i < min; i++) {
        if (args.type != Type_pair) {
            // We've run out of args.
            THROW("%s: %s%d arg%s expected, %d provided",
                caller, min == max ? "" : "at least ",
                min, PLURAL(min), i);
        }
        PUSH(pair_get(args, 0));
        args = pair_get(args, 1);
    }

    // Then process the optional args, if required.
    for (int i = min; args.type != Type_nil && (i < max); i++) {
        PUSH(pair_get(args, 0));
        args = pair_get(args, 1);
    }

    // Now check that there aren't any more args.
    if (args.type != Type_nil) {
        int got = max + args_count(args);

        THROW("%s: %s%d arg%s expected, %d provided",
              caller, min == max ? "" : "no more than ",
              max, PLURAL(max), got);
    }

    return before;
}
Exemplo n.º 3
0
/* ARGSUSED */
static int
do_params(const char *cname, int argc, char **argv)
{
	struct changer_params data;

	/* No arguments to this command. */
	if (argc) {
		warnx("%s: no arguments expected", cname);
		usage();
		/* NOTREACHED */
	}
	
	/* Get params from changer and display them. */
	(void)memset(&data, 0, sizeof(data));
	if (ioctl(changer_fd, CHIOGPARAMS, &data))
		err(EXIT_FAILURE, "%s: CHIOGPARAMS", changer_name);
		/* NOTREACHED */

#define	PLURAL(n)	(n) > 1 ? "s" : ""

	(void)printf("%s: %d slot%s, %d drive%s, %d picker%s",
	    changer_name,
	    data.cp_nslots, PLURAL(data.cp_nslots),
	    data.cp_ndrives, PLURAL(data.cp_ndrives),
	    data.cp_npickers, PLURAL(data.cp_npickers));
	if (data.cp_nportals)
		(void)printf(", %d portal%s", data.cp_nportals,
		    PLURAL(data.cp_nportals));

#undef PLURAL

	(void)printf("\n%s: current picker: %d\n", changer_name, data.cp_curpicker);

	return (0);
}
Exemplo n.º 4
0
static void
total_conflicts(void)
{
    fprintf(stderr, "%s: ", myname);
    if (SRtotal == 1)
	fprintf(stderr, "1 shift/reduce conflict");
    else if (SRtotal > 1)
	fprintf(stderr, "%d shift/reduce conflicts", SRtotal);

    if (SRtotal && RRtotal)
	fprintf(stderr, ", ");

    if (RRtotal == 1)
	fprintf(stderr, "1 reduce/reduce conflict");
    else if (RRtotal > 1)
	fprintf(stderr, "%d reduce/reduce conflicts", RRtotal);

    fprintf(stderr, ".\n");

    if (SRexpect >= 0 && SRtotal != SRexpect)
    {
	fprintf(stderr, "%s: ", myname);
	fprintf(stderr, "expected %d shift/reduce conflict%s.\n",
		SRexpect, PLURAL(SRexpect));
	exit_code = EXIT_FAILURE;
    }
    if (RRexpect >= 0 && RRtotal != RRexpect)
    {
	fprintf(stderr, "%s: ", myname);
	fprintf(stderr, "expected %d reduce/reduce conflict%s.\n",
		RRexpect, PLURAL(RRexpect));
	exit_code = EXIT_FAILURE;
    }
}
Exemplo n.º 5
0
static void
log_conflicts(void)
{
    int i;

    fprintf(verbose_file, "\n\n");
    for (i = 0; i < nstates; i++)
    {
	if (SRconflicts[i] || RRconflicts[i])
	{
	    fprintf(verbose_file, "State %d contains ", i);
	    if (SRconflicts[i] > 0)
		fprintf(verbose_file, "%d shift/reduce conflict%s",
			SRconflicts[i],
			PLURAL(SRconflicts[i]));
	    if (SRconflicts[i] && RRconflicts[i])
		fprintf(verbose_file, ", ");
	    if (RRconflicts[i] > 0)
		fprintf(verbose_file, "%d reduce/reduce conflict%s",
			RRconflicts[i],
			PLURAL(RRconflicts[i]));
	    fprintf(verbose_file, ".\n");
	}
    }
}
Exemplo n.º 6
0
static size_t obj_desc_pval(const object_type *o_ptr, char *buf, size_t max, size_t end)
{
	u32b f1, f2, f3, fn;
	object_flags(o_ptr, &f1, &f2, &f3, &fn);

	if (!(f1 & TR1_PVAL_MASK)) return end;

	strnfcat(buf, max, &end, " (%+d", o_ptr->pval);

	if (!(f3 & TR3_HIDE_TYPE))
	{
		if (f1 & TR1_STEALTH)
			strnfcat(buf, max, &end, " stealth");
		else if (f1 & TR1_SEARCH)
			strnfcat(buf, max, &end, " searching");
		else if (f1 & TR1_INFRA)
			strnfcat(buf, max, &end, " infravision");
		else if (f1 & TR1_SPEED)
			strnfcat(buf, max, &end, " speed");
		else if (f1 & TR1_BLOWS)
			strnfcat(buf, max, &end, " attack%s", PLURAL(o_ptr->pval));
	}

	strnfcat(buf, max, &end, ")");

	return end;
}
Exemplo n.º 7
0
/**
 * Describe charges or charging status for re-usable items with magic effects
 */
static size_t obj_desc_charges(const struct object *obj, char *buf, size_t max,
							   size_t end, int mode)
{
	bool aware = object_flavor_is_aware(obj) || (mode & ODESC_STORE);

	/* Wands and Staffs have charges */
	if (aware && tval_can_have_charges(obj))
		strnfcat(buf, max, &end, " (%d charge%s)", obj->pval,
				 PLURAL(obj->pval));

	/* Charging things */
	else if (obj->timeout > 0)
	{
		if (tval_is_rod(obj) && obj->number > 1)
		{
			strnfcat(buf, max, &end, " (%d charging)", number_charging(obj));
		}
		/* Artifacts, single rods */
		else if (!(tval_is_light(obj) && !obj->artifact))
		{
			strnfcat(buf, max, &end, " (charging)");
		}
	}

	return end;
}
Exemplo n.º 8
0
static size_t obj_desc_pval(const object_type *o_ptr, char *buf, size_t max, size_t end)
{
	bitflag f[OF_SIZE];

	object_flags(o_ptr, f);

	if (!flags_test(f, OF_SIZE, OF_PVAL_MASK, FLAG_END)) return end;

	strnfcat(buf, max, &end, " (%+d", o_ptr->pval);

	if (!of_has(f, OF_HIDE_TYPE))
	{
		if (of_has(f, OF_STEALTH))
			strnfcat(buf, max, &end, " stealth");
		else if (of_has(f, OF_SEARCH))
			strnfcat(buf, max, &end, " searching");
		else if (of_has(f, OF_INFRA))
			strnfcat(buf, max, &end, " infravision");
		else if (of_has(f, OF_SPEED))
			strnfcat(buf, max, &end, " speed");
		else if (of_has(f, OF_BLOWS))
			strnfcat(buf, max, &end, " attack%s", PLURAL(o_ptr->pval));
	}

	strnfcat(buf, max, &end, ")");

	return end;
}
Exemplo n.º 9
0
int args_checkCount(const char* caller, int expected, int got)
{
    if (expected != got) {
        THROW("%s: %d arg%s expected, %d provided",
            caller, expected, PLURAL(expected), got);
    }
    return got;
}
Exemplo n.º 10
0
/**
 * Describe the charges on an item in the inventory.
 */
void inven_item_charges(struct object *obj)
{
	/* Require staff/wand */
	if (tval_can_have_charges(obj) && object_flavor_is_aware(obj)) {
		msg("You have %d charge%s remaining.",
				obj->pval,
				PLURAL(obj->pval));
	}
}
Exemplo n.º 11
0
int TransferOK (time_t dNow)
{
char     szBuf [256];
    StopTransfer ();    // free resources

     // close MD5 computation
     MD5Final (sTC.m.ident, & sTC.m.ctx);

    // Semaphore released
    ReleaseSemaphore (hTftpClientSemaphore, 1, NULL);

    if (! sTC.bMultiFile)  
    {char szMD5 [33];
     int Ark;
     for (Ark=0 ; Ark<16; Ark++)
         wsprintf (szMD5 + 2*Ark, "%02x", sTC.m.ident[Ark]);
      wsprintf (szBuf, "%d block%s transferred in %d second%s\n %d block%s retransmitted\nMD5: %s",
                       sTC.nCount, // + (sTC.opcode==TFTP_RRQ ? 1 : 0),
                       PLURAL (sTC.nCount), // + (sTC.opcode==TFTP_RRQ ? 1 : 0)),
                       (int) (dNow-sTC.StartTime),
                       PLURAL (dNow-sTC.StartTime),
                       sTC.nTotRetrans,
                       PLURAL (sTC.nTotRetrans),
                       szMD5
            );
        CMsgBox (hTftpClientWnd, szBuf, APPLICATION, MB_OK | MB_ICONINFORMATION);
   } // one transfer --> display stats
 else 
  {
      sTC.dwMultiFileBlk += sTC.nCount;
      sTC.dwMultiFile++;
 }


return TRUE;
} // TransferOK
Exemplo n.º 12
0
static size_t obj_desc_charges(const object_type * o_ptr, char *buf, size_t max,
			       size_t end)
{
    object_kind *k_ptr = &k_info[o_ptr->k_idx];

    bool aware = object_aware_p(o_ptr);

    /* Wands and Staffs have charges */
    if (aware && (o_ptr->tval == TV_STAFF || o_ptr->tval == TV_WAND))
	strnfcat(buf, max, &end, " (%d charge%s)", o_ptr->pval,
		 PLURAL(o_ptr->pval));

    /* Charging things */
    else if (o_ptr->timeout > 0) {
	if (o_ptr->tval == TV_ROD && o_ptr->number > 1) {
	    int power;
	    int time_base = randcalc(k_ptr->time, 0, MINIMISE);

	    if (!time_base)
		time_base = 1;

	    /* 
	     * Find out how many rods are charging, by dividing
	     * current timeout by each rod's maximum timeout.
	     * Ensure that any remainder is rounded up.  Display
	     * very discharged stacks as merely fully discharged.
	     */
	    power = (o_ptr->timeout + (time_base - 1)) / time_base;
	    if (power > o_ptr->number)
		power = o_ptr->number;

	    /* Display prettily */
	    strnfcat(buf, max, &end, " (%d charging)", power);
	}

	/* Artifacts, single rods */
	else if (!(o_ptr->tval == TV_LIGHT && !artifact_p(o_ptr))) {
	    strnfcat(buf, max, &end, " (charging)");
	}
    }

    return end;
}
Exemplo n.º 13
0
/**
* Searches for all uses of a craft and displays them.
*
* @param char_data *ch The player.
* @param craft_vnum vnum The craft vnum.
*/
void olc_search_craft(char_data *ch, craft_vnum vnum) {
	char buf[MAX_STRING_LENGTH];
	craft_data *craft = craft_proto(vnum);
	int size, found;
	
	if (!craft) {
		msg_to_char(ch, "There is no craft %d.\r\n", vnum);
		return;
	}
	
	found = 0;
	size = snprintf(buf, sizeof(buf), "Occurrences of craft %d (%s):\r\n", vnum, GET_CRAFT_NAME(craft));
	
	// crafts are not found anywhere in the world yet
	
	if (found > 0) {
		size += snprintf(buf + size, sizeof(buf) - size, "%d location%s shown\r\n", found, PLURAL(found));
	}
	else {
		size += snprintf(buf + size, sizeof(buf) - size, " none\r\n");
	}
	
	page_string(ch->desc, buf, TRUE);
}
Exemplo n.º 14
0
/*
 * Learn the specified spell.
 */
void spell_learn(int spell)
{
	int i;
	const char *p = ((cp_ptr->spell_book == TV_MAGIC_BOOK) ? "spell" : "prayer");

	/* Learn the spell */
	p_ptr->spell_flags[spell] |= PY_SPELL_LEARNED;

	/* Find the next open entry in "spell_order[]" */
	for (i = 0; i < PY_MAX_SPELLS; i++)
	{
		/* Stop at the first empty space */
		if (p_ptr->spell_order[i] == 99) break;
	}

	/* Add the spell to the known list */
	p_ptr->spell_order[i] = spell;

	/* Mention the result */
	msgt(MSG_STUDY, "You have learned the %s of %s.",
	           p, get_spell_name(cp_ptr->spell_book, spell));

	/* One less spell available */
	p_ptr->new_spells--;

	/* Message if needed */
	if (p_ptr->new_spells)
	{
		/* Message */
		msg("You can learn %d more %s%s.",
		           p_ptr->new_spells, p, PLURAL(p_ptr->new_spells));
	}

	/* Redraw Study Status */
	p_ptr->redraw |= (PR_STUDY | PR_OBJECT);
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
    int i, f, size, symcnt, off;
    unsigned int fingerprint;
    int num_funcs = 0;
    int fancy_output = 0;
    int strip_names = 0;
    bfd *b;
    asymbol **syms;
    unsigned char buf[SIGNATSIZE+4];
    char *nameptr;

    const char *short_options = "fsh";
    struct option long_options[] = {
        {"fancy", no_argument, NULL, 'f'},
        {"strip", no_argument, NULL, 's'},
        {"help",  no_argument, NULL, 'h'},
        {0,       no_argument, NULL, 0}
    };

    while ((i = getopt_long(argc, argv, short_options, long_options, NULL)) != EOF) {
        switch (i) {
            case 'f':
                fancy_output = 1;
                break;
            case 's':
                strip_names = 1;
                break;
            case 'h':
            case '?':
                usage(argv[0]); /* never returns */
            default:
                break;
        }
    }

    if (optind >= argc) {
        usage(argv[0]); /* never returns */
        exit(1);
    }

    while (optind < argc) {
        b = bfd_openr(argv[optind++], 0);
        if (!b) {
            fprintf(stderr, "bfd_openr failed for '%s'\n", argv[optind - 1]);
            continue;
        }

        bfd_check_format(b, bfd_archive);
        bfd_check_format_matches(b, bfd_object, 0);

        if ((bfd_get_file_flags(b) & HAS_SYMS) == 0) {
            fprintf(stderr, (fancy_output) ? "EMPTY" : "No symbols.\n");
            continue;
        }

        size = bfd_get_symtab_upper_bound(b);
        syms = (asymbol **) malloc(size);
        symcnt = bfd_canonicalize_symtab(b, syms);

        for (i = 0; i < symcnt; ++i) {
            if (syms[i]->flags & BSF_FUNCTION) {
                nameptr = (char *)(bfd_asymbol_name(syms[i]));
                if (strip_names!=0) {
                    while (*nameptr == '_') {
                        nameptr++;
                    }
                }
                off = syms[i]->value;
                if (syms[i]->section) {
                    off += syms[i]->section->filepos;
                }

                f = open(argv[optind - 1], O_RDONLY);
                lseek(f, off, SEEK_SET);
                num_funcs++;
                read(f, buf, SIGNATSIZE);
                fingerprint = fnprint_compute(buf);
                close(f);

                // Ignore only NOPs
                if (fingerprint != 0xA120AD5C) {
                    printf("[%s+%d] %s %08X\n", argv[optind - 1], off, nameptr, fingerprint);
                } else {
                    printf("\n");
                }
            }
        }

        if (fancy_output) {
            fprintf(stderr, "%d function%s", num_funcs, PLURAL(num_funcs, "s"));
        } else {
            fprintf(stderr, "[*] %s: (%d function%s)\n", argv[optind - 1], num_funcs, PLURAL(num_funcs, "s"));
        }
    }
    return 0;
}
Exemplo n.º 16
0
void parse_config(const char *conf_file, struct options *opt)
{
	FILE *fh;
	struct buffer line;
	unsigned int lineno = 1;
	int errors = 0;

	/* Journal hasn't been opened yet */
	printf("Reading configuration file at \"%s\"...\n", conf_file);

	if (opt->strict) {
		security_conf_file_check(conf_file);
	}

	fh = fopen(conf_file, "r");
	if (fh == NULL) {
		fprintf(stderr, "Unable to open configuration file \"%s\": %s.\n",
			conf_file, strerror(errno));
		cleanup(EXIT_IO, true);
	}

#if DEBUG
	printf("Raw key/value pairs from config file:\n");
#endif /* DEBUG */

	while (file_read_line(fh, conf_file, &lineno, &line)) {
		struct buffer key, val;
		bool success;
		int ch;

		if (!read_key_and_value(conf_file, lineno, &line, &key, &val)) {
			if (key.length) {
				errors++;
			}

			continue;
		}

		/* Check each possible option */
		if (!strcasecmp(key.data, "Daemonize")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->daemonize = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "TransportProtocol")) {
			if (!strcasecmp(val.data, "tcp")) {
				opt->tproto = PROTOCOL_TCP;
			} else if (!strcasecmp(val.data, "udp")) {
				opt->tproto = PROTOCOL_UDP;
			} else {
				fprintf(stderr, "%s:%d: invalid transport protocol: \"%s\"\n",
					conf_file, lineno, val.data);
				errors++;
			}
		} else if (!strcasecmp(key.data, "InternetProtocol")) {
			if (!strcasecmp(val.data, "both")) {
				opt->iproto = PROTOCOL_BOTH;
			} else if (!strcasecmp(val.data, "ipv4")) {
				opt->iproto = PROTOCOL_IPv4;
			} else if (!strcasecmp(val.data, "ipv6")) {
				opt->iproto = PROTOCOL_IPv6;
			} else {
				fprintf(stderr, "%s:%d: invalid internet protocol: \"%s\"\n",
					conf_file, lineno, val.data);
				errors++;
			}
		} else if (!strcasecmp(key.data, "Port")) {
			/* atoi is ok because it returns 0 in case of failure, and 0 isn't a valid port */
			int port = atoi(val.data);
			if (0 >= port || port > PORT_MAX) {
				fprintf(stderr, "%s:%d: invalid port number: \"%s\"\n",
					conf_file, lineno, val.data);
				errors++;
			} else {
				opt->port = port;
			}
		} else if (!strcasecmp(key.data, "StrictChecking")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->strict = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "DropPrivileges")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->drop_privileges = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "PidFile")) {
			if (!strcmp(val.data, "none")) {
				opt->pid_file = NULL;
				continue;
			}

			opt->pid_file = strdup(val.data);
			if (unlikely(!opt->pid_file)) {
				perror("Unable to allocate memory for config value");
				fclose(fh);
				cleanup(EXIT_MEMORY, true);
			}
		} else if (!strcasecmp(key.data, "RequirePidFile")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->require_pidfile = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "JournalFile")) {
			if (!strcmp(val.data, "-")) {
				opt->journal_file = NULL;
			} else if (strcmp(val.data, "none") != 0) {
				opt->journal_file = strdup(val.data);
				if (unlikely(!opt->journal_file)) {
					perror("Unable to allocate memory for config value");
					fclose(fh);
					cleanup(EXIT_MEMORY, true);
				}
			}
		} else if (!strcasecmp(key.data, "QuotesFile")) {
			opt->quotes_file = strdup(val.data);
			if (unlikely(!opt->quotes_file)) {
				perror("Unable to allocate memory for config value");
				fclose(fh);
				cleanup(EXIT_MEMORY, true);
			}
		} else if (!strcasecmp(key.data, "QuoteDivider")) {
			if (!strcasecmp(val.data, "line")) {
				opt->linediv = DIV_EVERYLINE;
			} else if (!strcasecmp(val.data, "percent")) {
				opt->linediv = DIV_PERCENT;
			} else if (!strcasecmp(val.data, "file")) {
				opt->linediv = DIV_WHOLEFILE;
			} else {
				fprintf(stderr,
					"%s:%d: unsupported division type: \"%s\"\n",
					conf_file, lineno, val.data);
				errors++;
			}
		} else if (!strcasecmp(key.data, "PadQuotes")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->pad_quotes = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "DailyQuotes")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->is_daily = ch;
			} else {
				errors++;
			}
		} else if (!strcasecmp(key.data, "AllowBigQuotes")) {
			ch = str_to_bool(val.data, conf_file, lineno, &success);

			if (likely(success)) {
				opt->allow_big = ch;
			} else {
				errors++;
			}
		} else {
			fprintf(stderr, "%s:%d: unknown conf option: \"%s\"\n",
				conf_file, lineno, key.data);
			errors++;
		}

		lineno++;
	}

	fclose(fh);

	if (opt->strict && errors) {
		fprintf(stderr,
			"Your configuration file has %d issue%s. The daemon will not start.\n"
			"(To disable this behavior, use the --lax flag when running).\n",
			errors, PLURAL(errors));
		cleanup(EXIT_SECURITY, true);
	}
}
Exemplo n.º 17
0
int
chopen(dev_t dev, int flags, int fmt, struct proc *p)
{
	struct ch_softc *sc;
	int oldcounts[4];
	int i, unit, error = 0;

	unit = CHUNIT(dev);
	if ((unit >= ch_cd.cd_ndevs) ||
	    ((sc = ch_cd.cd_devs[unit]) == NULL))
		return (ENXIO);

	/*
	 * Only allow one open at a time.
	 */
	if (sc->sc_link->flags & SDEV_OPEN)
		return (EBUSY);

	sc->sc_link->flags |= SDEV_OPEN;

	/*
	 * Absorb any unit attention errors. We must notice
	 * "Not ready" errors as a changer will report "In the
	 * process of getting ready" any time it must rescan
	 * itself to determine the state of the changer.
	 */
	error = scsi_test_unit_ready(sc->sc_link, TEST_READY_RETRIES,
	    SCSI_IGNORE_ILLEGAL_REQUEST | SCSI_IGNORE_MEDIA_CHANGE);
	if (error)
		goto bad;

	/*
	 * Get information about the device. Save old information
	 * so we can decide whether to be verbose about new parameters.
	 */
	for (i = 0; i < 4; i++) {
		oldcounts[i] = sc->sc_counts[i];
	}
	error = ch_get_params(sc, scsi_autoconf);
	if (error)
		goto bad;

	for (i = 0; i < 4; i++) {
		if (oldcounts[i] != sc->sc_counts[i]) {
			break;
		}
	}
	if (i < 4) {
#ifdef CHANGER_DEBUG
#define PLURAL(c)	(c) == 1 ? "" : "s"
		printf("%s: %d slot%s, %d drive%s, %d picker%s, %d portal%s\n",
		    sc->sc_dev.dv_xname,
		    sc->sc_counts[CHET_ST], PLURAL(sc->sc_counts[CHET_ST]),
		    sc->sc_counts[CHET_DT], PLURAL(sc->sc_counts[CHET_DT]),
		    sc->sc_counts[CHET_MT], PLURAL(sc->sc_counts[CHET_MT]),
		    sc->sc_counts[CHET_IE], PLURAL(sc->sc_counts[CHET_IE]));
#undef PLURAL
		printf("%s: move mask: 0x%x 0x%x 0x%x 0x%x\n",
		    sc->sc_dev.dv_xname,
		    sc->sc_movemask[CHET_MT], sc->sc_movemask[CHET_ST],
		    sc->sc_movemask[CHET_IE], sc->sc_movemask[CHET_DT]);
		printf("%s: exchange mask: 0x%x 0x%x 0x%x 0x%x\n",
		    sc->sc_dev.dv_xname,
		    sc->sc_exchangemask[CHET_MT], sc->sc_exchangemask[CHET_ST],
		    sc->sc_exchangemask[CHET_IE], sc->sc_exchangemask[CHET_DT]);
#endif /* CHANGER_DEBUG */
	}

	/* Default the current picker. */
	sc->sc_picker = sc->sc_firsts[CHET_MT];

	return (0);

 bad:
	sc->sc_link->flags &= ~SDEV_OPEN;
	return (error);
}
Exemplo n.º 18
0
/**
 * Format a section of the monster list: a header followed by monster list
 * entry rows.
 *
 * This function will process each entry for the given section. It will display:
 * - monster char;
 * - number of monsters;
 * - monster name (truncated, if needed to fit the line);
 * - whether or not the monster is asleep (and how many if in a group);
 * - monster distance from the player (aligned to the right side of the list).
 * By passing in a NULL textblock, the maximum line width of the section can be
 * found.
 *
 * \param list is the monster list to format.
 * \param tb is the textblock to produce or NULL if only the dimensions need to
 * be calculated.
 * \param section is the section of the monster list to format.
 * \param lines_to_display are the number of entries to display (not including
 * the header).
 * \param max_width is the maximum line width.
 * \param prefix is the beginning of the header; the remainder is appended with
 * the number of monsters.
 * \param show_others is used to append "other monsters" to the header,
 * after the number of monsters.
 * \param max_width_result is returned with the width needed to format the list
 * without truncation.
 */
static void monster_list_format_section(const monster_list_t *list, textblock *tb, monster_list_section_t section, int lines_to_display, int max_width, const char *prefix, bool show_others, size_t *max_width_result)
{
	int remaining_monster_total = 0;
	int line_count = 0;
	int index;
	int total;
	char line_buffer[200];
	const char *punctuation = (lines_to_display == 0) ? "." : ":";
	const char *others = (show_others) ? "other " : "";
	size_t max_line_length = 0;

	if (list == NULL || list->entries == NULL)
		return;

	total = list->distinct_entries;

	if (list->total_monsters[section] == 0) {
		max_line_length = strnfmt(line_buffer, sizeof(line_buffer),
								  "%s no monsters.\n", prefix);

		if (tb != NULL)
			textblock_append(tb, "%s", line_buffer);

		/* Force a minimum width so that the prompt doesn't get cut off. */
		if (max_width_result != NULL)
			*max_width_result = MAX(max_line_length, 40);

		return;
	}

	max_line_length = strnfmt(line_buffer, sizeof(line_buffer),
							  "%s %d %smonster%s%s\n",
							  prefix,
							  list->total_monsters[section],
							  others,
							  PLURAL(list->total_monsters[section]),
							  punctuation);

	if (tb != NULL)
		textblock_append(tb, "%s", line_buffer);

	for (index = 0; index < total && line_count < lines_to_display; index++) {
		char asleep[20] = { '\0' };
		char location[20] = { '\0' };
		byte line_attr;
		size_t full_width;
		size_t name_width;

		line_buffer[0] = '\0';

		if (list->entries[index].count[section] == 0)
			continue;

		/* Only display directions for the case of a single monster. */
		if (list->entries[index].count[section] == 1) {
			const char *direction1 = (list->entries[index].dy <= 0) ? "N" : "S";
			const char *direction2 = (list->entries[index].dx <= 0) ? "W" : "E";
			strnfmt(location, sizeof(location), " %d %s %d %s",
					abs(list->entries[index].dy), direction1,
					abs(list->entries[index].dx), direction2);
		}

		/* Get width available for monster name and sleep tag: 2 for char and
		 * space; location includes padding; last -1 for some reason? */
		full_width = max_width - 2 - utf8_strlen(location) - 1;

		if (list->entries[index].asleep[section] > 1)
			strnfmt(asleep, sizeof(asleep), " (%d asleep)",
					list->entries[index].asleep[section]);
		else if (list->entries[index].asleep[section] == 1)
			strnfmt(asleep, sizeof(asleep), " (asleep)");

		/* Clip the monster name to fit, and append the sleep tag. */
		name_width = MIN(full_width - utf8_strlen(asleep), sizeof(line_buffer));
		get_mon_name(line_buffer, sizeof(line_buffer),
					 list->entries[index].race,
					 list->entries[index].count[section]);
		utf8_clipto(line_buffer, name_width);
		my_strcat(line_buffer, asleep, sizeof(line_buffer));

		/* Calculate the width of the line for dynamic sizing; use a fixed max
		 * width for location and monster char. */
		max_line_length = MAX(max_line_length,
							  utf8_strlen(line_buffer) + 12 + 2);

		/* textblock_append_pict will safely add the monster symbol,
		 * regardless of ASCII/graphics mode. */
		if (tb != NULL && tile_width == 1 && tile_height == 1) {
			textblock_append_pict(tb, list->entries[index].attr, monster_x_char[list->entries[index].race->ridx]);
			textblock_append(tb, " ");
		}

		/* Add the left-aligned and padded monster name which will align the
		 * location to the right. */
		if (tb != NULL) {
			/* Hack - Because monster race strings are UTF8, we have to add
			 * additional padding for any raw bytes that might be consolidated
			 * into one displayed character. */
			full_width += strlen(line_buffer) - utf8_strlen(line_buffer);
			line_attr = monster_list_entry_line_color(&list->entries[index]);
			textblock_append_c(tb, line_attr, "%-*s%s\n",
							   full_width,
							   line_buffer, location);
		}

		line_count++;
	}

	/* Don't worry about the "...others" line, since it's probably shorter
	 * than what's already printed. */
	if (max_width_result != NULL)
		*max_width_result = max_line_length;

	/* Bail since we don't have enough room to display the remaining count or
	 * since we've displayed them all. */
	if (lines_to_display <= 0 ||
		lines_to_display >= list->total_entries[section])
		return;

	/* Sum the remaining monsters; start where we left off in the above loop. */
	while (index < total) {
		remaining_monster_total += list->entries[index].count[section];
		index++;
	}

	if (tb != NULL)
		textblock_append(tb, "%6s...and %d others.\n", " ",
						 remaining_monster_total);
}
Exemplo n.º 19
0
/**
 * Format a section of the object list: a header followed by object list entry
 * rows.
 *
 * This function will process each entry for the given section. It will display:
 * - object char;
 * - number of objects;
 * - object name (truncated, if needed to fit the line);
 * - object distance from the player (aligned to the right side of the list).
 * By passing in a NULL textblock, the maximum line width of the section can
 * be found.
 *
 * \param list is the object list to format.
 * \param tb is the textblock to produce or NULL if only the dimensions need to
 * be calculated.
 * \param lines_to_display are the number of entries to display (not including
 * the header).
 * \param max_width is the maximum line width.
 * \param prefix is the beginning of the header; the remainder is appended with
 * the number of objects.
 * \param max_width_result is returned with the width needed to format the list
 * without truncation.
 */
static void object_list_format_section(const object_list_t *list,
									   textblock *tb,
									   object_list_section_t section,
									   int lines_to_display, int max_width,
									   const char *prefix, bool show_others,
									   size_t *max_width_result)
{
	int remaining_object_total = 0;
	int line_count = 0;
	int entry_index;
	int total;
	char line_buffer[200];
	const char *punctuation = (lines_to_display == 0) ? "." : ":";
	const char *others = (show_others) ? "other " : "";
	size_t max_line_length = 0;

	if (list == NULL || list->entries == NULL)
		return;

	total = list->distinct_entries;

	if (list->total_entries[section] == 0) {
		max_line_length = strnfmt(line_buffer, sizeof(line_buffer),
								  "%s no objects.\n", prefix);

		if (tb != NULL)
			textblock_append(tb, "%s", line_buffer);

		/* Force a minimum width so that the prompt doesn't get cut off. */
		if (max_width_result != NULL)
			*max_width_result = MAX(max_line_length, 40);

		return;
	}

	max_line_length = strnfmt(line_buffer, sizeof(line_buffer),
							  "%s %d %sobject%s%s\n", prefix,
							  list->total_entries[section], others,
							  PLURAL(list->total_entries[section]),
							  punctuation);

	if (tb != NULL)
		textblock_append(tb, "%s", line_buffer);

	for (entry_index = 0; entry_index < total && line_count < lines_to_display;
		 entry_index++) {
		char location[20] = { '\0' };
		byte line_attr;
		size_t full_width;
		const char *direction_y = (list->entries[entry_index].dy <= 0) ? "N" : "S";
		const char *direction_x = (list->entries[entry_index].dx <= 0) ? "W" : "E";

		line_buffer[0] = '\0';

		if (list->entries[entry_index].count[section] == 0)
			continue;

		/* Build the location string. */
		strnfmt(location, sizeof(location), " %d %s %d %s",
				abs(list->entries[entry_index].dy), direction_y,
				abs(list->entries[entry_index].dx), direction_x);

		/* Get width available for object name: 2 for char and space; location
		 * includes padding; last -1 for some reason? */
		full_width = max_width - 2 - utf8_strlen(location) - 1;

		/* Add the object count and clip the object name to fit. */
		object_list_format_name(&list->entries[entry_index], line_buffer,
								sizeof(line_buffer));
		utf8_clipto(line_buffer, full_width);

		/* Calculate the width of the line for dynamic sizing; use a fixed max
		 * width for location and object char. */
		max_line_length = MAX(max_line_length,
							  utf8_strlen(line_buffer) + 12 + 2);

		/* textblock_append_pict will safely add the object symbol, regardless
		 * of ASCII/graphics mode. */
		if (tb != NULL && tile_width == 1 && tile_height == 1) {
			byte a = COLOUR_RED;
			wchar_t c = L'*';

			if (!is_unknown(list->entries[entry_index].object) &&
				list->entries[entry_index].object->kind != NULL) {
				a = object_kind_attr(list->entries[entry_index].object->kind);
				c = object_kind_char(list->entries[entry_index].object->kind);
			}

			textblock_append_pict(tb, a, c);
			textblock_append(tb, " ");
		}

		/* Add the left-aligned and padded object name which will align the
		 * location to the right. */
		if (tb != NULL) {
			/*
			 * Hack - Because object name strings are UTF8, we have to add
			 * additional padding for any raw bytes that might be consolidated
			 * into one displayed character.
			 */
			full_width += strlen(line_buffer) - utf8_strlen(line_buffer);
			line_attr = object_list_entry_line_attribute(&list->entries[entry_index]);
			textblock_append_c(tb, line_attr, "%-*s%s\n", full_width,
							   line_buffer, location);
		}

		line_count++;
	}

	/* Don't worry about the "...others" line, since it's probably shorter than
	 * what's already printed. */
	if (max_width_result != NULL)
		*max_width_result = max_line_length;

	/* Bail since we don't have enough room to display the remaining count or
	 * since we've displayed them all. */
	if (lines_to_display <= 0 ||
		lines_to_display >= list->total_entries[section])
		return;

	/* Count the remaining objects, starting where we left off in the above
	 * loop. */
	remaining_object_total = total - entry_index;

	if (tb != NULL)
		textblock_append(tb, "%6s...and %d others.\n", " ", remaining_object_total);
}
Exemplo n.º 20
0
// returns true if error
bool CScriptEngine::Execute (DISPID & dispid,  // dispatch ID, will be set to DISPID_UNKNOWN on an error
                              LPCTSTR szProcedure,  // eg. ON_TRIGGER_XYZ
                              const unsigned short iReason,  // value for m_iCurrentActionSource
                              LPCTSTR szType,   // eg. trigger, alias
                              LPCTSTR szReason, // eg. trigger subroutine XXX
                              DISPPARAMS & params,  // parameters
                              long & nInvocationCount,  // count of invocations
                              COleVariant * result    // result of call
                              )
  {


  // If Lua, we may have been called with no arguments, so just do that
  if (L)
    {
    list<double> nparams;
    list<string> sparams;
    bool r;
    bool status = ExecuteLua (dispid, 
                             szProcedure, 
                             iReason,
                             szType, 
                             szReason, 
                             nparams,
                             sparams, 
                             nInvocationCount,
                             NULL, NULL, NULL, &r);


    if (result)
      {
      result->vt = VT_BOOL;
      result->boolVal = r; 
      }
    return status;
    } // have Lua 

  // don't do it if no routine address 
  if (dispid == DISPID_UNKNOWN)
    return false;

  strProcedure = szProcedure;
  strType = szType;
  strReason = szReason;
  bImmediate = false;

  unsigned short iOldStyle = m_pDoc->m_iNoteStyle;
  m_pDoc->m_iNoteStyle = NORMAL;    // back to default style

  HRESULT hr;

  EXCEPINFO ExcepInfo;
  unsigned int ArgErr;
  LARGE_INTEGER start, 
                finish;
  SCRIPTSTATE ss;

  m_pDoc->Trace (TFormat ("Executing %s script \"%s\"", szType, szProcedure));
//  Frame.SetStatusMessageNow (TFormat ("Executing %s subroutine \"%s\"", szType, szProcedure));

  if (m_IActiveScript)
    {
    // new for Python - an error may have caused the script state to change
    hr = m_IActiveScript->GetScriptState (&ss);
  
    if (hr == S_OK)
      {
      // try to put it back to connected
      if (ss != SCRIPTSTATE_CONNECTED)
        hr = m_IActiveScript->SetScriptState (SCRIPTSTATE_CONNECTED);
      }

    if (hr != S_OK)
      {
      ::UMessageBox (TFormat ("Script engine problem invoking subroutine \"%s\" when %s",
                               (LPCTSTR) szProcedure,
                               (LPCTSTR) szReason));
      strProcedure.Empty ();
      strType.Empty ();
      strReason.Empty ();
      bImmediate = true;

      m_pDoc->m_iNoteStyle = iOldStyle;
      return true;
      }
    } // end of having script engine

  if (App.m_iCounterFrequency)
    QueryPerformanceCounter (&start);
  else
    {
    start.QuadPart = 0;
    finish.QuadPart = 0;
    }

  if (iReason != eDontChangeAction)
    m_pDoc->m_iCurrentActionSource = iReason;

  hr = m_pDispatch->Invoke (dispid, IID_NULL, 0, 
                            DISPATCH_METHOD, &params, result, &ExcepInfo, &ArgErr);

  if (iReason != eDontChangeAction)
    m_pDoc->m_iCurrentActionSource = eUnknownActionSource;

  if (hr == S_OK && App.m_iCounterFrequency)
    {
    QueryPerformanceCounter (&finish);
    m_pDoc->m_iScriptTimeTaken += finish.QuadPart - start.QuadPart;
    if (m_pDoc->m_CurrentPlugin)
      m_pDoc->m_CurrentPlugin->m_iScriptTimeTaken += finish.QuadPart - start.QuadPart;
    }

  // put status line back
//  ShowStatusLine ();


  if (hr == S_OK)
    nInvocationCount++;   // count number of times used
  else
    {
    dispid = DISPID_UNKNOWN;   // stop further invocations

    if (hr == 0x800a01c2)   // wrong number of arguments
      ::UMessageBox (TFormat ("Wrong number of arguments for script subroutine \"%s\" when %s"
                                "\n\nWe expected your subroutine to have %i argument%s",
                               (LPCTSTR) szProcedure,
                               (LPCTSTR) szReason,
                               PLURAL (params.cArgs)));
    else
      ::UMessageBox (TFormat ("Unable to invoke script subroutine \"%s\" when %s",
                               (LPCTSTR) szProcedure,
                               (LPCTSTR) szReason));
    }   // end of bad invoke


  strProcedure.Empty ();
  strType.Empty ();
  strReason.Empty ();
  bImmediate = true;

  m_pDoc->m_iNoteStyle = iOldStyle;

  return hr != S_OK;    // true on error

  } // end of CScriptEngine::ExecuteScript
Exemplo n.º 21
0
void CGenPropertyPage::LoadList (void)
  {
  long iCount = 0;
  long iNotShown = 0;

  // for filtering

  CScriptEngine * m_ScriptEngine = NULL;    // for the filtering checks
  bool bFiltering = GetFilterFlag ();

  
  if (bFiltering)
    {
    m_ScriptEngine = new CScriptEngine (m_doc, "Lua");

    if (m_ScriptEngine->CreateScriptEngine ())
      bFiltering = false;
    else
      {

        // compile filter script
       try
         {

          if (m_ScriptEngine->Parse (GetFilterScript (), "Script file"))
            bFiltering = false;

         }  // end of try
       catch (CException * e)
         {
          e->ReportError ();
          e->Delete ();
          bFiltering = false;
         }
      }  // not error creating engine

    }  // end of filtering wanted

  lua_State * L = NULL;

  // if filtering, get the "filter" function on the stack
  if (bFiltering)
    {
    L = m_ScriptEngine->L;   // make copy for convenience

    lua_settop(L, 0);   // clear stack, just in case

    if (!GetNestedFunction (L, "filter", true))
        bFiltering = false;
    }

  // remove all old items (we used the item data to key to the item)

  for (int nItem = 0; nItem < m_ctlList->GetItemCount (); nItem++)
    delete (CString *) m_ctlList->GetItemData (nItem);

   m_ctlList->DeleteAllItems ();
  
   CString strObjectName;
   CObject * pItem;

// Item data

   for (POSITION pos = m_ObjectMap->GetStartPosition (); pos; )
     {
     m_ObjectMap->GetNextAssoc (pos, strObjectName, pItem);
     bool bUse = true;  // defaults to true if no filtering

     if (bFiltering)
       {
       lua_pushvalue(L, 1);        // filter function
       lua_pushstring (L, (const char *) strObjectName);     // key of the item
       GetFilterInfo (pItem, L);   // table of related info
       if (lua_pcall (L, 2, 1, 0))   // call with 1 arg1 and 1 result
         {
         LuaError (L);
         bFiltering = false;
         }
       else
         {
         // use result if we get the exact type: boolean (true/false)
         if (lua_isboolean (L, -1))
           {
           bUse = lua_toboolean (L, -1);
           if (!bUse)
             iNotShown++;  // this one not shown
           }
         lua_pop (L, 1);  // pop result
         }

       }  // end of filtering wanted

     if (bUse)  // add to list if passed filter
       {
       CString * pstrObjectName = new CString (strObjectName);
       add_item (pItem, pstrObjectName, 0, TRUE); 
       iCount++;
       }
     }

  t_gen_sort_param sort_param (m_ObjectMap, m_last_col, m_reverse, m_CompareObjects);

  m_ctlList->SortItems (CompareFunc, (LPARAM) &sort_param); 

// set the 1st item to be selected - we do this here because sorting the
// list means our first item is not necessarily the 1st item in the list

 if (!m_ObjectMap->IsEmpty ())    // provided we have any
   m_ctlList->SetItemState (0, LVIS_FOCUSED | LVIS_SELECTED, 
                               LVIS_FOCUSED | LVIS_SELECTED);

  CString strSummary = TFormat ("%i item%s.", PLURAL (iCount));

  if (iNotShown)
    strSummary += TFormat (" (%i item%s hidden by filter)", PLURAL (iNotShown));
  m_ctlSummary->SetWindowText (strSummary);

  delete m_ScriptEngine;

  }  // end of CGenPropertyPage::LoadList
Exemplo n.º 22
0
void CGenPropertyPage::OnDeleteItem() 
{

CUIntArray arySelected;
int iCount =  m_ctlList->GetSelectedCount ();
int nItem,
    i,
    iIncluded = 0,
    iExecuting = 0;

  arySelected.SetSize (iCount);

  // first, remember selected items
for (nItem = -1, i = 0;
      (nItem = m_ctlList->GetNextItem(nItem, LVNI_SELECTED)) != -1;)
       arySelected [i++] = nItem;

if (iCount == 0)
  return;

if (App.m_bTriggerRemoveCheck)
  {
  // mucking around to make it plural properly
  CString sName =  m_strObjectType;
  if (iCount > 1)
    if (sName == "alias")
      sName += "es";
    else
      sName += "s";

  if (::UMessageBox (TFormat ("Delete %i %s - are you sure?",
      iCount, sName), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2)
      != IDYES )
      return;
  } // end of wanting to confirm

// we do it this way because deleting items buggers up the position in the array
for (i = iCount - 1; i >= 0; i--)
  {
  nItem = arySelected [i];

  // get the lower-case name of this item's object
  CString * pstrObjectName = (CString *) m_ctlList->GetItemData (nItem);
  ASSERT (pstrObjectName != NULL);

  CObject * pItem;

  // see if in the map
  if (!m_ObjectMap->Lookup (*pstrObjectName, pItem))
    continue;   // already deleted!

  ASSERT_VALID (pItem);
  ASSERT( pItem->IsKindOf( RUNTIME_CLASS( CObject ) ) );

  if (CheckIfIncluded (pItem))
    {
    iIncluded++;    // don't do message here in case hundreds of them
    continue;
    }

  if (CheckIfExecuting (pItem))
    {
    iExecuting++;    // don't do message here in case hundreds of them
    continue;
    }

  // They can no longer cancel the property sheet, the document has changed
  CancelToClose ();
  if (!CheckIfTemporary (pItem))
    m_doc->SetModifiedFlag (TRUE);

  // delete from the map
  m_ObjectMap->RemoveKey (*pstrObjectName);

  // delete the item itself
  delete pItem;
  
  // and remove from the dialog list control
  m_ctlList->DeleteItem (nItem);

  // delete its item string
  delete pstrObjectName;

  }   // end of dealing with each selected item

  if (iIncluded)
    {
    CString strMsg;
    strMsg = TFormat ("%i item%s %s included from an include file. You cannot delete %s here.",
                   PLURAL (iIncluded),
                   iIncluded == 1 ? "was" : "were",
                   iIncluded == 1 ? "it" : "them");
      ::UMessageBox (strMsg);
    }

  if (iExecuting)
    {
    CString strMsg;
    strMsg = TFormat ("%i item%s %s currently executing a script. You cannot delete %s now.",
                   PLURAL (iExecuting),
                   iExecuting == 1 ? "is" : "are",
                   iExecuting == 1 ? "it" : "them");
      ::UMessageBox (strMsg);
    }

}   // end of CGenPropertyPage::OnDeleteItem
Exemplo n.º 23
0
void nglContextInfo::Dump(uint Level) const
{
  const nglChar* human_readable[5] = { _T("none"), _T("single"), _T("double"), _T("triple"), _T(">3 (waw!)") };
  uint fbcount = (FrameCnt <= 4) ? FrameCnt : 4;

  NGL_LOG(_T("context"), Level, _T("GL Context description :"));
  NGL_LOG(_T("context"), Level, _T("  Frame buffer : %s"), human_readable[fbcount]);
  NGL_LOG(_T("context"), Level, _T("  Frame bits   : %d:%d:%d:%d\n"), FrameBitsR, FrameBitsG, FrameBitsB, FrameBitsA);
  NGL_LOG(_T("context"), Level, _T("  Depth bits   : %d\n"), DepthBits);
  NGL_LOG(_T("context"), Level, _T("  Stencil bits : %d\n"), StencilBits);
  NGL_LOG(_T("context"), Level, _T("  Accum bits   : %d:%d:%d:%d\n"), AccumBitsR, AccumBitsG, AccumBitsB, AccumBitsA);
  NGL_LOG(_T("context"), Level, _T("  Aux buffer   : %d\n"), AuxCnt);
  NGL_LOG(_T("context"), Level, _T("  Multisample  : %d buffer%s, %d sample%s\n"), AABufferCnt, PLURAL(AABufferCnt), AASampleCnt, PLURAL(AASampleCnt));
  NGL_LOG(_T("context"), Level, _T("  Stereo       : %s\n"), YESNO(Stereo));
  NGL_LOG(_T("context"), Level, _T("  Offscreen    : %s\n"), YESNO(Offscreen));
  NGL_LOG(_T("context"), Level, _T("  Copy On Swap : %s\n"), YESNO(CopyOnSwap));
  NGL_LOG(_T("context"), Level, _T("  Vertical Sync: %s\n"), YESNO(VerticalSync));
  NGL_LOG(_T("context"), Level, _T("  CopyOnSwap  : %s\n"), YESNO(CopyOnSwap));
  NGL_LOG(_T("context"), Level, _T("  VerticalSync: %s\n"), YESNO(VerticalSync));
}
Exemplo n.º 24
0
static void
chattach(device_t parent, device_t self, void *aux)
{
	struct ch_softc *sc = device_private(self);
	struct scsipibus_attach_args *sa = aux;
	struct scsipi_periph *periph = sa->sa_periph;

	sc->sc_dev = self;
	selinit(&sc->sc_selq);

	/* Glue into the SCSI bus */
	sc->sc_periph = periph;
	periph->periph_dev = sc->sc_dev;
	periph->periph_switch = &ch_switch;

	printf("\n");

	/*
	 * Find out our device's quirks.
	 */
	ch_get_quirks(sc, &sa->sa_inqbuf);

	/*
	 * Some changers require a long time to settle out, to do
	 * tape inventory, for instance.
	 */
	if (sc->sc_settledelay) {
		printf("%s: waiting %d seconds for changer to settle...\n",
		    device_xname(sc->sc_dev), sc->sc_settledelay);
		delay(1000000 * sc->sc_settledelay);
	}

	/*
	 * Get information about the device.  Note we can't use
	 * interrupts yet.
	 */
	if (ch_get_params(sc, XS_CTL_DISCOVERY|XS_CTL_IGNORE_MEDIA_CHANGE))
		printf("%s: offline\n", device_xname(sc->sc_dev));
	else {
#define PLURAL(c)	(c) == 1 ? "" : "s"
		printf("%s: %d slot%s, %d drive%s, %d picker%s, %d portal%s\n",
		    device_xname(sc->sc_dev),
		    sc->sc_counts[CHET_ST], PLURAL(sc->sc_counts[CHET_ST]),
		    sc->sc_counts[CHET_DT], PLURAL(sc->sc_counts[CHET_DT]),
		    sc->sc_counts[CHET_MT], PLURAL(sc->sc_counts[CHET_MT]),
		    sc->sc_counts[CHET_IE], PLURAL(sc->sc_counts[CHET_IE]));
#undef PLURAL
#ifdef CHANGER_DEBUG
		printf("%s: move mask: 0x%x 0x%x 0x%x 0x%x\n",
		    device_xname(sc->sc_dev),
		    sc->sc_movemask[CHET_MT], sc->sc_movemask[CHET_ST],
		    sc->sc_movemask[CHET_IE], sc->sc_movemask[CHET_DT]);
		printf("%s: exchange mask: 0x%x 0x%x 0x%x 0x%x\n",
		    device_xname(sc->sc_dev),
		    sc->sc_exchangemask[CHET_MT], sc->sc_exchangemask[CHET_ST],
		    sc->sc_exchangemask[CHET_IE], sc->sc_exchangemask[CHET_DT]);
#endif /* CHANGER_DEBUG */
	}

	/* Default the current picker. */
	sc->sc_picker = sc->sc_firsts[CHET_MT];
}
Exemplo n.º 25
0
// Hook designed to insert the name of the dragged file into the edit control
LRESULT CALLBACK TftpClientFileNameProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
char szFileName [MAX_PATH];
static HANDLE hDrop;
static int    nAmount, Ark; 

    switch (message)
   {
      case WM_TIMER :
                // is previous transfer terminated
             if (WaitForSingleObject (hTftpClientSemaphore, 0) == WAIT_OBJECT_0)
                {       
                   if (! sTC.bBreak && ++Ark<nAmount)
                 {
                      DragQueryFile (hDrop, Ark, szFileName, MAX_PATH-1);
                        SetWindowText (hWnd, szFileName);
                      // ignore directories (wait for next turn)
                     if ( (GetFileAttributes (szFileName) & FILE_ATTRIBUTE_DIRECTORY) == 0)
                            SendMessage (hTftpClientWnd, WM_COMMAND, IDC_CLIENT_SEND_BUTTON, 0);
                        else   ReleaseSemaphore (hTftpClientSemaphore, 1, NULL);
                   }
                  else    // mutiple transfer either stopped or finished
                 {
                      DragFinish (hDrop);
                        KillTimer (hWnd, wParam);
                      CMsgBox (hWnd, "%d file%s fully transferred in %d block%s and %d retransmission%s", "Tftpd32", MB_OK, 
                              sTC.dwMultiFile, PLURAL(sTC.dwMultiFile),
                              sTC.dwMultiFileBlk, PLURAL(sTC.dwMultiFileBlk), 
                               sTC.nTotRetrans, PLURAL(sTC.nTotRetrans)); 
                       sTC.bBreak = sTC.bMultiFile = FALSE;
                       sTC.nTotRetrans = sTC.dwMultiFileBlk = sTC.dwMultiFile = 0 ; 
                      ReleaseSemaphore (hTftpClientSemaphore, 1, NULL);
                      break;
                 }
              }
              break;


       case WM_DROPFILES :
            hDrop = (HANDLE) wParam;
           nAmount = DragQueryFile (hDrop, -1, szFileName, MAX_PATH);
         // multi files mode : only if field Host has been filled
           if (   nAmount>=2 
             && GetDlgItemText (GetParent (hWnd), IDC_CLIENT_HOST, sTC.szHost, sizeof sTC.szHost) > 0)
          {
              if (CMsgBox (hWnd, 
                         "Upload (Put) %d files to host ?", 
                        "Tftpd32", 
                         MB_ICONQUESTION | MB_YESNOCANCEL,
                          nAmount)==IDYES)
             {
                      sTC.bMultiFile = TRUE;
                     sTC.dwMultiFileBlk=sTC.dwMultiFile=0 ; 
                        Ark=-1 ;

                      if (SetTimer (hWnd, ID_CLIENT_TRANSFER, 1000, NULL)==0)
                                CMsgBox (hWnd, "Create timer failed", "Tftpd32", MB_OK);

              } // User do not cancel MessageBox warning
         } // multi files have been dropped
         else
           {
              // only one file selected : just put its name into control 
                DragQueryFile (hDrop, 0, szFileName, MAX_PATH);
                SetWindowText (hWnd, szFileName);
              DragFinish (hDrop);
            }
          break;
     default : break;
           
   }
return CallWindowProc (fEditBoxProc, hWnd, message, wParam, lParam);
} // TftpClientFileNameProc
void sing(int bottles) {
  printf("%d green %s, standing on the wall.\n", bottles, PLURAL(bottles));
}
Exemplo n.º 27
0
static size_t obj_desc_charges(const object_type *o_ptr, char *buf, size_t max, size_t end)
{
	object_kind *k_ptr = &k_info[o_ptr->k_idx];

	bool aware = object_flavor_is_aware(o_ptr) || (o_ptr->ident & IDENT_STORE);

	/* See if the object is "known" */
	bool known = (object_known_p(o_ptr) ? TRUE : FALSE);

	/* Wands and Staffs have charges */
	if (aware && known && (o_ptr->tval == TV_STAFF || o_ptr->tval == TV_WAND))
		strnfcat(buf, max, &end, " (%d charge%s)", o_ptr->pval, PLURAL(o_ptr->pval));

	/* Charging things */
	else if (o_ptr->timeout > 0)
	{
		/* Hack -- Rods have a "charging" indicator */
		if (known && (o_ptr->tval == TV_ROD))
		{
			/* Hack -- Dump " (# charging)" if relevant */
			if (o_ptr->timeout >= 1)
			{

				/* Stacks of rods display an exact count of charging rods. */
				if (o_ptr->number > 1)
				{
					int power;

					/* Paranoia. */
					if (k_ptr->pval == 0) k_ptr->pval = 1;

					/* Find out how many rods are charging, by dividing
				 	 * current timeout by each rod's maximum timeout.
				 	 * Ensure that any remainder is rounded up.  Display
				 	 * very discharged stacks as merely fully discharged.
				 	 */
					power = (o_ptr->timeout + (k_ptr->pval - 1)) / k_ptr->pval;

					if (power > o_ptr->number) power = o_ptr->number;

					/* Display prettily */
					strnfcat(buf, max, &end, " (%d charging)", power);
				}


				/* Display prettily */
				else strnfcat(buf, max, &end, " (charging)");
			}
		}


		/* Indicate "charging" objects, but not rods or lites */
		if (known && o_ptr->timeout && o_ptr->tval != TV_ROD
			    && !fuelable_lite_p(o_ptr))
		{

			/* Hack -- Dump " (charging)" if relevant */
			strnfcat(buf, max, &end, " (charging)");
		}
	}

	return end;
}
Exemplo n.º 28
0
void CWorldSocket::OnClose(int nErrorCode)
  {

bool bWasClosed = m_pDoc->m_iConnectPhase == eConnectNotConnected;

  TRACE1 ("CWorldSocket::OnClose, error code %i\n", nErrorCode);

  m_pDoc->m_iConnectPhase = eConnectDisconnecting;

  m_pDoc->UpdateAllViews (NULL);

  m_pDoc->MXP_Off (true);   // turn off MXP now

  // update button bar - make button red
  if (m_pDoc->m_view_number >= 1 &&
      m_pDoc->m_view_number <= 10)
    Frame.OnUpdateBtnWorlds (m_pDoc->m_view_number, NULL);

  // execute "disconnect" script
  if (m_pDoc->m_ScriptEngine)
    {
    if (m_pDoc->SeeIfHandlerCanExecute (m_pDoc->m_strWorldDisconnect))
      {
      DISPPARAMS params = { NULL, NULL, 0, 0 };
      long nInvocationCount = 0;

      m_pDoc->ExecuteScript (m_pDoc->m_dispidWorldDisconnect,  
                             m_pDoc->m_strWorldDisconnect,
                             eWorldAction,
                             "world disconnect", 
                             "disconnecting from world",
                             params, 
                             nInvocationCount); 
      }
    } // end of executing disconnect script

  m_pDoc->SendToAllPluginCallbacks (ON_PLUGIN_DISCONNECT);

  // close log file if we auto-opened it
  if (!m_pDoc->m_strAutoLogFileName.IsEmpty ())
    m_pDoc->CloseLog ();

  if (m_pDoc->m_bShowConnectDisconnect && !bWasClosed)
    {
    CTime theTime;
    theTime = CTime::GetCurrentTime();

    CString strConnected;
    strConnected = theTime.Format (TranslateTime ("--- Disconnected on %A, %B %d, %Y, %#I:%M %p ---"));

    m_pDoc->Note (strConnected);  

    // find time spent connected
    CTimeSpan ts = CTime::GetCurrentTime() - m_pDoc->m_tConnectTime;
      
    CString strDuration = TFormat ("--- Connected for %i day%s, %i hour%s, %i minute%s, %i second%s. ---",
                  PLURAL ((long) ts.GetDays()),
                  PLURAL ((long) ts.GetHours()),
                  PLURAL ((long) ts.GetMinutes()),
                  PLURAL ((long) ts.GetSeconds()));

    m_pDoc->Note (strDuration);  

    // and a horizontal rule

    m_pDoc->m_pCurrentLine->flags = HORIZ_RULE;  
    m_pDoc->StartNewLine (true, 0); 
    }  // end of message in world window wanted

  CString strInfo = TFormat ("--- Received %i line%s, sent %i line%s.",
                PLURAL (m_pDoc->m_nTotalLinesReceived),
                PLURAL (m_pDoc->m_nTotalLinesSent)
                );
  
  m_pDoc->Note (strInfo);  

  strInfo = TFormat ("--- Output buffer has %i/%i line%s in it (%.1f%% full).",
                m_pDoc->m_LineList.GetCount (),
                m_pDoc->m_maxlines,
                (m_pDoc->m_LineList.GetCount ()) == 1 ? "" : "s",
                (double) m_pDoc->m_LineList.GetCount () / (double) m_pDoc->m_maxlines * 100.0
                );

  m_pDoc->Note (strInfo);  

  strInfo = TFormat ("--- Matched %i trigger%s, %i alias%s, and %i timer%s fired.",
                PLURAL (m_pDoc->m_iTriggersMatchedThisSessionCount),   
                PLURALES (m_pDoc->m_iAliasesMatchedThisSessionCount),    
                PLURAL (m_pDoc->m_iTimersFiredThisSessionCount)       
                );

  m_pDoc->Note (strInfo);  

CString str;

  str = TFormat ("The \"%s\" server has closed the connection", 
              (const char *) m_pDoc->m_mush_name);

  if (App.m_bNotifyOnDisconnect && !m_pDoc->m_bDisconnectOK)
    {
    if (App.m_bErrorNotificationToOutputWindow)
      m_pDoc->Note (str);
    else
      ::UMessageBox (str, MB_ICONEXCLAMATION);
    }
  else
    Frame.SetStatusMessage (str);
  m_pDoc->m_iConnectPhase = eConnectNotConnected;

  m_pDoc->UpdateAllViews  (NULL);     // force window title to be redrawn

  } // end of OnClose