static CSSParserToken dimension(NumericValueType type, double value, const String& string)
{
    CSSParserToken token = number(type, value, NoSign); // sign ignored
    token.convertToDimensionWithUnit(toParserString(string));
    return token;
}
Пример #2
0
void
cmd_users(int argc, char *argv[])
{
	Uid *ui;
	int u, g, o, line;
	char *file, *p, *uname, *ulead, *unext;

	file = "/adm/users";
	if(argc > 1)
		file = argv[1];

	if(strcmp(file, "default") == 0) {
		setminusers();
		return;
	}

	uidgc.uidbuf = getbuf(devnone, Cuidbuf, 0);
	if(walkto(file) || con_open(FID2, 0)) {
		print("cmd_users: cannot access %s\n", file);
		putbuf(uidgc.uidbuf);
		return;
	}

	uidgc.flen = 0;
	uidgc.find = 0;
	cons.offset = 0;
	cons.nuid = 0;

	u = 0;
	line = 0;
	while(readln(buf, sizeof buf) != 0) {
		line++;
		p = getword(buf, L':', "no : after number", line);
		if(p == nil)
			continue;
		ulead = getword(p, L':', "no : after name", line);
		if(ulead == nil)
			continue;

		if(strlen(p) > NAMELEN-1) {
			print("%s: name too long\n", p);
			continue;
		}
		strcpy(uid[u].name, p);
		uid[u].uid = number(buf, 0, 10);
		uid[u].lead = 0;
		uid[u].ngrp = 0;
		u++;
		if(u >= conf.nuid) {
			print("conf.nuid too small (%ld)\n", conf.nuid);
			break;
		}
	}

	/* Sorted by uid for use in uidtostr */
	wlock(&uidgc.uidlock);
	qsort(uid, u, sizeof(uid[0]), byuid);
	cons.nuid = u;
	wunlock(&uidgc.uidlock);

	/* Parse group table */
	uidgc.flen = 0;
	uidgc.find = 0;
	cons.offset = 0;
	cons.ngid = 0;

	g = 0;
	line = 0;
	while(readln(buf, sizeof buf) != 0) {
		line++;
		uname = getword(buf, L':', 0, 0);	/* skip number */
		if(uname == nil)
			continue;

		ulead = getword(uname, L':', 0, 0);	/* skip name */
		if(ulead == nil)
			continue;

		p = getword(ulead, L':', "no : after leader", line);
		if(p == nil)
			continue;

		ui = uidpstr(uname);
		if(ui == nil)
			continue;

		/* set to owner if name not known */
		ui->lead = 0;
		if(ulead[0]) {
			o = strtouid(ulead);
			if(o >= 0)
				ui->lead = o;
			else
				ui->lead = ui->uid;
		}
		ui->gtab = &gidspace[g];
		ui->ngrp = 0;
		while (p != nil) {
			unext = getword(p, L',', 0, 0);
			o = strtouid(p);
			if(o >= 0) {
				gidspace[g++] = o;
				ui->ngrp++;
			}
			p = unext;
		}
	}

	cons.ngid = g;

	putbuf(uidgc.uidbuf);
	print("%d uids read, %d groups used\n", cons.nuid, cons.ngid);
}
Пример #3
0
/*
 * Returns an sql query to fetch contact item IDs for all the contact items which may contain
 * the specified telephone number in a telephone, fax or SMS type field.
 *
 * This is improved version of createMatchPhoneNumberQuery method.
 * The number is compared starting from the right side of the number and 
 * the method returns an array of candidate matches.  
 * Punctuation (e.g. spaces) and other alphabetic characters are ignored
 * when comparing. Leading zeros are removed. Digits are compared up to 
 * the length of shorter number.
 */
void CntFilterDetail::bestMatchPhoneNumberQuery(const QContactFilter& filter,
                                                QString& sqlQuery,
                                                QContactManager::Error* error)
    {
    if (!filterSupported(filter) ) {
          *error = QContactManager::NotSupportedError;
          return;
        }
              
    QContactDetailFilter detailFilter(filter);
    QString number((detailFilter.value()).toString());
    TPtrC numberPtr(reinterpret_cast<const TUint16*>(number.utf16()));
    
    const TInt KUpperMaxLength = KMaxPhoneMatchLength - KLowerSevenDigits;
    TMatch phoneDigits = createPaddedPhoneDigits(numberPtr, KLowerSevenDigits, KUpperMaxLength, error);
    
    if (*error == QContactManager::NoError) {
        // select fields for contacts that match phone lookup
        //  SELECT contact_id, extra_value FROM comm_addr
        //      WHERE value = [value string] AND type = [type value];
        //
        QString type =  QString(" type = %1").arg(CntDbInfo::EPhoneNumber);
        QString value =  QString(" value = %1").arg(phoneDigits.iLowerSevenDigits);
        QString whereClause = " WHERE" + value + " AND" + type;
        sqlQuery = "SELECT contact_id, extra_value FROM comm_addr" + whereClause;
        
        QList<QPair<QContactLocalId, QString> > contactMatches =  m_srvConnection.searchPhoneNumbers(sqlQuery, error);
        
        // Check if search query was successful
        if (*error != QContactManager::NoError) {
              return;
            }
        
        QStringList list;
        for (int i=0; i<contactMatches.count(); ++i) {
            // Check the upper digits...
            TInt32 number = phoneDigits.iUpperDigits;
            QString extraValue = contactMatches.at(i).second;
            TPtrC extValString(reinterpret_cast<const TUint16*>(extraValue.utf16()));
            
            TInt32 storedUpperDigits(0);
            if (TLex(extValString).Val(storedUpperDigits) == KErrNone) {
                
                TInt32 stored = storedUpperDigits;
                TBool nonZeroInStoredFound = EFalse;
                TBool nonZeroInNumberFound = EFalse;
                while ((number != 0) && (stored != 0)) {
                    nonZeroInNumberFound |= (number % 10 != 0);
                    nonZeroInStoredFound |= (stored % 10 != 0);
                    if (nonZeroInStoredFound && nonZeroInNumberFound) {
                        break;
                    }
                    number /= 10;
                    stored /= 10;
                }
                
                if ((phoneDigits.iUpperDigits == 0) || (storedUpperDigits == 0) ||
                     (number == stored)) {
                    list.append(QString("%1").arg(contactMatches.at(i).first));
                }
            }
            else {
                *error = QContactManager::UnspecifiedError;
                return;
            }
        }
        // Recreate query to fetch all match ids
        // SELECT DISTINCT contact_id FROM contact WHERE contact_id in (
        //      ..
        // )  
        QString ids = list.join(" ,");
        sqlQuery = "SELECT DISTINCT contact_id FROM contact WHERE contact_id in (";
        sqlQuery += ids;
        sqlQuery += ')';
        }
    }
Пример #4
0
static int
validate_beg(Cx_t* cx, Cxexpr_t* expr, void* data, Cxdisc_t* disc)
{
	char**			argv = (char**)data;
	int			errors = error_info.errors;
	char*			s;
	State_t*		state;
	Cxvariable_t*		variable;
	register Field_t*	field;
	Field_t*		lastfield;
	Cxconstraint_t*		constraint;
	int			all;
	int			list;
	Vmalloc_t*		vm;

	if (!(vm = vmopen(Vmdcheap, Vmlast, 0)) || !(state = vmnewof(vm, 0, State_t, 1, 0)))
	{
		if (vm)
			vmclose(vm);
		if (disc->errorf)
			(*disc->errorf)(NiL, disc, ERROR_SYSTEM|2, "out of space");
		return -1;
	}
	state->vm = vm;
	list = 0;
	sfprintf(cx->buf, "%s%s", strchr(dss_lib_validate.description, '['), validate_usage);
	s = sfstruse(cx->buf);
	for (;;)
	{
		switch (optget(argv, s))
		{
		case 'd':
			state->discard = 1;
			continue;
		case 'l':
			list = 1;
			continue;
		case 'r':
			if (!(state->setf = cxcallout(cx, CX_SET, cx->state->type_void, cx->state->type_void, cx->disc)))
			{
				if (cx->disc->errorf)
					(*cx->disc->errorf)(NiL, cx->disc, 3, "reair requires CX_SET callout");
				return -1;
			}
			continue;
		case 's':
			state->summary = 1;
			continue;
		case 'v':
			state->summary = state->verbose = 1;
			continue;
		case '?':
			if (disc->errorf)
				(*disc->errorf)(NiL, disc, ERROR_USAGE|4, "%s", opt_info.arg);
			else
				return -1;
			continue;
		case ':':
			if (disc->errorf)
				(*disc->errorf)(NiL, disc, 2, "%s", opt_info.arg);
			else
				return -1;
			continue;
		}
		break;
	}
	if (error_info.errors > errors)
		goto bad;
	argv += opt_info.index;
	if (all = !*argv)
		variable = 0;
	do
	{
		if (all)
		{
			if (!(variable = (Cxvariable_t*)(variable ? dtnext(cx->fields, variable) : dtfirst(cx->fields))))
				break;
		}
		else if (!(variable = cxvariable(cx, *argv, NiL, disc)))
			goto bad;
		if (variable->format.constraint || variable->format.map)
		{
			if (!(field = vmnewof(vm, 0, Field_t, 1, 0)))
			{
				if (disc->errorf)
					(*disc->errorf)(NiL, disc, ERROR_SYSTEM|2, "out of space");
				goto bad;
			}
			field->variable = variable;
			if (state->field)
				lastfield = lastfield->next = field;
			else
				lastfield = state->field = field;
		}
	} while (all || *++argv);
	if (!state->field && disc->errorf)
		(*disc->errorf)(NiL, disc, 1, "no field has constraints or maps");
	if (list)
	{
		for (field = state->field; field; field = field->next)
		{
			sfprintf(expr->op, "%16s", field->variable->name);
			if (field->variable->format.map)
				sfprintf(expr->op, " map");
			if (constraint = field->variable->format.constraint)
			{
				if (constraint->name)
					sfprintf(expr->op, " name=%s", constraint->name);
				if (constraint->constraintf)
					sfprintf(expr->op, " external");
				if (cxisnumber(field->variable->type))
				{
					if (constraint->def)
						number(expr->op, "default", constraint->def->number, &field->variable->format);
					if (constraint->min)
						number(expr->op, "min", constraint->min->number, &field->variable->format);
					if (constraint->max)
						number(expr->op, "max", constraint->max->number, &field->variable->format);
				}
				else if (cxisstring(field->variable->type) && constraint->def)
					sfprintf(expr->op, " default=\"%-.*s\"", constraint->def->string.size, constraint->def->string.data);
				if (constraint->expression)
					sfprintf(expr->op, " expression=\"%s\"", constraint->expression);
				if (constraint->pattern)
					sfprintf(expr->op, " pattern=\"%s\"", constraint->pattern);
			}
			sfprintf(expr->op, "\n");
		}
		goto bad;
	}
	if (!(state->getf = cxcallout(cx, CX_GET, cx->state->type_void, cx->state->type_void, cx->disc)))
	{
		if (cx->disc->errorf)
			(*cx->disc->errorf)(NiL, cx->disc, 3, "validation requires CX_GET callout");
		goto bad;
	}
	if (!state->verbose)
	{
		state->invaliddisc.comparf = invalidcmp;
		if (!(state->invalid = dtnew(vm, &state->invaliddisc, Dtoset)))
		{
			if (cx->disc->errorf)
				(*cx->disc->errorf)(NiL, cx->disc, 3, "validation requires CX_GET callout");
			goto bad;
		}
	}
	expr->data = state;
	return 0;
 bad:
	vmclose(vm);
	return -1;
}
Пример #5
0
 bool operator<(const RuleID & x) const {
   return number() < x.number();
 };
Пример #6
0
/*
 * Bulk transfer routine --
 *  used by getfl(), cu_take(), and pipefile()
 */
void
transfer(char *buf, int fd, char *eofchars)
{
	int ct;
	char c, buffer[BUFSIZ];
	char *p = buffer;	/* can't be register because of longjmp */
	int cnt, eof, bol;
	time_t start;
	sig_handler_t	f;

	parwrite(FD, (unsigned char *)buf, strlen(buf));
	(void) kill(pid, SIGIOT);
	/* Wait until read process stops */
	(void) read(repdes[0], (char *)&ccc, 1);

	/*
	 * finish command
	 */
	parwrite(FD, (unsigned char *)"\r", 1);
	do
		(void) read(FD, &c, 1);
	while ((c&0177) != '\n')
		;

	if (sigsetjmp(intbuf, 1))
		goto out;
	f = signal(SIGINT, (sig_handler_t)intcopy);
	intr("on");

	start = time(0);
	bol = 1;
	ct = 0;
	for (;;) {
		eof = read(FD, &c, 1) <= 0;
		if (noparity)
			c &= 0377;
		else
			c &= 0177;
		if (eof || (bol && any(c, eofchars)))
			break;
		if (c == 0)
			continue;	/* ignore nulls */
		if (c == '\r')
			continue;
		*p++ = c;

		if (c == '\n') {
			bol = 1;
			if (boolean(value(VERBOSE)))
				(void) printf("\r%d", ++ct);
		} else
			bol = 0;
		if ((cnt = (p-buffer)) == number(value(FRAMESIZE))) {
			if (write(fd, buffer, cnt) != cnt) {
				(void) printf("\r\nwrite error\r\n");
				goto out;
			}
			p = buffer;
		}
	}
out:
	if ((cnt = (p-buffer)) != 0)
		if (write(fd, buffer, cnt) != cnt)
			(void) printf("\r\nwrite error\r\n");

	if (boolean(value(VERBOSE)))
		prtime(" lines transferred in ", time(0)-start);
	intr("off");
	(void) write(fildes[1], (char *)&ccc, 1);
	(void) signal(SIGINT, f);
	(void) close(fd);
}
Пример #7
0
static void
push_arg(dbref player, struct frame *fr, const char *arg)
{
    int num, lflag, sflag = 0;
    float inum;

    if (fr->argument.top >= STACK_SIZE) {
	anotify_nolisten(player, CFAIL "That would overflow the stack.", 1);
	return;
    }
    if (number(arg)) {
	/* push a number */
	num = atoi(arg);
	push(fr->argument.st, &fr->argument.top, PROG_INTEGER, MIPSCAST &num);
	anotify_nolisten(player, CSUCC "Integer pushed.", 1);
    } else if (ifloat(arg)) {
	/* push a float */
	inum = (float) atof(arg);
	push(fr->argument.st, &fr->argument.top, PROG_FLOAT, MIPSCAST & inum);
	notify_nolisten(player, "Float pushed.", 1);
    } else if (*arg == '#') {
	/* push a dbref */
	if (!number(arg+1)) {
	    anotify_nolisten(player, CINFO "I don't understand that dbref.", 1);
	    return;
	}
	num = atoi(arg+1);
	push(fr->argument.st, &fr->argument.top, PROG_OBJECT, MIPSCAST &num);
	anotify_nolisten(player, CSUCC "Dbref pushed.", 1);
    } else if (*arg == 'L' || *arg == 'V' || *arg == 'l' || *arg == 'v') {
	if (*arg == 'S' || *arg == 's') {
	    arg++;
	    sflag = 1;
	} else if (*arg == 'L' || *arg == 'l') {
	    arg++;
	    lflag = 1;
      }
	if (*arg == 'V' || *arg == 'v')
	    arg++;
	if (!number(arg)) {
	    anotify_nolisten(player, CINFO "I don't understand which variable you mean.", 1);
	    return;
	}
	num = atoi(arg);
	if (lflag) {
	    push(fr->argument.st, &fr->argument.top, PROG_LVAR, MIPSCAST &num);
	    anotify_nolisten(player, CSUCC "Local variable pushed.", 1);
	} else if (sflag) {
	    push(fr->argument.st, &fr->argument.top, PROG_SVAR, MIPSCAST & num);
	    notify_nolisten(player, "Scoped variable pushed.", 1);
	} else {
	    push(fr->argument.st, &fr->argument.top, PROG_VAR, MIPSCAST &num);
	    anotify_nolisten(player, CSUCC "Global variable pushed.", 1);
	}
    } else if (*arg == '"') {
	/* push a string */
	char buf[BUFFER_LEN];
	char *ptr;
	const char *ptr2;

	for (ptr = buf, ptr2 = arg+1; *ptr2; ptr2++) {
	    if (*ptr2 == '\\') {
		if (!*(++ptr2)) break;
		*ptr++ = *ptr2;
	    } else if (*ptr2 == '"') {
		break;
	    } else {
		*ptr++ = *ptr2;
	    }
	}
	*ptr = '\0';
	push(fr->argument.st, &fr->argument.top, PROG_STRING,
		MIPSCAST alloc_prog_string(buf));
	anotify_nolisten(player, CSUCC "String pushed.", 1);
    } else {
	anotify_nolisten(player, CINFO "I don't know that data type.", 1);
    }
}
Пример #8
0
SynPacket::~SynPacket()
{
    if ((m_client->getListVer() != m_ver) && bDone) {
        if (m_data) {
            Contact *contact;
            if (m_client->findContact(m_data->EMail.ptr, contact)) {
                Event e(EventContactChanged, contact);
                e.process();
            }
        }
        m_client->setListVer(m_ver);
        ContactList::GroupIterator itg;
        Group *grp;
        list<Group*>	grpRemove;
        list<Contact*>	contactRemove;
        while ((grp = ++itg) != NULL) {
            ClientDataIterator it(grp->clientData, m_client);
            MSNUserData *data = (MSNUserData*)(++it);
            if (grp->id() && (data == NULL)) {
                MSNListRequest lr;
                lr.Type = LR_GROUPxCHANGED;
                lr.Name = number(grp->id());
                m_client->m_requests.push_back(lr);
                continue;
            }
            if (data == NULL)
                continue;
            if ((data->sFlags.value & MSN_CHECKED) == 0)
                grpRemove.push_back(grp);
        }
        Contact *contact;
        ContactList::ContactIterator itc;
        while ((contact = ++itc) != NULL) {
            MSNUserData *data;
            ClientDataIterator it(contact->clientData, m_client);
            list<void*> forRemove;
            while ((data = (MSNUserData*)(++it)) != NULL) {
                if (data->sFlags.value & MSN_CHECKED) {
                    if ((data->sFlags.value & MSN_REVERSE) && ((data->Flags.value & MSN_REVERSE) == 0))
                        m_client->auth_message(contact, MessageRemoved, data);
                } else {
                    forRemove.push_back(data);
                }
            }
            if (forRemove.empty())
                continue;
            for (list<void*>::iterator itr = forRemove.begin(); itr != forRemove.end(); ++itr)
                contact->clientData.freeData(*itr);
            if (contact->clientData.size() == 0)
                contactRemove.push_back(contact);
        }
        for (list<Contact*>::iterator rc = contactRemove.begin(); rc != contactRemove.end(); ++rc)
            delete *rc;
        for (list<Group*>::iterator rg = grpRemove.begin(); rg != grpRemove.end(); ++rg)
            delete *rg;
    }
    if (m_client->getState() == Client::Connecting) {
        m_client->setState(Client::Connected);
        m_client->processRequests();
    }
}
Пример #9
0
RmgPacket::RmgPacket(MSNClient *client, unsigned id)
    : MSNPacket(client, "RMG")
{
    addArg(number(id).c_str());
}
Пример #10
0
void show_char_to_char(struct char_data *i, struct char_data *ch, int mode)
{
    char buffer[MAX_STRING_LENGTH];
    int j, found, percent;
    struct obj_data *tmp_obj;

    if (mode == 0) {

        if (IS_AFFECTED(i, AFF_HIDE) || !CAN_SEE(ch,i)) {
            if (IS_AFFECTED(ch, AFF_SENSE_LIFE))
                send_to_char("You sense a hidden life form in the room.\n\r", ch);
            return;
        }

        if (!(i->player.long_descr)||(GET_POS(i) != i->specials.default_pos)) {
            /* A player char or a mobile without long descr, or not in default pos. */
            if (!IS_NPC(i)) {
                strcpy(buffer,GET_NAME(i));
                strcat(buffer," ");
                strcat(buffer,GET_TITLE(i));
            } else {
                strcpy(buffer, i->player.short_descr);
                CAP(buffer);
            }

            if ( IS_AFFECTED(i,AFF_INVISIBLE))
                strcat(buffer," (invisible)");

            switch(GET_POS(i)) {
            case POSITION_STUNNED  :
                strcat(buffer," is lying here, stunned.");
                break;
            case POSITION_INCAP    :
                strcat(buffer," is lying here, incapacitated.");
                break;
            case POSITION_MORTALLYW:
                strcat(buffer," is lying here, mortally wounded.");
                break;
            case POSITION_DEAD     :
                strcat(buffer," is lying here, dead.");
                break;
            case POSITION_STANDING :
                strcat(buffer," is standing here.");
                break;
            case POSITION_SITTING  :
                strcat(buffer," is sitting here.");
                break;
            case POSITION_RESTING  :
                strcat(buffer," is resting here.");
                break;
            case POSITION_SLEEPING :
                strcat(buffer," is sleeping here.");
                break;
            case POSITION_FIGHTING :
                if (i->specials.fighting) {

                    strcat(buffer," is here, fighting ");
                    if (i->specials.fighting == ch)
                        strcat(buffer," YOU!");
                    else {
                        if (i->in_room == i->specials.fighting->in_room)
                            if (IS_NPC(i->specials.fighting))
                                strcat(buffer, i->specials.fighting->player.short_descr);
                            else
                                strcat(buffer, GET_NAME(i->specials.fighting));
                        else
                            strcat(buffer, "someone who has already left.");
                    }
                } else /* NIL fighting pointer */
                    strcat(buffer," is here struggling with thin air.");
                break;
            default :
                strcat(buffer," is floating here.");
                break;
            }
            if (IS_AFFECTED(ch, AFF_DETECT_EVIL)) {
                if (IS_EVIL(i))
                    strcat(buffer, " (Red Aura)");
            }

            strcat(buffer,"\n\r");
            send_to_char(buffer, ch);
        }
        else  /* npc with long */
        {
            if (IS_AFFECTED(i,AFF_INVISIBLE))
                strcpy(buffer,"*");
            else
                *buffer = '\0';

            if (IS_AFFECTED(ch, AFF_DETECT_EVIL)) {
                if (IS_EVIL(i))
                    strcat(buffer, " (Red Aura)");
            }

            strcat(buffer, i->player.long_descr);

            send_to_char(buffer, ch);
        }

        if (IS_AFFECTED(i,AFF_SANCTUARY))
            act("$n glows with a bright light!", FALSE, i, 0, ch, TO_VICT);

    } else if (mode == 1) {

        if (i->player.description)
            send_to_char(i->player.description, ch);
        else {
            act("You see nothing special about $m.", FALSE, i, 0, ch, TO_VICT);
        }

        /* Show a character to another */

        if (GET_MAX_HIT(i) > 0)
            percent = (100*GET_HIT(i))/GET_MAX_HIT(i);
        else
            percent = -1; /* How could MAX_HIT be < 1?? */

        if (IS_NPC(i))
            strcpy(buffer, i->player.short_descr);
        else
            strcpy(buffer, GET_NAME(i));

        if (percent >= 100)
            strcat(buffer, " is in an excellent condition.\n\r");
        else if (percent >= 90)
            strcat(buffer, " has a few scratches.\n\r");
        else if (percent >= 75)
            strcat(buffer, " has some small wounds and bruises.\n\r");
        else if (percent >= 50)
            strcat(buffer, " has quite a few wounds.\n\r");
        else if (percent >= 30)
            strcat(buffer, " has some big nasty wounds and scratches.\n\r");
        else if (percent >= 15)
            strcat(buffer, " looks pretty hurt.\n\r");
        else if (percent >= 0)
            strcat(buffer, " is in an awful condition.\n\r");
        else
            strcat(buffer, " is bleeding awfully from big wounds.\n\r");

        send_to_char(buffer, ch);

        found = FALSE;
        for (j=0; j< MAX_WEAR; j++) {
            if (i->equipment[j]) {
                if (CAN_SEE_OBJ(ch,i->equipment[j])) {
                    found = TRUE;
                }
            }
        }
        if (found) {
            act("\n\r$n is using:", FALSE, i, 0, ch, TO_VICT);
            for (j=0; j< MAX_WEAR; j++) {
                if (i->equipment[j]) {
                    if (CAN_SEE_OBJ(ch,i->equipment[j])) {
                        send_to_char(where[j],ch);
                        show_obj_to_char(i->equipment[j],ch,1);
                    }
                }
            }
        }
        if ((GET_CLASS(ch) == CLASS_THIEF) && (ch != i)) {
            found = FALSE;
            send_to_char("\n\rYou attempt to peek at the inventory:\n\r", ch);
            for(tmp_obj = i->carrying; tmp_obj; tmp_obj = tmp_obj->next_content) {
                if (CAN_SEE_OBJ(ch, tmp_obj) && (number(0,20) < GET_LEVEL(ch))) {
                    show_obj_to_char(tmp_obj, ch, 1);
                    found = TRUE;
                }
            }
            if (!found)
                send_to_char("You can't see anything.\n\r", ch);
        }

    } else if (mode == 2) {

        /* Lists inventory */
        act("$n is carrying:", FALSE, i, 0, ch, TO_VICT);
        list_obj_to_char(i->carrying,ch,1,TRUE);
    }
}
Пример #11
0
bool DSManager::PutAttributes(LPITEM pDS)
{
	if (!pDS->IsDragonSoul())
	{
		sys_err ("This item(ID : %d) is not DragonSoul.", pDS->GetID());
		return false;
	}

	BYTE ds_type, grade_idx, step_idx, strength_idx;
	GetDragonSoulInfo(pDS->GetVnum(), ds_type, grade_idx, step_idx, strength_idx);

	DragonSoulTable::TVecApplys vec_basic_applys;
	DragonSoulTable::TVecApplys vec_addtional_applys;

	if (!m_pTable->GetBasicApplys(ds_type, vec_basic_applys))
	{
		sys_err ("There is no BasicApply about %d type dragon soul.", ds_type);
		return false;
	}
	if (!m_pTable->GetAdditionalApplys(ds_type, vec_addtional_applys))
	{
		sys_err ("There is no AdditionalApply about %d type dragon soul.", ds_type);
		return false;
	}

	
	int basic_apply_num, add_min, add_max;
	if (!m_pTable->GetApplyNumSettings(ds_type, grade_idx, basic_apply_num, add_min, add_max))
	{
		sys_err ("In ApplyNumSettings, INVALID VALUES Group type(%d), GRADE idx(%d)", ds_type, grade_idx);
		return false;
	}

	float fWeight = 0.f;
	if (!m_pTable->GetWeight(ds_type, grade_idx, step_idx, strength_idx, fWeight))
	{
		return false;
	}
	fWeight /= 100.f;

	int n = MIN(basic_apply_num, vec_basic_applys.size());
	for (int i = 0; i < n; i++)
	{	
		const SApply& basic_apply = vec_basic_applys[i];
		BYTE bType = basic_apply.apply_type;
		short sValue = (short)(ceil((float)basic_apply.apply_value * fWeight - 0.01f));

		pDS->SetForceAttribute(i, bType, sValue);
	}

	BYTE additional_attr_num = MIN(number (add_min, add_max), 3);

	std::vector <int> random_set;
	if (additional_attr_num > 0)
	{
		random_set.resize(additional_attr_num);
		std::list <float> list_probs;
		for (int i = 0; i < vec_addtional_applys.size(); i++)
		{
			list_probs.push_back(vec_addtional_applys[i].prob);
		}
		if (!MakeDistinctRandomNumberSet(list_probs, random_set))
		{
			sys_err ("MakeDistinctRandomNumberSet error.");
			return false;
		}

		for (int i = 0; i < additional_attr_num; i++)
		{
			int r = random_set[i];
			const SApply& additional_attr = vec_addtional_applys[r];
			BYTE bType = additional_attr.apply_type;
			short sValue = (short)(ceil((float)additional_attr.apply_value * fWeight - 0.01f));

			pDS->SetForceAttribute(DRAGON_SOUL_ADDITIONAL_ATTR_START_IDX + i, bType, sValue);
		}
	}

	return true;
}
Пример #12
0
static void
parse_level_string(const char *str, char **return_ptr)
{
     static char text[MAXLEVELINDENT];
     char *p;
     int i, c, num;
    
     p = text;
     memset(text, ' ', sizeof(text));
     text[sizeof(text)-1] = 0;
     
     while (*str) {
	  switch (*str) {
	  case '\\':
	       switch (*++str) {
	       case 'a':
		    *p++ = '\a';
		    break;
	       case 'b':
		    *p++ = '\b';
		    break;
	       case 'e':
		    *p++ = '\033';
		    break;
	       case 'f':
		    *p++ = '\f';
		    break;
	       case 'n':
		    *p++ = '\n';
		    break;
	       case 'r':
		    *p++ = '\r';
		    break;
	       case 't':
		    *p++ = '\t';
		    break;
	       case 'x':
	       case 'X':
		    ++str;
		    *p++ = number(&str,16,2);
		    break;
	       case '0':
		    ++str;
		    *p++ = number(&str,8,3);
		    break;
	       default:
		    *p++ = *str;
	       }
	       ++str;
	       break;
	  case 'x':
	       if (p == text) {
		    goto copy;
	       }
	       num = strtol(str+1, (char**)&str, 10);
	       c = p[-1];
	       for (i = 1; i < num; i++) {
		    *p++ = c;
		    if (*p == 0)
			 error(EX_USAGE, 0,
			       _("level indent string is too long"));
	       }
	       break;
	  default:
	  copy:
	       *p++ = *str++;
	       if (*p == 0)
		    error(EX_USAGE, 0, _("level indent string is too long"));
	  }
     }
     *p = 0;
     *return_ptr = strdup(text);
}
TEST(CSSTokenizerTest, NumberToken)
{
    TEST_TOKENS("10", number(IntegerValueType, 10, NoSign));
    TEST_TOKENS("12.0", number(NumberValueType, 12, NoSign));
    TEST_TOKENS("+45.6", number(NumberValueType, 45.6, PlusSign));
    TEST_TOKENS("-7", number(IntegerValueType, -7, MinusSign));
    TEST_TOKENS("010", number(IntegerValueType, 10, NoSign));
    TEST_TOKENS("10e0", number(NumberValueType, 10, NoSign));
    TEST_TOKENS("12e3", number(NumberValueType, 12000, NoSign));
    TEST_TOKENS("3e+1", number(NumberValueType, 30, NoSign));
    TEST_TOKENS("12E-1", number(NumberValueType, 1.2, NoSign));
    TEST_TOKENS(".7", number(NumberValueType, 0.7, NoSign));
    TEST_TOKENS("-.3", number(NumberValueType, -0.3, MinusSign));
    TEST_TOKENS("+637.54e-2", number(NumberValueType, 6.3754, PlusSign));
    TEST_TOKENS("-12.34E+2", number(NumberValueType, -1234, MinusSign));

    TEST_TOKENS("+ 5", delim('+'), whitespace(), number(IntegerValueType, 5, NoSign));
    TEST_TOKENS("-+12", delim('-'), number(IntegerValueType, 12, PlusSign));
    TEST_TOKENS("+-21", delim('+'), number(IntegerValueType, -21, MinusSign));
    TEST_TOKENS("++22", delim('+'), number(IntegerValueType, 22, PlusSign));
    TEST_TOKENS("13.", number(IntegerValueType, 13, NoSign), delim('.'));
    TEST_TOKENS("1.e2", number(IntegerValueType, 1, NoSign), delim('.'), ident("e2"));
    TEST_TOKENS("2e3.5", number(NumberValueType, 2000, NoSign), number(NumberValueType, 0.5, NoSign));
    TEST_TOKENS("2e3.", number(NumberValueType, 2000, NoSign), delim('.'));
    TEST_TOKENS("1000000000000000000000000", number(IntegerValueType, 1e24, NoSign));
}
static CSSParserToken percentage(NumericValueType type, double value)
{
    CSSParserToken token = number(type, value, NoSign); // sign ignored
    token.convertToPercentage();
    return token;
}
Пример #15
0
/* toss $n $dice $table for $face */
void
char__do_toss (CHAR_DATA * ch, char *argument, int cmd)
{
    register short int nArg = 0;
    register short int nDiceArg = 0;
    register short int nTableArg = 0;
    register short int nFaceArg = 0;
    register short int nFacet = 0;
    register short int nMaxFacet = 0;
    size_t nIndex = 0;
    register int nCount = 0;

    char *p = NULL;
    char buf[AVG_STRING_LENGTH * 10] = "";
    char arg[5][AVG_STRING_LENGTH / 5] = { "", "", "", "", "" };
    char key[AVG_STRING_LENGTH] = "";
    char strFacet[AVG_STRING_LENGTH] = "";
    char strFacetList[AVG_STRING_LENGTH] = "";
    OBJ_DATA *dice = NULL;
    OBJ_DATA *table = NULL;

    nArg =
        sscanf (argument, "%s %s %s %s %s", arg[0], arg[1], arg[2], arg[3],
                arg[4]);

    if (nArg <= 0)
    {
        send_to_char ("Toss what?\n", ch);
        return;
    }

    nCount = strtol (arg[0], &p, 10);
    if (errno == ERANGE || nCount == 0 || strlen (p) != 0)
    {
        nCount = 0;
    }
    else
    {
        nDiceArg = 1;
    }

    switch (nArg - nDiceArg)
    {
    case 3:
        nFaceArg = (strcmp ("for", arg[nDiceArg + 1]) == 0) ? nDiceArg + 2 : -1;
        break;
    case 4:
        nFaceArg = (strcmp ("for", arg[nDiceArg + 2]) == 0) ? nDiceArg + 3 : -1;	/* NO BREAK HERE goes to next case */
    case 2:
        nTableArg = nDiceArg + 1;
        break;
    default:
        break;
    }

    if (nFaceArg < 0)
    {
        send_to_char ("Toss them how?\n", ch);
        return;
    }

    if (!(dice = get_obj_in_dark (ch, arg[nDiceArg], ch->right_hand)) &&
            !(dice = get_obj_in_dark (ch, arg[nDiceArg], ch->left_hand)))
    {
        sprintf (buf, "You don't have a '%s'.\n", arg[nDiceArg]);
        send_to_char (buf, ch);
        return;
    }
    if (dice->obj_flags.type_flag != ITEM_TOSSABLE
            && dice->obj_flags.type_flag != ITEM_MONEY)
    {
        send_to_char ("Did you mean to #6throw#0 that object?\n", ch);
        return;
    }

    if (dice->count > 12 && (nCount == 0 || nCount > 12))
    {
        send_to_char ("You can't toss that many at once.\n", ch);
        return;
    }

    if (nTableArg && arg[nTableArg][0] &&
            (!(table = get_obj_in_list_vis (ch, arg[nTableArg], ch->room->contents))
             || !IS_TABLE(table)))
    {
        sprintf (buf, "You don't see any furniture like '%s'.\n",
                 arg[nTableArg]);
        send_to_char (buf, ch);
        return;
    }

    obj_from_char (&dice, nCount);

    if (dice->obj_flags.type_flag == ITEM_MONEY)
    {
        strcpy (key, " obverse reverse ");
        nMaxFacet = 2;
    }
    else if (dice->desc_keys)
    {
        sprintf (key, " %s ", dice->desc_keys);
    }
    else
    {
        strcpy (key,
                " one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty ");
    }

    if (nFaceArg && dice->o.od.value[1])
    {
        /*
           nFacet = strtol(arg[nFaceArg],&p,10);
           if ( errno == ERANGE || nFacet == 0 || strlen(p) != 0 ) {
           strcpy(strFacet,strstr(key,arg[nFaceArg]));
           if () {
           }
           else {
           nFacet = 0;
           }
           }
           else {
           }
         */

    }
    nMaxFacet = (nMaxFacet) ? nMaxFacet : dice->o.od.value[0];
    for (nCount = 0; nCount < dice->count; nCount++)
    {

        nFacet = number (1, nMaxFacet);

        for (nIndex = 0; nIndex < strlen (key); nIndex++)
        {
            if (key[nIndex] == ' ' && --nFacet <= 0)
                break;
        }

        sscanf (key + nIndex + 1, "%s %s", strFacet, buf);
        sprintf (strFacetList + strlen (strFacetList), "#6%s%s#0%s",
                 (nMaxFacet == 2) ? "the " : "a ", strFacet,
                 (nCount ==
                  dice->count - 2) ? " and " : ((nCount !=
                                                dice->count - 1) ? ", " : ""));
    }

    sprintf (buf, "You toss $p onto %s%s%s%s. The upright face%s show%s: %s.\n",
             (nTableArg) ? "$P" : "the ground",
             (nFaceArg) ? ", trying for #6a " : "",
             (nFaceArg) ? arg[nFaceArg] : "", (nFaceArg) ? "#0" : "",
             (nCount > 1) ? "s" : "", (nCount > 1) ? "" : "s", strFacetList);
    act (buf, true, ch, dice, table, TO_CHAR | _ACT_FORMAT);

    sprintf (buf, "$n tosses $p onto %s. The upright face%s show%s: %s.\n",
             (nTableArg) ? "$P" : "the ground", (nCount > 1) ? "s" : "",
             (nCount > 1) ? "" : "s", strFacetList);
    act (buf, true, ch, dice, table, TO_ROOM | _ACT_FORMAT);

    if (nTableArg)
    {
        obj_to_obj (dice, table);
    }
    else
    {
        obj_to_room (dice, ch->in_room);
    }
}
Пример #16
0
    string BSONElement::jsonString( JsonStringFormat format, bool includeFieldNames, int pretty ) const {
        BSONType t = type();
        if ( t == Undefined )
            return "";

        stringstream s;
        if ( includeFieldNames )
            s << '"' << escape( fieldName() ) << "\" : ";
        switch ( type() ) {
        case mongo::String:
        case Symbol:
            s << '"' << escape( valuestr() ) << '"';
            break;
        case NumberLong:
            s << _numberLong();
            break;
        case NumberInt:
        case NumberDouble:
            if ( number() >= -numeric_limits< double >::max() &&
                    number() <= numeric_limits< double >::max() ) {
                s.precision( 16 );
                s << number();
            } else {
                stringstream ss;
                ss << "Number " << number() << " cannot be represented in JSON";
                string message = ss.str();
                massert( 10311 ,  message.c_str(), false );
            }
            break;
        case mongo::Bool:
            s << ( boolean() ? "true" : "false" );
            break;
        case jstNULL:
            s << "null";
            break;
        case Object:
            s << embeddedObject().jsonString( format, pretty );
            break;
        case mongo::Array: {
            if ( embeddedObject().isEmpty() ) {
                s << "[]";
                break;
            }
            s << "[ ";
            BSONObjIterator i( embeddedObject() );
            BSONElement e = i.next();
            if ( !e.eoo() )
                while ( 1 ) {
                    if( pretty ) {
                        s << '\n';
                        for( int x = 0; x < pretty; x++ )
                            s << "  ";
                    }
                    s << e.jsonString( format, false, pretty?pretty+1:0 );
                    e = i.next();
                    if ( e.eoo() )
                        break;
                    s << ", ";
                }
            s << " ]";
            break;
        }
        case DBRef: {
            mongo::OID *x = (mongo::OID *) (valuestr() + valuestrsize());
            if ( format == TenGen )
                s << "Dbref( ";
            else
                s << "{ \"$ref\" : ";
            s << '"' << valuestr() << "\", ";
            if ( format != TenGen )
                s << "\"$id\" : ";
            s << '"' << *x << "\" ";
            if ( format == TenGen )
                s << ')';
            else
                s << '}';
            break;
        }
        case jstOID:
            if ( format == TenGen ) {
                s << "ObjectId( ";
            } else {
                s << "{ \"$oid\" : ";
            }
            s << '"' << __oid() << '"';
            if ( format == TenGen ) {
                s << " )";
            } else {
                s << " }";
            }
            break;
        case BinData: {
            int len = *(int *)( value() );
            BinDataType type = BinDataType( *(char *)( (int *)( value() ) + 1 ) );
            s << "{ \"$binary\" : \"";
            char *start = ( char * )( value() ) + sizeof( int ) + 1;
            base64::encode( s , start , len );
            s << "\", \"$type\" : \"" << hex;
            s.width( 2 );
            s.fill( '0' );
            s << type << dec;
            s << "\" }";
            break;
        }
        case mongo::Date:
            if ( format == Strict )
                s << "{ \"$date\" : ";
            else
                s << "Date( ";
            if( pretty ) {
                Date_t d = date();
                if( d == 0 ) s << '0';
                else
                    s << '"' << date().toString() << '"';
            } else
                s << date();
            if ( format == Strict )
                s << " }";
            else
                s << " )";
            break;
        case RegEx:
            if ( format == Strict ){
                s << "{ \"$regex\" : \"" << escape( regex() );
                s << "\", \"$options\" : \"" << regexFlags() << "\" }";
            } else {
                s << "/" << escape( regex() , true ) << "/";
                // FIXME Worry about alpha order?
                for ( const char *f = regexFlags(); *f; ++f ){
                    switch ( *f ) {
                    case 'g':
                    case 'i':
                    case 'm':
                        s << *f;
                    default:
                        break;
                    }
                }
            }
            break;

        case CodeWScope: {
            BSONObj scope = codeWScopeObject();
            if ( ! scope.isEmpty() ){
                s << "{ \"$code\" : " << _asCode() << " , "
                  << " \"$scope\" : " << scope.jsonString() << " }";
                break;
            }
        }


        case Code:
            s << _asCode();
            break;
            
        case Timestamp:
            s << "{ \"t\" : " << timestampTime() << " , \"i\" : " << timestampInc() << " }";
            break;

        case MinKey:
            s << "{ \"$minKey\" : 1 }";
            break;

        case MaxKey:
            s << "{ \"$maxKey\" : 1 }";
            break;

        default:
            stringstream ss;
            ss << "Cannot create a properly formatted JSON string with "
            << "element: " << toString() << " of type: " << type();
            string message = ss.str();
            massert( 10312 ,  message.c_str(), false );
        }
        return s.str();
    }
Пример #17
0
/***********************************************************************//**
 * @brief Print event cube information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing event cube information.
 ***************************************************************************/
std::string GLATEventCube::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GLATEventCube ===");

        // Append information
        result.append("\n"+gammalib::parformat("Number of elements") +
                      gammalib::str(size()));
        result.append("\n"+gammalib::parformat("Number of pixels"));
        result.append(gammalib::str(m_map.nx()) +
                      " x " +
                      gammalib::str(m_map.ny()));
        result.append("\n"+gammalib::parformat("Number of energy bins") +
                      gammalib::str(ebins()));
        result.append("\n"+gammalib::parformat("Number of events") +
                      gammalib::str(number()));

        // Append time interval
        result.append("\n"+gammalib::parformat("Time interval"));
        if (gti().size() > 0) {
            result.append(gammalib::str(tstart().secs()) +
                          " - " +
                          gammalib::str(tstop().secs())+" sec");
        }
        else {
            result.append("not defined");
        }

        // Append energy range
        result.append("\n"+gammalib::parformat("Energy range"));
        if (ebounds().size() > 0) {
            result.append(emin().print()+" - "+emax().print(chatter));
        }
        else {
            result.append("not defined");
        }

        // Append sky projection
        if (m_map.projection() != NULL) {
            result.append("\n"+m_map.projection()->print(chatter));
        }

        // Append source maps
        result.append("\n"+gammalib::parformat("Number of source maps"));
        result.append(gammalib::str(m_srcmap.size()));
        for (int i = 0; i < m_srcmap.size(); ++i) {
            result.append("\n"+gammalib::parformat(" "+m_srcmap_names[i]));
            result.append(gammalib::str(m_srcmap[i]->nx()));
            result.append(" x ");
            result.append(gammalib::str(m_srcmap[i]->ny()));
            result.append(" x ");
            result.append(gammalib::str(m_srcmap[i]->nmaps()));
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Пример #18
0
Youtube::operator bool() const {
    DB::Result r = DB::query("SELECT 1 FROM youtube_refresh_tokens WHERE user_id = " + number(_uid) + " LIMIT 1");
    return r.size() > 0;
}
Пример #19
0
/*
 * Bulk transfer routine to remote host --
 *   used by tip_sendfile() and cu_put()
 */
void
transmit(FILE *fd, char *eofchars, char *command)
{
	sig_handler_t	ointr;
	char *pc, lastc, rc;
	int c, ccount, lcount;
	time_t start_t, stop_t;

	(void) kill(pid, SIGIOT);	/* put TIPOUT into a wait state */
	timedout = 0;
	if (sigsetjmp(intbuf, 1)) {
		if (timedout)
			(void) printf("\r\ntimed out at eol\r\n");
		(void) alarm(0);
		goto out;
	}
	ointr = signal(SIGINT, (sig_handler_t)intcopy);
	intr("on");
	(void) read(repdes[0], (char *)&ccc, 1);
	if (command != NULL) {
		for (pc = command; *pc; pc++)
			send(*pc);
		if (boolean(value(ECHOCHECK)))
			(void) read(FD, (char *)&c, 1);	/* trailing \n */
		else {
			struct termios buf;
			/* wait for remote stty to take effect */
			(void) sleep(5);
			/* this does a */
			(void) ioctl(FD, TCGETS, (char *)&buf);
			/* wflushtty */
			(void) ioctl(FD, TCSETSF, (char *)&buf);
		}
	}
	lcount = 0;
	lastc = '\0';
	start_t = time(0);
	if (boolean(value(RAWFTP))) {
		while ((c = getc(fd)) != EOF) {
			lcount++;
			send(c);
			if (boolean(value(VERBOSE)) && lcount%100 == 0)
				(void) printf("\r%d", lcount);
		}
		if (boolean(value(VERBOSE)))
			(void) printf("\r%d", lcount);
		goto out;
	}
	for (;;) {
		ccount = 0;
		do {
			c = getc(fd);
			if (c == EOF)
				goto out;
			if (c == 0177)
				continue;
			lastc = c;
			if (c < 040) {
				if (c == '\n') {
					c = '\r';
				} else if (c == '\t') {
					if (boolean(value(TABEXPAND))) {
						send(' ');
						while ((++ccount % 8) != 0)
							send(' ');
						continue;
					}
				} else
					continue;
			}
			send(c);
		} while (c != '\r');
		if (boolean(value(VERBOSE)))
			(void) printf("\r%d", ++lcount);
		if (boolean(value(ECHOCHECK))) {
			(void) alarm(number(value(ETIMEOUT)));
			do {	/* wait for prompt */
				(void) read(FD, &rc, 1);
			} while ((rc&0177) != character(value(PROMPT)));
			(void) alarm(0);
		}
	}
out:
	if (lastc != '\n' && !boolean(value(RAWFTP)))
		send('\r');
	if (eofchars)
		for (pc = eofchars; *pc; pc++)
			send(*pc);
	stop_t = time(0);
	(void) fclose(fd);
	if (boolean(value(VERBOSE)))
		if (boolean(value(RAWFTP)))
			prtime(" chars transferred in ", stop_t-start_t);
		else
			prtime(" lines transferred in ", stop_t-start_t);
	(void) write(fildes[1], (char *)&ccc, 1);
	intr("off");
	(void) signal(SIGINT, ointr);
}
Пример #20
0
void Youtube::unlink() {
    DB::query("DELETE FROM youtube_refresh_tokens WHERE user_id = " + number(_uid));
}
Пример #21
0
int
muf_debugger(int descr, dbref player, dbref program, const char *text, struct frame *fr)
{
    char cmd[BUFFER_LEN];
    char buf[BUFFER_LEN];
    char buf2[BUFFER_LEN];
    char *ptr, *ptr2, *arg;
    struct inst *pinst;
    dbref ref;
    int i, j, cnt;

    while (isspace(*text)) text++;
    strcpy(cmd, text);
    ptr = cmd + strlen(cmd);
    if (ptr > cmd) ptr--;
    while (ptr >= cmd && isspace(*ptr)) *ptr-- = '\0';
    for (arg = cmd; *arg && !isspace(*arg); arg++);
    if (*arg) *arg++ = '\0';
    if (!*cmd && fr->brkpt.lastcmd) {
        strcpy(cmd, fr->brkpt.lastcmd);
    } else {
        if (fr->brkpt.lastcmd)
            free(fr->brkpt.lastcmd);
        if (*cmd)
            fr->brkpt.lastcmd = string_dup(cmd);
    }
    /* delete triggering breakpoint, if it's only temp. */
    j = fr->brkpt.breaknum;
    if (j >= 0 && fr->brkpt.temp[j]) {
        for (j++; j < fr->brkpt.count; j++) {
            fr->brkpt.temp[j-1]         = fr->brkpt.temp[j];
            fr->brkpt.level[j-1]        = fr->brkpt.level[j];
            fr->brkpt.line[j-1]         = fr->brkpt.line[j];
            fr->brkpt.linecount[j-1]    = fr->brkpt.linecount[j];
            fr->brkpt.pc[j-1]           = fr->brkpt.pc[j];
            fr->brkpt.pccount[j-1]      = fr->brkpt.pccount[j];
            fr->brkpt.prog[j-1]         = fr->brkpt.prog[j];
        }
	fr->brkpt.count--;
    }
    fr->brkpt.breaknum = -1;
    
    if (!string_compare(cmd, "cont")) {
    } else if (!string_compare(cmd, "finish")) {
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot finish because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = fr->system.top - 1;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = program;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "stepi")) {
        i = atoi(arg);
        if (!i) i = 1;
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot stepi because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = -1;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = i;
        fr->brkpt.prog[j] = NOTHING;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "step")) {
        i = atoi(arg);
        if (!i) i = 1;
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot step because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = -1;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = i;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = NOTHING;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "nexti")) {
        i = atoi(arg);
        if (!i) i = 1;
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot nexti because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = fr->system.top;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = i;
        fr->brkpt.prog[j] = program;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "next")) {
        i = atoi(arg);
        if (!i) i = 1;
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot next because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = fr->system.top;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = i;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = program;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "exec")) {
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot finish because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
	if (!(pinst = funcname_to_pc(program, arg))) {
	    anotify_nolisten(player, CINFO "I don't know a function by that name.", 1);
            add_muf_read_event(descr, player, program, fr);
	    return 0;
	}
	if (fr->system.top >= STACK_SIZE) {
	    anotify_nolisten(player, CFAIL "That would exceed the system stack size for this program.", 1);
            add_muf_read_event(descr, player, program, fr);
	    return 0;
	}
	fr->system.st[fr->system.top].progref = program;
	fr->system.st[fr->system.top++].offset = fr->pc;
	fr->pc = pinst;
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = fr->system.top - 1;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = program;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "prim")) {
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Cannot finish because there are too many breakpoints set.", 1);
            add_muf_read_event(descr, player, program, fr);
            return 0;
        }
	if (!(i = primitive(arg))) {
	    anotify_nolisten(player, CINFO "I don't recognize that primitive.", 1);
            add_muf_read_event(descr, player, program, fr);
	    return 0;
	}
	if (fr->system.top >= STACK_SIZE) {
	    anotify_nolisten(player, CFAIL "That would exceed the system stack size for this program.", 1);
            add_muf_read_event(descr, player, program, fr);
	    return 0;
	}

	shstr.data[0] = '\0';
	shstr.links = 1;
	shstr.length= strlen(shstr.data);
	primset[0].type = PROG_FUNCTION;
	primset[0].line = 0;
	primset[0].data.string = &shstr;
	primset[1].type = PROG_DECLVAR;
	primset[1].line = 0;
	primset[1].data.number = 0;
	primset[1].type = PROG_PRIMITIVE;
	primset[1].line = 0;
	primset[1].data.number = /* i */ get_primitive(arg);
	primset[2].type = PROG_PRIMITIVE;
	primset[2].line = 0;
	primset[2].data.number = primitive("EXIT");

	fr->system.st[fr->system.top].progref = program;
	fr->system.st[fr->system.top++].offset = fr->pc;
	fr->pc = primset;
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 1;
        fr->brkpt.level[j] = fr->system.top - 1;
        fr->brkpt.line[j] = -1;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = program;
        fr->brkpt.bypass = 1;
        return 0;
    } else if (!string_compare(cmd, "break")) {
	add_muf_read_event(descr, player, program, fr);
        if (fr->brkpt.count >= MAX_BREAKS) {
            anotify_nolisten(player, CFAIL "Too many breakpoints set.", 1);
            return 0;
        }
        if (number(arg)) {
            i = atoi(arg);
        } else {
            if (!(pinst = funcname_to_pc(program, arg))) {
                anotify_nolisten(player, CINFO "I don't know a function by that name.", 1);
                return 0;
            } else {
                i = pinst->line;
            }
        }
        if (!i) i = fr->pc->line;
        j = fr->brkpt.count++;
        fr->brkpt.temp[j] = 0;
        fr->brkpt.level[j] = -1;
        fr->brkpt.line[j] = i;
        fr->brkpt.linecount[j] = -2;
        fr->brkpt.pc[j] = NULL;
        fr->brkpt.pccount[j] = -2;
        fr->brkpt.prog[j] = program;
        anotify_nolisten(player, CSUCC "Breakpoint set.", 1);
        return 0;
    } else if (!string_compare(cmd, "delete")) {
	add_muf_read_event(descr, player, program, fr);
        i = atoi(arg);
        if (!i) {
            anotify_nolisten(player, CINFO "Which breakpoint did you want to delete?", 1);
            return 0;
        }
        if (i < 1 || i > fr->brkpt.count) {
            anotify_nolisten(player, CFAIL "No such breakpoint.", 1);
            return 0;
        }
        j = i - 1;
        for (j++; j < fr->brkpt.count; j++) {
            fr->brkpt.temp[j-1]      = fr->brkpt.temp[j];
            fr->brkpt.level[j-1]     = fr->brkpt.level[j];
            fr->brkpt.line[j-1]      = fr->brkpt.line[j];
            fr->brkpt.linecount[j-1] = fr->brkpt.linecount[j];
            fr->brkpt.pc[j-1]        = fr->brkpt.pc[j];
            fr->brkpt.pccount[j-1]   = fr->brkpt.pccount[j];
            fr->brkpt.prog[j-1]      = fr->brkpt.prog[j];
        }
        fr->brkpt.count--;
        anotify_nolisten(player, CSUCC "Breakpoint deleted.", 1);
        return 0;
    } else if (!string_compare(cmd, "breaks")) {
        anotify_nolisten(player, CINFO "Breakpoints:", 1);
        for (i = 0; i < fr->brkpt.count; i++) {
            ptr = unparse_breakpoint(fr, i);
            notify_nolisten(player, ptr, 1);
        }
        anotify_nolisten(player, CINFO "Done.", 1);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "where")) {
        i = atoi(arg);
        muf_backtrace(player, program, i, fr);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "stack")) {
        anotify_nolisten(player, CINFO "*Argument stack top*", 1);
        i = atoi(arg);
        if (!i) i = STACK_SIZE;
        ptr = "";
        ref = program;
        for (j = fr->argument.top; j>0 && i-->0;) {
            cnt = 0;
            do {
                strcpy(buf, ptr);
                ptr = insttotext(&fr->argument.st[--j], buf2, sizeof(buf2), 4000, program);
                cnt++;
            } while (!string_compare(ptr, buf) && j>0);
            if (cnt > 1)
                notify_fmt(player, "     [repeats %d times]", cnt);
            if (string_compare(ptr, buf))
                notify_fmt(player, "%3d) %s", j+1, ptr);
        }
        anotify_nolisten(player, CINFO "Done.", 1);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "list") ||
	       !string_compare(cmd, "listi")) {
        int startline, endline;
        startline = endline = 0;
	add_muf_read_event(descr, player, program, fr);
        if ((ptr2 = (char *)index(arg, ','))) {
            *ptr2++ = '\0';
        } else {
            ptr2 = "";
        }
        if (!*arg) {
            if (fr->brkpt.lastlisted) {
                startline = fr->brkpt.lastlisted + 1;
            } else {
                startline = fr->pc->line;
            }
            endline = startline + 15;
        } else {
            if (!number(arg)) {
                if (!(pinst = funcname_to_pc(program, arg))) {
                    anotify_nolisten(player, CINFO "I don't know a function by that name. (starting arg, 1)", 1);
                    return 0;
                } else {
                    startline = pinst->line;
                    endline = startline + 15;
                }
            } else {
                if (*ptr2) {
                    endline = startline = atoi(arg);
                } else {
                    startline = atoi(arg) - 7;
                    endline = startline + 15;
                }
            }
        }
        if (*ptr2) {
            if (!number(ptr2)) {
                if (!(pinst = funcname_to_pc(program, ptr2))) {
                    anotify_nolisten(player, CINFO "I don't know a function by that name. (ending arg, 1)", 1);
                    return 0;
                } else {
                    endline = pinst->line;
                }
            } else {
                endline = atoi(ptr2);
            }
        }
        i = (DBFETCH(program)->sp.program.code +
                DBFETCH(program)->sp.program.siz - 1)->line;
        if (startline > i) {
            anotify_nolisten(player, CFAIL "Starting line is beyond end of program.", 1);
            return 0;
        }
        if (startline < 1) startline = 1;
        if (endline > i) endline = i;
        if (endline < startline) endline = startline;
        anotify_nolisten(player, CINFO "Listing:", 1);
	if (!string_compare(cmd, "listi")) {
	    for (i = startline; i <= endline; i++) {
		pinst = linenum_to_pc(program, i);
		if (pinst) {
		    sprintf(buf, "line %d: %s", i, (i == fr->pc->line) ?
			    show_line_prims(program, fr->pc, STACK_SIZE, 1) :
			    show_line_prims(program, pinst, STACK_SIZE, 0));
		    notify_nolisten(player, buf, 1);
		}
	    }
	} else {
	    list_proglines(player, program, fr, startline, endline);
	}
        fr->brkpt.lastlisted = endline;
        anotify_nolisten(player, CINFO "Done.", 1);
        return 0;
    } else if (!string_compare(cmd, "quit")) {
        anotify_nolisten(player, CINFO "Halting execution.", 1);
        return 1;
    } else if (!string_compare(cmd, "trace")) {
	add_muf_read_event(descr, player, program, fr);
        if (!string_compare(arg, "on")) {
            fr->brkpt.showstack = 1;
            anotify_nolisten(player, CSUCC "Trace turned on.", 1);
        } else if (!string_compare(arg, "off")) {
            fr->brkpt.showstack = 0;
            anotify_nolisten(player, CSUCC "Trace turned off.", 1);
        } else {
            sprintf(buf, CINFO "Trace is currently %s.",
                    fr->brkpt.showstack? "on" : "off");
            anotify_nolisten(player, buf, 1);
        }
        return 0;
    } else if (!string_compare(cmd, "words")) {
	list_program_functions(player, program, arg);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "print")) {
	debug_printvar(player, fr, arg);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "push")) {
	push_arg(player, fr, arg);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "pop")) {
	fr->argument.top--;
	CLEAR(fr->argument.st + fr->argument.top);
	anotify_nolisten(player, CSUCC "Stack item popped.", 1);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    } else if (!string_compare(cmd, "help")) {
notify_nolisten(player, "cont            continues execution until a breakpoint is hit.", 1);
notify_nolisten(player, "finish          completes execution of current function.", 1);
notify_nolisten(player, "step [NUM]      executes one (or NUM, 1) lines of muf.", 1);
notify_nolisten(player, "stepi [NUM]     executes one (or NUM, 1) muf instructions.", 1);
notify_nolisten(player, "next [NUM]      like step, except skips CALL and EXECUTE.", 1);
notify_nolisten(player, "nexti [NUM]     like stepi, except skips CALL and EXECUTE.", 1);
notify_nolisten(player, "break LINE#     sets breakpoint at given LINE number.", 1);
notify_nolisten(player, "break FUNCNAME  sets breakpoint at start of given function.", 1);
notify_nolisten(player, "breaks          lists all currently set breakpoints.", 1);
notify_nolisten(player, "delete NUM      deletes breakpoint by NUM, as listed by 'breaks'", 1);
notify_nolisten(player, "where [LEVS]    displays function call backtrace of up to num levels deep.", 1);
notify_nolisten(player, "stack [NUM]     shows the top num items on the stack.", 1);
notify_nolisten(player, "print v#        displays the value of given global variable #.", 1);
notify_nolisten(player, "print lv#       displays the value of given local variable #.", 1);
notify_nolisten(player, "trace [on|off]  turns on/off debug stack tracing.", 1);
notify_nolisten(player, "list [L1,[L2]]  lists source code of given line range.", 1);
notify_nolisten(player, "list FUNCNAME   lists source code of given function.", 1);
notify_nolisten(player, "listi [L1,[L2]] lists instructions in given line range.", 1);
notify_nolisten(player, "listi FUNCNAME  lists instructions in given function.", 1);
notify_nolisten(player, "words           lists all function word names in program.", 1);
notify_nolisten(player, "words PATTERN   lists all function word names that match PATTERN.", 1);
notify_nolisten(player, "exec FUNCNAME   calls given function with the current stack data.", 1);
notify_nolisten(player, "prim PRIMITIVE  executes given primitive with current stack data.", 1);
notify_nolisten(player, "push DATA       pushes an int, dbref, var, or string onto the stack.", 1);
notify_nolisten(player, "pop             pops top data item off the stack.", 1);
notify_nolisten(player, "help            displays this help screen.", 1);
notify_nolisten(player, "quit            stop execution here.", 1);
	add_muf_read_event(descr, player, program, fr);
	return 0;
    } else {
        anotify_nolisten(player, CINFO "I don't understand that debugger command. Type 'help' for help.", 1);
	add_muf_read_event(descr, player, program, fr);
        return 0;
    }
    return 0;
}
Пример #22
0
static int
multitech_connect(void)
{
	char c;
	int nc, nl, n;
	char dialer_buf[64];
	struct baud_msg *bm;
	sig_t f;

	if (multitech_swallow("\r\n") == 0)
		return (0);
	f = signal(SIGALRM, sigALRM);
again:
	nc = 0; nl = sizeof(dialer_buf)-1;
	bzero(dialer_buf, sizeof(dialer_buf));
	timeout = 0;
	for (nc = 0, nl = sizeof(dialer_buf)-1 ; nl > 0 ; nc++, nl--) {
		if (setjmp(timeoutbuf))
			break;
		alarm(number(value(DIALTIMEOUT)));
		n = read(FD, &c, 1);
		alarm(0);
		if (n <= 0)
			break;
		c &= 0x7f;
		if (c == '\r') {
			if (multitech_swallow("\n") == 0)
				break;
			if (!dialer_buf[0])
				goto again;
			if (strcmp(dialer_buf, "RINGING") == 0 &&
			    boolean(value(VERBOSE))) {
#ifdef DEBUG
				printf("%s\r\n", dialer_buf);
#endif
				goto again;
			}
			if (strncmp(dialer_buf, "CONNECT",
				    sizeof("CONNECT")-1) != 0)
				break;
			if (lock_baud) {
				signal(SIGALRM, f);
#ifdef DEBUG
				if (boolean(value(VERBOSE)))
					printf("%s\r\n", dialer_buf);
#endif
				return (1);
			}
			for (bm = baud_msg ; bm->msg ; bm++)
				if (strcmp(bm->msg, dialer_buf+sizeof("CONNECT")-1) == 0) {
					if (!acu_setspeed (bm->baud))
						goto error;
					signal(SIGALRM, f);
#ifdef DEBUG
					if (boolean(value(VERBOSE)))
						printf("%s\r\n", dialer_buf);
#endif
					return (1);
				}
			break;
		}
		dialer_buf[nc] = c;
	}
	printf("%s\r\n", dialer_buf);
error:
	signal(SIGALRM, f);
	return (0);
}
Пример #23
0
 bool operator==(const RuleID & x) const {
   return number()==x.number();
 };
Пример #24
0
int
multitech_dialer(char *num, char *acu)
{
	char *cp;
#if ACULOG
	char line [80];
#endif

	if (lock_baud)
	{
		int i;
		if ((i = speed(number(value(BAUDRATE)))) == 0)
			return 0;
		ttysetup (i);
	}

	if (boolean(value(VERBOSE)))
		printf("Using \"%s\"\n", acu);

	acu_hupcl ();

	/*
	 * Get in synch.
	 */
	if (!multitechsync()) {
badsynch:
		printf("can't synchronize with multitech\n");
#if ACULOG
		logent(value(HOST), num, "multitech", "can't synch up");
#endif
		return (0);
	}
	acu_nap (intercommand_delay);

	multitech_write_str (FD, echo_off_command);	/* turn off echoing */

	sleep(1);

#ifdef DEBUG
	if (boolean(value(VERBOSE)))
		multitech_verbose_read();
#endif

	acu_flush ();

	acu_nap (intercommand_delay);
	multitech_write_str (FD, init_string);

	if (!multitech_swallow ("\r\nOK\r\n"))
		goto badsynch;

	fflush (stdout);

	acu_nap (intercommand_delay);
	multitech_write_str (FD, dial_command);

	for (cp = num; *cp; cp++)
		if (*cp == '=')
			*cp = ',';

	multitech_write_str (FD, num);

	multitech_write_str (FD, "\r");

	connected = multitech_connect();

#if ACULOG
	if (timeout) {
		sprintf(line, "%d second dial timeout",
			number(value(DIALTIMEOUT)));
		logent(value(HOST), num, "multitech", line);
	}
#endif
	if (timeout)
		multitech_disconnect ();
	return (connected);
}
Пример #25
0
atom_t *new_number(const double value) {
	atom_t *atom = new_atom(ATOM_NUMBER);
	number(atom) = value;
	return atom;
}
Пример #26
0
int
main(int argc, char *argv[])
{
	char *sys = NOSTR, sbuf[12], *p;
	int i;

	/* XXX preserve previous braindamaged behavior */
	setboolean(value(DC), TRUE);

	gid = getgid();
	egid = getegid();
	uid = getuid();
	euid = geteuid();
	if (equal(__progname, "cu")) {
		cumode = 1;
		cumain(argc, argv);
		goto cucommon;
	}

	if (argc > 4) {
		fprintf(stderr, "usage: tip [-v] [-speed] [system-name]\n");
		exit(1);
	}
	if (!isatty(0)) {
		fprintf(stderr, "%s: must be interactive\n", __progname);
		exit(1);
	}

	for (; argc > 1; argv++, argc--) {
		if (argv[1][0] != '-')
			sys = argv[1];
		else switch (argv[1][1]) {

		case 'v':
			vflag++;
			break;

		case 'n':
			noesc++;
			break;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			BR = atoi(&argv[1][1]);
			break;

		default:
			fprintf(stderr, "%s: %s, unknown option\n", __progname,
			    argv[1]);
			break;
		}
	}

	if (sys == NOSTR)
		goto notnumber;
	if (isalpha(*sys))
		goto notnumber;
	/*
	 * System name is really a phone number...
	 * Copy the number then stomp on the original (in case the number
	 *	is private, we don't want 'ps' or 'w' to find it).
	 */
	if (strlen(sys) > sizeof PNbuf - 1) {
		fprintf(stderr, "%s: phone number too long (max = %d bytes)\n",
			__progname, (int)sizeof(PNbuf) - 1);
		exit(1);
	}
	strlcpy(PNbuf, sys, sizeof PNbuf - 1);
	for (p = sys; *p; p++)
		*p = '\0';
	PN = PNbuf;
	(void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR);
	sys = sbuf;

notnumber:
	(void)signal(SIGINT, cleanup);
	(void)signal(SIGQUIT, cleanup);
	(void)signal(SIGHUP, cleanup);
	(void)signal(SIGTERM, cleanup);
	(void)signal(SIGCHLD, SIG_DFL);

	if ((i = hunt(sys)) == 0) {
		printf("all ports busy\n");
		exit(3);
	}
	if (i == -1) {
		printf("link down\n");
		(void)uu_unlock(uucplock);
		exit(3);
	}
	setbuf(stdout, NULL);
	loginit();

	/*
	 * Now that we have the logfile and the ACU open
	 *  return to the real uid and gid.  These things will
	 *  be closed on exit.  Swap real and effective uid's
	 *  so we can get the original permissions back
	 *  for removing the uucp lock.
	 */
	user_uid();

	/*
	 * Kludge, their's no easy way to get the initialization
	 *   in the right order, so force it here
	 */
	if ((PH = getenv("PHONES")) == NOSTR)
		PH = _PATH_PHONES;
	vinit();				/* init variables */
	setparity("none");			/* set the parity table */

	/*
	 * Hardwired connections require the
	 *  line speed set before they make any transmissions
	 *  (this is particularly true of things like a DF03-AC)
	 */
	if (HW && ttysetup(number(value(BAUDRATE)))) {
		fprintf(stderr, "%s: bad baud rate %ld\n", __progname,
		    number(value(BAUDRATE)));
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(3);
	}
	if ((p = con())) {
		printf("\07%s\n[EOT]\n", p);
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(1);
	}
	if (!HW && ttysetup(number(value(BAUDRATE)))) {
		fprintf(stderr, "%s: bad baud rate %ld\n", __progname,
		    number(value(BAUDRATE)));
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(3);
	}
cucommon:
	/*
	 * From here down the code is shared with
	 * the "cu" version of tip.
	 */

	i = fcntl(FD, F_GETFL);
	if (i == -1) {
		perror("fcntl");
		cleanup(0);
	}
	i = fcntl(FD, F_SETFL, i & ~O_NONBLOCK);
	if (i == -1) {
		perror("fcntl");
		cleanup(0);
	}

	tcgetattr(0, &defterm);
	gotdefterm = 1;
	term = defterm;
	term.c_lflag &= ~(ICANON|IEXTEN|ECHO);
	term.c_iflag &= ~(INPCK|ICRNL);
	term.c_oflag &= ~OPOST;
	term.c_cc[VMIN] = 1;
	term.c_cc[VTIME] = 0;
	defchars = term;
	term.c_cc[VINTR] = term.c_cc[VQUIT] = term.c_cc[VSUSP] =
	    term.c_cc[VDSUSP] = term.c_cc[VDISCARD] =
	    term.c_cc[VLNEXT] = _POSIX_VDISABLE;
	raw();

	pipe(fildes); pipe(repdes);
	(void)signal(SIGALRM, timeout);

	if (value(LINEDISC) != TTYDISC) {
		int ld = (int)(intptr_t)value(LINEDISC);
		ioctl(FD, TIOCSETD, &ld);
	}		

	/*
	 * Everything's set up now:
	 *	connection established (hardwired or dialup)
	 *	line conditioned (baud rate, mode, etc.)
	 *	internal data structures (variables)
	 * so, fork one process for local side and one for remote.
	 */
	printf(cumode ? "Connected\r\n" : "\07connected\r\n");
	tipin_pid = getpid();
	if ((tipout_pid = fork()))
		tipin();
	else
		tipout();
	/*NOTREACHED*/
	exit(0);
}
Пример #27
0
/*
 * Creates an sql query to fetch contact item IDs for all the contact items
 * which may contain the specified telephone number in a telephone, fax
 * or SMS type field.
 *
 * The comparison method used is not exact.  The number is compared starting from
 * the right side of the number and the method returns an array of candidate
 * matches.  Punctuation (e.g. spaces) and other alphabetic characters are ignored
 * when comparing.
 * 
 * Note that due to the way numbers are stored in the database, it is recommended
 * that at least 7 match digits are specified even when matching a number
 * containing fewer digits.  Failure to follow this guideline may (depending on the
 * database contents) mean that the function will not return the expected Contact
 * IDs.
 */
void CntFilterDetail::createMatchPhoneNumberQuery(
                                      const QContactFilter& filter,
                                      QString& sqlQuery,
                                      QContactManager::Error* error)

{
    if (!filterSupported(filter) ) {
      *error = QContactManager::NotSupportedError;
      return;
    }
          
    QContactDetailFilter detailFilter(filter);
    QString number((detailFilter.value()).toString());
    TPtrC numberPtr(reinterpret_cast<const TUint16*>(number.utf16()));
    
    TInt matchLengthFromRight(KDefaultMatchLength);
    // no need to propagate error, we can use the default match length
    TRAP_IGNORE(getMatchLengthL(matchLengthFromRight));
    
    TInt numLowerDigits = matchLengthFromRight;
    TInt numUpperDigits = 0;
    
    if (numLowerDigits > KLowerSevenDigits) {
        numLowerDigits = KLowerSevenDigits;
        numUpperDigits = matchLengthFromRight - KLowerSevenDigits;
    }
    else if (numLowerDigits == 0) {
        // best match phonenumbers
        numLowerDigits = KLowerSevenDigits;
    }
    
    TMatch phoneDigits = createPaddedPhoneDigits(
                          numberPtr, numLowerDigits, numUpperDigits, error);
    
    if (*error == QContactManager::NoError) {
        // select fields for contacts that match phone lookup
        //  SELECT contact_id FROM comm_addr
        //      WHERE value = [value string] AND type = [type value];
        //
        QString type =  QString(" type = %1").arg(CntDbInfo::EPhoneNumber);
        QString value =  QString(" value = %1").arg(phoneDigits.iLowerSevenDigits);
        QString whereClause = " WHERE" + value + " AND" + type;
        if (matchLengthFromRight <= KLowerSevenDigits) {
            // Matching 7 or less digits...
            sqlQuery = "SELECT contact_id FROM comm_addr" + whereClause;
        }
        else {
            // Checking the upper digits...
        
            // select fields for contacts that match phone lookup
            //  SELECT contact_id, extra_value FROM comm_addr
            //      WHERE value = [value string] AND type = [type value];
            //
            QString type =  QString(" type = %1").arg(CntDbInfo::EPhoneNumber);
            QString value =  QString(" value = %1").arg(phoneDigits.iLowerSevenDigits);
            QString whereClause = " WHERE" + value + " AND" + type;
            sqlQuery = "SELECT contact_id, extra_value FROM comm_addr" + whereClause;
            
            QList<QPair<QContactLocalId, QString> > contactMatches =  m_srvConnection.searchPhoneNumbers(sqlQuery, error);
            
            // Check if search query was successful
            if (*error != QContactManager::NoError) {
                  return;
                }
            
            QStringList list;
            for (int i=0; i<contactMatches.count(); ++i) {
                // Check the upper digits...
                TInt32 storedUpperDigits(0);
                QString extraValue = contactMatches.at(i).second;
                TPtrC extValString(reinterpret_cast<const TUint16*>(extraValue.utf16()));
                if (TLex(extValString).Val(storedUpperDigits) == KErrNone) {
                
                    const TInt KDigitsToRemove = KMaxPhoneMatchLength - KLowerSevenDigits - phoneDigits.iNumUpperDigits;
                    for (TInt j = 0; j < KDigitsToRemove; ++j) {
                        // repeatedly divide by 10 to lop off the appropriate number of digits from the right
                        storedUpperDigits /= 10;
                    }
                
                    storedUpperDigits = TMatch::padOutPhoneMatchNumber(storedUpperDigits, KDigitsToRemove);
                
                    if (phoneDigits.iUpperDigits == storedUpperDigits) {
                        list.append(QString("%1").arg(contactMatches.at(i).first));
                    }
                }
                else {
                    *error = QContactManager::UnspecifiedError;
                    return;
                }
            }
            // Recreate query to fetch all match ids
            // SELECT DISTINCT contact_id FROM contact WHERE contact_id in (
            //      ..
            // )  
            QString ids = list.join(" ,");
            sqlQuery = "SELECT DISTINCT contact_id FROM contact WHERE contact_id in (";
            sqlQuery += ids;
            sqlQuery += ')';
        }
    }
}
Пример #28
0
void *LiveJournalClient::processEvent(Event *e)
{
    if (e->type() == EventOpenMessage){
        Message *msg = (Message*)(e->param());
        if (msg->type() != MessageUpdated)
            return NULL;
        if (dataName(&data.owner) != msg->client())
            return NULL;
        Event eDel(EventMessageDeleted, msg);
        eDel.process();
        string url = "http://";
        url += getServer();
        if (getPort() != 80){
            url += ":";
            url += number(getPort());
        }
        url += "/";
        Event eGo(EventGoURL, (void*)url.c_str());
        eGo.process();
        if (getState() == Connected)
            m_timer->start(getInterval() * 60 * 1000, true);
        return e->param();
    }
    if (e->type() == EventFetchDone){
        fetchData *data = (fetchData*)e->param();
        if (data->req_id != m_fetchId)
            return NULL;
        m_fetchId = 0;
        if (data->result == 200){
            m_request->result(data->data);
        }else{
            string err = "Fetch error ";
            err += number(data->result);
            error_state(err.c_str(), 0);
            statusChanged();
        }
        delete m_request;
        m_request = NULL;
        send();
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdDeleteJournalMessage){
            Message *msg = (Message*)(cmd->param);
            Contact *contact = getContacts()->contact(msg->contact());
            if (contact == NULL)
                return NULL;
            LiveJournalUserData *data;
            ClientDataIterator it(contact->clientData, this);
            while ((data = (LiveJournalUserData*)(++it)) != NULL){
                if (dataName(data) == msg->client()){
                    JournalMessage *m = new JournalMessage(msg->save().c_str());
                    m->setContact(msg->contact());
                    m->setOldID(msg->id());
                    m->setText("");
                    if (!send(m, data))
                        delete m;
                    return e->param();
                }
            }
            return NULL;
        }
        unsigned menu_id = cmd->menu_id - MenuWeb;
        if (menu_id > LiveJournalPlugin::MenuCount)
            return NULL;
        unsigned item_id = cmd->id - CmdMenuWeb;
        if ((item_id == 0) || (item_id >= 0x100))
            return NULL;
        const char *url = getMenuUrl(menu_id * 0x100 + item_id);
        if ((url == NULL) || (*url == 0))
            return NULL;
        Event eUrl(EventGoURL, (void*)url);
        eUrl.process();
        return e->param();
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if (cmd->id == CmdMenuWeb){
            unsigned menu_id = cmd->menu_id - MenuWeb;
            if (menu_id > LiveJournalPlugin::MenuCount)
                return NULL;
            unsigned nItems = 0;
            unsigned list_id = menu_id * 0x100 + 1;
            for (;;){
                const char *text = getMenu(list_id);
                if ((text == NULL) || (*text == 0))
                    break;
                nItems++;
                list_id++;
            }
            if (nItems == 0)
                return NULL;
            CommandDef *cmds = new CommandDef[nItems + 1];
            memset(cmds, 0, sizeof(CommandDef) * (nItems + 1));
            list_id = menu_id * 0x100 + 1;
            for (unsigned i = 0;; i++){
                const char *text = getMenu(list_id);
                if ((text == NULL) || (*text == 0))
                    break;
                cmds[i].text = "_";
                if (strcmp(text, "-")){
                    cmds[i].id = CmdMenuWeb + i + 1;
                    cmds[i].text = "_";
                    QString s = i18n(text);
                    cmds[i].text_wrk = strdup(s.utf8());
                    const char *url = getMenuUrl(list_id);
                    if (url && (*url == '@')){
                        unsigned nSub = atol(url + 1);
                        while (nSub > LiveJournalPlugin::MenuCount){
                            unsigned menu_id = MenuWeb + (++LiveJournalPlugin::MenuCount);
                            Event eMenu(EventMenuCreate, (void*)menu_id);
                            eMenu.process();
                            Command cmd;
                            cmd->id       = CmdMenuWeb;
                            cmd->text     = "_";
                            cmd->menu_id  = menu_id;
                            cmd->menu_grp = 0x1000;
                            cmd->flags    = COMMAND_CHECK_STATE;
                            Event e(EventCommandCreate, cmd);
                            e.process();
                        }
                        cmds[i].popup_id = MenuWeb + nSub;
                    }
                }else{
                    cmds[i].id = 0;
                }
                list_id++;
            }
            cmd->param = cmds;
            cmd->flags |= COMMAND_RECURSIVE;
            return e->param();
        }
    }
    return NULL;
}
Пример #29
0
int
trapcmd(shinstance *psh, int argc, char **argv)
{
	char *action;
	char **ap;
	int signo;
#ifndef HAVE_SYS_SIGNAME
	init_sys_signame();
#endif

	if (argc <= 1) {
		for (signo = 0 ; signo <= NSIG ; signo++)
			if (psh->trap[signo] != NULL) {
				out1fmt(psh, "trap -- ");
				print_quoted(psh, psh->trap[signo]);
				out1fmt(psh, " %s\n",
				    (signo) ? sys_signame[signo] : "EXIT");
			}
		return 0;
	}
	ap = argv + 1;

	action = NULL;

	if (strcmp(*ap, "--") == 0)
		if (*++ap == NULL)
			return 0;

	if (signame_to_signum(psh, *ap) == -1) {
		if ((*ap)[0] == '-') {
			if ((*ap)[1] == '\0')
				ap++;
			else if ((*ap)[1] == 'l' && (*ap)[2] == '\0') {
				printsignals(psh);
				return 0;
			}
			else
				error(psh, "bad option %s\n", *ap);
		}
		else
			action = *ap++;
	}

	while (*ap) {
		if (is_number(*ap))
			signo = number(psh, *ap);
		else
			signo = signame_to_signum(psh, *ap);

		if (signo < 0 || signo > NSIG)
			error(psh, "%s: bad trap", *ap);

		INTOFF;
		if (action)
			action = savestr(psh, action);

		if (psh->trap[signo])
			ckfree(psh, psh->trap[signo]);

		psh->trap[signo] = action;

		if (signo != 0)
			setsignal(psh, signo, 0);
		INTON;
		ap++;
	}
	return 0;
}
Пример #30
0
static int
cour_connect(void)
{
	char c;
	int volatile nc;
	int volatile nl;
	int n;
	char dialer_buf[64];
	struct baud_msg *bm;
	sig_t f;

	if (cour_swallow("\r\n") == 0)
		return (0);
	f = signal(SIGALRM, sigALRM);
again:
	(void)memset(dialer_buf, 0, sizeof(dialer_buf));
	timeout = 0;
	for (nc = 0, nl = sizeof(dialer_buf) - 1 ; nl > 0 ; nc++, nl--) {
		if (setjmp(timeoutbuf))
			break;
		(void)alarm((unsigned)number(value(DIALTIMEOUT)));
		n = read(FD, &c, 1);
		(void)alarm(0);
		if (n <= 0)
			break;
		c &= 0x7f;
		if (c == '\r') {
			if (cour_swallow("\n") == 0)
				break;
			if (!dialer_buf[0])
				goto again;
			if (strcmp(dialer_buf, "RINGING") == 0 &&
			    boolean(value(VERBOSE))) {
#ifdef DEBUG
				(void)printf("%s\r\n", dialer_buf);
#endif
				goto again;
			}
			if (strncmp(dialer_buf, "CONNECT",
				    sizeof("CONNECT")-1) != 0)
				break;
			for (bm = baud_msg ; bm->msg ; bm++)
				if (strcmp(bm->msg,
				    dialer_buf+sizeof("CONNECT")-1) == 0) {
					struct termios	cntrl;

					(void)tcgetattr(FD, &cntrl);
					(void)cfsetospeed(&cntrl, bm->baud);
					(void)cfsetispeed(&cntrl, bm->baud);
					(void)tcsetattr(FD, TCSAFLUSH, &cntrl);
					(void)signal(SIGALRM, f);
#ifdef DEBUG
					if (boolean(value(VERBOSE)))
						(void)printf("%s\r\n", dialer_buf);
#endif
					return (1);
				}
			break;
		}
		dialer_buf[nc] = c;
#ifdef notdef
		if (boolean(value(VERBOSE)))
			(void)putchar(c);
#endif
	}
	(void)printf("%s\r\n", dialer_buf);
	(void)signal(SIGALRM, f);
	return (0);
}