/*---------------------------------------------------------------------------*/
static void
lpm_drop_handler(uint8_t mode)
{
  /*
   * First, wait for any outstanding TX to complete. If we have an input
   * handler, the SERIAL PD will be kept on and the UART module clock will
   * be enabled under sleep as well as deep sleep. In theory, this means that
   * we shouldn't lose any outgoing bytes, but we actually do on occasion.
   * This byte loss may (or may not) be related to the freezing of IO latches
   * between MCU and AON when we drop to deep sleep. This here is essentially a
   * workaround
   */
  if(accessible() == true) {
    while(ti_lib_uart_busy(UART0_BASE));
  }

  /*
   * If we have a registered input_handler then we need to retain RX
   * capability. Thus, if this is not a shutdown notification and we have an
   * input handler, we do nothing
   */
  if((mode != LPM_MODE_SHUTDOWN) && (input_handler != NULL)) {
    return;
  }

  /*
   * If we reach here, we either don't care about staying awake or we have
   * received a shutdown notification
   *
   * Only touch UART registers if the module is powered and clocked
   */
  if(accessible() == true) {
    /* Disable the module */
    ti_lib_uart_disable(UART0_BASE);

    /* Disable all UART interrupts and clear all flags */
    disable_interrupts();
  }

  /*
   * Always stop the clock in run mode. Also stop in Sleep and Deep Sleep if
   * this is a request for full shutdown
   */
  ti_lib_prcm_peripheral_run_disable(PRCM_PERIPH_UART0);
  if(mode == LPM_MODE_SHUTDOWN) {
    ti_lib_prcm_peripheral_sleep_disable(PRCM_PERIPH_UART0);
    ti_lib_prcm_peripheral_deep_sleep_disable(PRCM_PERIPH_UART0);
  }
  ti_lib_prcm_load_set();
  while(!ti_lib_prcm_load_get());

  /* Set pins to low leakage configuration in preparation for deep sleep */
  lpm_pin_set_default_state(BOARD_IOID_UART_TX);
  lpm_pin_set_default_state(BOARD_IOID_UART_RX);
  lpm_pin_set_default_state(BOARD_IOID_UART_CTS);
  lpm_pin_set_default_state(BOARD_IOID_UART_RTS);
}
bool CRestrictedObject::accessible			(u32 level_vertex_id) const
{
	START_PROFILE("Restricted Object/Accessible");
	VERIFY						(ai().level_graph().valid_vertex_id(level_vertex_id));
	return						(accessible(level_vertex_id,EPS_L));
	STOP_PROFILE;
}
/*---------------------------------------------------------------------------*/
void
board_i2c_select(uint8_t new_interface, uint8_t address)
{
  slave_addr = address;

  if(accessible() == false) {
    board_i2c_wakeup();
  }

  if(new_interface != interface) {
    interface = new_interface;

    ti_lib_i2c_master_disable(I2C0_BASE);

    if(interface == BOARD_I2C_INTERFACE_0) {
      ti_lib_ioc_io_port_pull_set(BOARD_IOID_SDA, IOC_NO_IOPULL);
      ti_lib_ioc_io_port_pull_set(BOARD_IOID_SCL, IOC_NO_IOPULL);
      ti_lib_ioc_pin_type_i2c(I2C0_BASE, BOARD_IOID_SDA, BOARD_IOID_SCL);
      ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SDA_HP);
      ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SCL_HP);
    } else if(interface == BOARD_I2C_INTERFACE_1) {
      ti_lib_ioc_io_port_pull_set(BOARD_IOID_SDA_HP, IOC_NO_IOPULL);
      ti_lib_ioc_io_port_pull_set(BOARD_IOID_SCL_HP, IOC_NO_IOPULL);
      ti_lib_ioc_pin_type_i2c(I2C0_BASE, BOARD_IOID_SDA_HP, BOARD_IOID_SCL_HP);
      ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SDA);
      ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SCL);
    }

    /* Enable and initialize the I2C master module */
    ti_lib_i2c_master_init_exp_clk(I2C0_BASE, ti_lib_sys_ctrl_clock_get(),
                                   true);
  }
}
/*---------------------------------------------------------------------------*/
void
board_i2c_shutdown()
{
  interface = NO_INTERFACE;

  if(accessible()) {
    ti_lib_i2c_master_disable(I2C0_BASE);
  }

  ti_lib_prcm_peripheral_run_disable(PRCM_PERIPH_I2C0);
  ti_lib_prcm_load_set();
  while(!ti_lib_prcm_load_get());

  /*
   * Set all pins to GPIO Input and disable the output driver. Set internal
   * pull to match external pull
   *
   * SDA and SCL: external PU resistor
   * SDA HP and SCL HP: MPU PWR low
   */
  ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SDA_HP);
  ti_lib_ioc_io_port_pull_set(BOARD_IOID_SDA_HP, IOC_IOPULL_DOWN);
  ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SCL_HP);
  ti_lib_ioc_io_port_pull_set(BOARD_IOID_SCL_HP, IOC_IOPULL_DOWN);

  ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SDA);
  ti_lib_ioc_io_port_pull_set(BOARD_IOID_SDA, IOC_IOPULL_UP);
  ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SCL);
  ti_lib_ioc_io_port_pull_set(BOARD_IOID_SCL, IOC_IOPULL_UP);
}
Beispiel #5
0
int BattleInfo::getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos) const
{
	bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
	//bool flying = VLC->creh->creatures[creID]->isFlying();

	int pos;
	if (initialPos > -1)
		pos = initialPos;
	else //summon elementals depending on player side
	{
 		if (attackerOwned)
	 		pos = 0; //top left
 		else
 			pos = GameConstants::BFIELD_WIDTH - 1; //top right
 	}

	auto accessibility = getAccesibility();

	std::set<BattleHex> occupyable;
	for(int i = 0; i < accessibility.size(); i++)
		if(accessibility.accessible(i, twoHex, attackerOwned))
			occupyable.insert(i);

	if (occupyable.empty())
	{
		return BattleHex::INVALID; //all tiles are covered
	}

	return BattleHex::getClosestTile(attackerOwned, pos, occupyable);
}
bool UIGChooserItemMachine::isDropAllowed(QGraphicsSceneDragDropEvent *pEvent, DragToken where) const
{
    /* No drops while saving groups: */
    if (model()->isGroupSavingInProgress())
        return false;
    /* No drops for immutable item: */
    if (isLockedMachine())
        return false;
    /* Get mime: */
    const QMimeData *pMimeData = pEvent->mimeData();
    /* If drag token is shown, its up to parent to decide: */
    if (where != DragToken_Off)
        return parentItem()->isDropAllowed(pEvent);
    /* Else we should make sure machine is accessible: */
    if (!accessible())
        return false;
    /* Else we should try to cast mime to known classes: */
    if (pMimeData->hasFormat(UIGChooserItemMachine::className()))
    {
        /* Make sure passed item id is not ours: */
        const UIGChooserItemMimeData *pCastedMimeData = qobject_cast<const UIGChooserItemMimeData*>(pMimeData);
        AssertMsg(pCastedMimeData, ("Can't cast passed mime-data to UIGChooserItemMimeData!"));
        UIGChooserItem *pItem = pCastedMimeData->item();
        UIGChooserItemMachine *pMachineItem = pItem->toMachineItem();
        /* Make sure passed machine is mutable: */
        if (pMachineItem->isLockedMachine())
            return false;
        return pMachineItem->id() != id();
    }
    /* That was invalid mime: */
    return false;
}
Beispiel #7
0
nsIntPoint
nsAccUtils::GetScreenCoordsForParent(nsIAccessNode *aAccessNode)
{
  nsRefPtr<nsAccessNode> parent;
  nsCOMPtr<nsIAccessible> accessible(do_QueryInterface(aAccessNode));
  if (accessible) {
    nsCOMPtr<nsIAccessible> parentAccessible;
    accessible->GetParent(getter_AddRefs(parentAccessible));
    parent = nsAccUtils::QueryAccessNode(parentAccessible);
  } else {
    nsCOMPtr<nsIAccessNode> parentAccessNode;
    aAccessNode->GetParentNode(getter_AddRefs(parentAccessNode));
    parent = nsAccUtils::QueryAccessNode(parentAccessNode);
  }

  if (!parent)
    return nsIntPoint(0, 0);

  nsIFrame *parentFrame = parent->GetFrame();
  if (!parentFrame)
    return nsIntPoint(0, 0);

  nsIntRect parentRect = parentFrame->GetScreenRectExternal();
  return nsIntPoint(parentRect.x, parentRect.y);
}
Beispiel #8
0
void
LevelDot::draw_hover(DrawingContext& gc)
{
  if (accessible())
  {
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x),
                             static_cast<int>(pos.y) - 44),
                    _(get_plf().get_levelname()), 
                    10000);
  }
  else
  {       
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x),
                             static_cast<int>(pos.y) - 44),
                    _("???"),
                    10000);
  }

  if (globals::developer_mode)
  {
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y) - 70),
                    get_plf().get_resname(), 
                    10000);
  }
}
Beispiel #9
0
u32int Ressource::call(u8int id, u32int a, u32int b, u32int c, u32int d, u32int e) {
	if (!ISROOT && !accessible()) return (u32int) - 1;
	if (id == 0) return m_type;
	m_lock.waitLock();
	u32int r = doCall(id, a, b, c, d, e);
	m_lock.unlock();
	return r;
}
void UIGChooserItemMachine::mousePressEvent(QGraphicsSceneMouseEvent *pEvent)
{
    /* Call to base-class: */
    UIGChooserItem::mousePressEvent(pEvent);
    /* No drag for inaccessible: */
    if (!accessible())
        pEvent->ignore();
}
void CRestrictedObject::add_border			(u32 start_vertex_id, u32 dest_vertex_id) const
{
	START_PROFILE("Restricted Object/Add Border");	
	VERIFY						(ai().level_graph().valid_vertex_id(start_vertex_id));
	VERIFY						(!m_applied);
	VERIFY						(m_removed);
	m_removed					= false;
	if (accessible(start_vertex_id)) {
		m_applied				= true;
		Level().space_restriction_manager().add_border(object().ID(),start_vertex_id,dest_vertex_id);
	}
	STOP_PROFILE;
}
Beispiel #12
0
void GridWorld::applyOn(const DAction& ac)
{
//     LOG_DEBUG(*dstate << " " << ac);
  
    // if we are on a goal, we eat it
    if(last_reward > 0) {
        world[state->x][state->y] = -1;
	
	//and pass to the next
        state->currentGoal++;
        if(state->currentGoal < NBGOALS) {
            state->xgoal = XGOALS[state->currentGoal];
            state->ygoal = YGOALS[state->currentGoal];
        }
    }

    int direction = ac[MOV];
    switch(direction) {
    case 0:
        if(accessible(state->x, state->y - 1))
            state->y --;
        break;
    case 1:
        if(accessible(state->x, state->y + 1))
            state->y ++;
        break;
    case 2:
        if(accessible(state->x - 1, state->y))
            state->x --;
        break;
    case 3:
        if(accessible(state->x + 1, state->y))
            state->x ++;
        break;
    }

    last_reward = reward();
}
Beispiel #13
0
/*---------------------------------------------------------------------------*/
void
cc26xx_uart_write_byte(uint8_t c)
{
  /* Return early if disabled by user conf or if ports are misconfigured */
  if(usable() == false) {
    return;
  }

  if(accessible() == false) {
    enable();
  }

  ti_lib_uart_char_put(UART0_BASE, c);
}
void CRestrictedObject::add_border			(const Fvector &start_position, const Fvector &dest_position) const
{
	START_PROFILE("Restricted Object/Add Border");	

	VERIFY						(!m_applied);
	VERIFY						(m_removed);
	m_removed					= false;
	if (accessible(start_position)) {
		m_applied				= true;
		Level().space_restriction_manager().add_border(object().ID(),start_position,dest_position);
	}

	STOP_PROFILE;
}
Beispiel #15
0
/*---------------------------------------------------------------------------*/
uint8_t
cc26xx_uart_busy(void)
{
  /* Return early if disabled by user conf or if ports are misconfigured */
  if(usable() == false) {
    return UART_IDLE;
  }

  /* If the UART is not accessible, it is not busy */
  if(accessible() == false) {
    return UART_IDLE;
  }

  return ti_lib_uart_busy(UART0_BASE);
}
u32	CRestrictedObject::accessible_nearest	(const Fvector &position, Fvector &result) const
{
	START_PROFILE("Restricted Object/Accessible Nearest");
	VERIFY2						(
		!accessible(position),
		make_string(
			"[%s] [%f][%f][%f]",
			object().cName().c_str(),
			VPUSH(position)
		)
	);

	return						(Level().space_restriction_manager().accessible_nearest(object().ID(),position,result));
	STOP_PROFILE;
}
nsAccStateChangeEvent::
  nsAccStateChangeEvent(nsIDOMNode *aNode,
                        PRUint32 aState, PRBool aIsExtraState):
  nsAccEvent(::nsIAccessibleEvent::EVENT_STATE_CHANGE, aNode),
  mState(aState), mIsExtraState(aIsExtraState)
{
  // Use GetAccessibleByNode() because we do not want to store an accessible
  // since it leads to problems with delayed events in the case when
  // an accessible gets reorder event before delayed event is processed.
  nsCOMPtr<nsIAccessible> accessible(GetAccessibleByNode());
  if (accessible) {
    PRUint32 state = 0, extraState = 0;
    accessible->GetFinalState(&state, mIsExtraState ? &extraState : nsnull);
    mIsEnabled = ((mIsExtraState ? extraState : state) & mState) != 0;
  } else {
    mIsEnabled = PR_FALSE;
  }
}
Beispiel #18
0
void
LevelDot::draw_hover(DrawingContext& gc)
{
  int pos_correction = 0;

  if (accessible())
  {
    int length = Fonts::pingus_small.bounding_rect(0, 0, _(get_plf().get_levelname())).get_width() / 2;
    int realpos = gc.world_to_screen(Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y))).x;
    if (realpos - length < 0)
      pos_correction = realpos - length;
    else if (realpos + length > gc.get_width())
      pos_correction = realpos + length - static_cast<int>(gc.get_width());
      
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x) - pos_correction,
                             static_cast<int>(pos.y) - 44),
                    _(get_plf().get_levelname()), 
                    10000);
  }
  else
  {
    int length  = Fonts::pingus_small.bounding_rect(0, 0, _("locked")).get_width() / 2;
    int realpos = gc.world_to_screen(Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y))).x;
    if (realpos - length < 0)
      pos_correction = realpos - length;
    else if (realpos + length > gc.get_width())
      pos_correction = realpos + length - static_cast<int>(gc.get_width());
        
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x) - pos_correction,
                             static_cast<int>(pos.y) - 30),
                    _("locked"), 
                    10000);
  }

  if (globals::maintainer_mode)
  {
    gc.print_center(Fonts::pingus_small,
                    Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y) - 56),
                    get_plf().get_resname(), 
                    10000);
  }
}
Beispiel #19
0
/*
 * Try to find a dismount point adjacent to the steed's location.
 * If all else fails, try enexto().  Use enexto() as a last resort because
 * enexto() chooses its point randomly, possibly even outside the
 * room's walls, which is not what we want.
 * Adapted from mail daemon code.
 */
static boolean
landing_spot(coord * spot,      /* landing position (we fill it in) */
             int reason, int forceit)
{
    int i = 0, x, y, distance, min_distance = -1;
    boolean found = FALSE;
    struct trap *t;

    /* avoid known traps (i == 0) and boulders, but allow them as a backup */
    if (reason != DISMOUNT_BYCHOICE || Stunned || Confusion || Fumbling)
        i = 1;
    for (; !found && i < 2; ++i) {
        for (x = u.ux - 1; x <= u.ux + 1; x++)
            for (y = u.uy - 1; y <= u.uy + 1; y++) {
                if (!isok(x, y) || (x == u.ux && y == u.uy))
                    continue;

                if (accessible(level, x,y) && !MON_AT(level, x, y)) {
                    distance = distu(x, y);
                    if (min_distance < 0 || distance < min_distance ||
                            (distance == min_distance && rn2(2))) {
                        if (i > 0 ||
                                (((t = t_at(level, x, y)) == 0 || !t->tseen) &&
                                 (!sobj_at(BOULDER, level, x, y) ||
                                  throws_rocks(youmonst.data)))) {
                            spot->x = x;
                            spot->y = y;
                            min_distance = distance;
                            found = TRUE;
                        }
                    }
                }
            }
    }

    /* If we didn't find a good spot and forceit is on, try enexto(). */
    if (forceit && min_distance < 0 &&
            !enexto(spot, level, u.ux, u.uy, youmonst.data))
        return FALSE;

    return found;
}
already_AddRefed<nsIDOMNode>
nsXFormsSelectableAccessible::GetItemByIndex(PRInt32 *aIndex,
                                             nsIAccessible *aAccessible)
{
  nsCOMPtr<nsIAccessible> accessible(aAccessible ? aAccessible : this);

  nsCOMPtr<nsIAccessible> curAccChild;
  accessible->GetFirstChild(getter_AddRefs(curAccChild));

  while (curAccChild) {
    nsCOMPtr<nsIAccessNode> curAccNodeChild(do_QueryInterface(curAccChild));
    if (curAccNodeChild) {
      nsCOMPtr<nsIDOMNode> curChildNode;
      curAccNodeChild->GetDOMNode(getter_AddRefs(curChildNode));
      nsCOMPtr<nsIContent> curChildContent(do_QueryInterface(curChildNode));
      if (curChildContent) {
        nsCOMPtr<nsINodeInfo> nodeInfo = curChildContent->NodeInfo();
        if (nodeInfo->NamespaceEquals(NS_LITERAL_STRING(NS_NAMESPACE_XFORMS))) {
          if (nodeInfo->Equals(nsAccessibilityAtoms::item)) {
            if (!*aIndex) {
              nsIDOMNode *itemNode = nsnull;
              curChildNode.swap(itemNode);
              return itemNode;
            }
            --*aIndex;
          } else if (nodeInfo->Equals(nsAccessibilityAtoms::choices)) {
            nsIDOMNode *itemNode = GetItemByIndex(aIndex, curAccChild).get();
            if (itemNode)
              return itemNode;
          }
        }
      }
    }

    nsCOMPtr<nsIAccessible> nextAccChild;
    curAccChild->GetNextSibling(getter_AddRefs(nextAccChild));
    curAccChild.swap(nextAccChild);
  }

  return nsnull;
}
Beispiel #21
0
already_AddRefed<nsIAccessible>
nsAccUtils::GetSelectableContainer(nsIAccessible *aAccessible, PRUint32 aState)
{
  if (!aAccessible)
    return nsnull;

  if (!(aState & nsIAccessibleStates::STATE_SELECTABLE))
    return nsnull;

  nsCOMPtr<nsIAccessibleSelectable> container;
  nsCOMPtr<nsIAccessible> parent, accessible(aAccessible);
  while (!container) {
    accessible->GetParent(getter_AddRefs(parent));

    if (!parent || Role(parent) == nsIAccessibleRole::ROLE_PANE)
      return nsnull;

    container = do_QueryInterface(parent);
    parent.swap(accessible);
  }

  return accessible.forget();
}
Beispiel #22
0
NS_IMETHODIMP nsXULTreeAccessible::GetCachedTreeitemAccessible(PRInt32 aRow, nsITreeColumn* aColumn, nsIAccessible** aAccessible)
{
  *aAccessible = nsnull;

  NS_ASSERTION(mAccessNodeCache, "No accessibility cache for tree");
  NS_ASSERTION(mTree && mTreeView, "Can't get mTree or mTreeView!\n");

  nsCOMPtr<nsITreeColumn> col;
#ifdef MOZ_ACCESSIBILITY_ATK
  col = aColumn;
#endif
  PRInt32 columnIndex = -1;

  if (!col && mTree) {
    nsCOMPtr<nsITreeColumns> cols;
    mTree->GetColumns(getter_AddRefs(cols));
    if (cols)
      cols->GetKeyColumn(getter_AddRefs(col));
  }

  if (col)
     col->GetIndex(&columnIndex);

  nsCOMPtr<nsIAccessNode> accessNode;
  GetCacheEntry(*mAccessNodeCache, (void*)(aRow * kMaxTreeColumns + columnIndex), getter_AddRefs(accessNode));
  if (!accessNode)
  {
    accessNode = new nsXULTreeitemAccessibleWrap(this, mDOMNode, mWeakShell, aRow, col);
    if (! accessNode)
      return NS_ERROR_OUT_OF_MEMORY;
    PutCacheEntry(*mAccessNodeCache, (void*)(aRow * kMaxTreeColumns + columnIndex), accessNode);
  }
  nsCOMPtr<nsIAccessible> accessible(do_QueryInterface(accessNode));
  NS_IF_ADDREF(*aAccessible = accessible);
  return NS_OK;
}
static bool getDragDataImpl(NPObject* npobj, int* eventId, WebDragData* data)
{
    if (!npobj)
        return false;
    if (npobj->_class != npScriptObjectClass)
        return false;

    v8::HandleScope handleScope;
    v8::Handle<v8::Context> context = v8::Context::GetEntered();
    if (context.IsEmpty())
        return false;

    // Get the current WebCore event.
    v8::Handle<v8::Value> currentEvent(getEvent(context));
    Event* event = V8Event::toNative(v8::Handle<v8::Object>::Cast(currentEvent));
    if (!event)
        return false;

    // Check that the given npobj is that event.
    V8NPObject* object = reinterpret_cast<V8NPObject*>(npobj);
    Event* given = V8Event::toNative(object->v8Object);
    if (given != event)
        return false;

    // Check the execution frames are same origin.
    V8Proxy* current = V8Proxy::retrieve(V8Proxy::retrieveFrameForCurrentContext());
    Frame* frame = V8Proxy::retrieveFrame(context);
    if (!current || !V8BindingSecurity::canAccessFrame(V8BindingState::Only(), frame, false))
        return false;

    const EventNames& names(eventNames());
    const AtomicString& eventType(event->type());

    enum DragTargetMouseEventId {
        DragEnterId = 1, DragOverId = 2, DragLeaveId = 3, DropId = 4
    };

    // The event type should be a drag event.
    if (eventType == names.dragenterEvent)
        *eventId = DragEnterId;
    else if (eventType == names.dragoverEvent)
        *eventId = DragOverId;
    else if (eventType == names.dragleaveEvent)
        *eventId = DragLeaveId;
    else if (eventType == names.dropEvent)
        *eventId = DropId;
    else
        return false;

    // Drag events are mouse events and should have a clipboard.
    MouseEvent* me = static_cast<MouseEvent*>(event);
    Clipboard* clipboard = me->clipboard();
    if (!clipboard)
        return false;

    // And that clipboard should be accessible by WebKit policy.
    ClipboardChromium* chrome = static_cast<ClipboardChromium*>(clipboard);
    HashSet<String> accessible(chrome->types());
    if (accessible.isEmpty())
        return false;

    RefPtr<ChromiumDataObject> dataObject(chrome->dataObject());
    if (dataObject && data)
        *data = WebDragData(dataObject);

    return dataObject;
}
Beispiel #24
0
void execution(Commande *commande, Niveau *niveau){
	fixDirectory(commande, niveau);
	insertionString(niveau->history, commande->commande);
	int nbArgument = nbArg(commande);
	int ok = 1;
	int redirect = 1;
	// printw("nb arg : %d\n", nbArgument);
	exceptionProcessing(niveau, commande);
	// Vérifie que la commande ne soit pas vide
	if (strlen(commande->commande) == 0){}
	else
	{
		// Vérifie si la commande est autorisée dans ce niveau
		if (!appartient(premierArg(commande->commande), niveau->charAutorise))
		{
			printw("Commande \"%s\" interdite !!\n", premierArg(commande->commande));
			printw("Liste des commandes autorisées :\n");
			String *temp = niveau->charAutorise->premier;
			printw("\t %s\n", temp->string);
			
			while((temp = temp->suivant) != NULL){
				printw("\t %s\n", temp->string);
			}
		}
		else
		{
			ListeString *listeArg = malloc(sizeof(ListeString));
			buildArgsChain(listeArg, commande);

			// Gestion particulière du cd
			if (!strcmp(substr(commande->commande,0,2), "cd"))
			{
				// Vérifie qu'il n'y a qu'un seul argument après le cd
				if (nbArgument == 1)
				{
					// Vérifie que le dossier visé existe et qu'il n'est pas un fichier et qu'il n'est pas au-dessus de la racine
					if (dirExists(listeArg->premier->string) && accessible(commande))
					{
						// Vérifie que ce n'est pas un fichier 
						if(fileExists(listeArg->premier->string))
							printw("\"%s\" est un fichier !!\n", listeArg->premier->string);
						else{
							chdir(listeArg->premier->string);
							fixDirectory(commande, niveau);
							commande->niveau = commande->niveau + incrementNiveau(commande);
						}
					}else
						printw("Le répertoire \"%s\" n'existe pas !!\n", listeArg->premier->string);
				}else{
					goBackRoot(commande);
				}
			}
			// gestion du pwd
			else if (!strcmp(substr(commande->commande,0,3), "pwd"))
				pwd(commande);
			// Gestion de >>
			else if((redirect = isRedirector(commande)) > 0)
				redirection(niveau, commande, redirect);
			// commandes autres
			else
			{
				printw("%s", exec(listeArg, commande, &(*niveau)));
			}
		}
	}
}
Beispiel #25
0
/*
 * Return true if a file is readable.
 */
static int readable(char *fname)
{
    return accessible(fname, "r");
}
Beispiel #26
0
/* return 1 if action took 1 (or more) moves, 0 if error or aborted */
static int
doengrave_core(const struct nh_cmd_arg *arg, int auto_elbereth)
{
    boolean dengr = FALSE;      /* TRUE if we wipe out the current engraving */
    boolean doblind = FALSE;    /* TRUE if engraving blinds the player */
    boolean doknown = FALSE;    /* TRUE if we identify the stylus */
    boolean doknown_after = FALSE;      /* TRUE if we identify the stylus after
                                           successfully engraving. */
    boolean eow = FALSE;        /* TRUE if we are overwriting oep */
    boolean jello = FALSE;      /* TRUE if we are engraving in slime */
    boolean ptext = TRUE;       /* TRUE if we must prompt for engrave text */
    boolean teleengr = FALSE;   /* TRUE if we move the old engraving */
    boolean zapwand = FALSE;    /* TRUE if we remove a wand charge */
    xchar type = DUST;          /* Type of engraving made */
    const char *buf;            /* Buffer for final/poly engraving text */
    const char *ebuf;           /* Buffer for initial engraving text */
    const char *qbuf;           /* Buffer for query text */
    const char *post_engr_text; /* Text displayed after engraving prompt */
    const char *everb;          /* Present tense of engraving type */
    const char *eloc;           /* Where the engraving is (ie dust/floor/...) */
    const char *esp;            /* Iterator over ebuf; mostly handles spaces */
    char *sp;                   /* Ditto for mutable copies of ebuf */
    int len;                    /* # of nonspace chars of new engraving text */
    int maxelen;                /* Max allowable length of engraving text */
    int helpless_time;          /* Temporary for calculating helplessness */
    const char *helpless_endmsg;/* Temporary for helpless end message */
    struct engr *oep = engr_at(level, u.ux, u.uy);
    struct obj *otmp;
    int cramps = 0;             /* How much your hand is cramping up from writing */

    /* The current engraving */
    const char *writer;

    buf = "";
    ebuf = "";
    post_engr_text = "";
    maxelen = 255; /* same value as in 3.4.3 */

    if (is_demon(youmonst.data) || youmonst.data->mlet == S_VAMPIRE)
        type = ENGR_BLOOD;

    /* Can the adventurer engrave at all? */

    if (Engulfed) {
        if (is_animal(u.ustuck->data)) {
            pline("What would you write?  \"Jonah was here\"?");
            return 0;
        } else if (is_whirly(u.ustuck->data)) {
            pline("You can't reach the %s.", surface(u.ux, u.uy));
            return 0;
        } else
            jello = TRUE;
    } else if (is_lava(level, u.ux, u.uy)) {
        pline("You can't write on the lava!");
        return 0;
    } else if (Underwater) {
        pline("You can't write underwater!");
        return 0;
    } else if (is_pool(level, u.ux, u.uy) ||
               IS_FOUNTAIN(level->locations[u.ux][u.uy].typ)) {
        pline("You can't write on the water!");
        return 0;
    }
    if (Is_airlevel(&u.uz) || Is_waterlevel(&u.uz) /* in bubble */ ) {
        pline("You can't write in thin air!");
        return 0;
    } else if (u.utrap && u.utraptype == TT_INFLOOR) {
        pline ("You can't write on the %s while embedded therein.",
               surface(u.ux, u.uy));
        return 0;
    } else if (u.utrap && u.utraptype == TT_ICEBLOCK) {
        pline("You cannot write on the %s while embedded in a block of %s.",
              surface(u.ux,u.uy),
              (level->locations[u.ux][u.uy].typ == ICE) ? "it" : "ice");
        return 0;
    } else if (!accessible(level, u.ux, u.uy)) {
        /* stone, tree, wall, secret corridor, pool, lava, bars */
        pline("You can't write here.");
        return 0;
    }
    if (cantwield(youmonst.data)) {
        pline("You can't even hold anything!");
        return 0;
    }
    if (check_capacity(NULL))
        return 0;

    /* One may write with finger, or weapon, or wand, or..., or... Edited by
       GAN 10/20/86 so as not to change weapon wielded. */

    otmp = getargobj(arg, styluses, "write with");
    if (!otmp)
        return 0;       /* otmp == &zeroobj if fingers */

    if (otmp == &zeroobj)
        writer = makeplural(body_part(FINGER));
    else
        writer = xname(otmp);

    /* There's no reason you should be able to write with a wand while both
       your hands are tied up. */
    if (!freehand() && otmp != uwep && !otmp->owornmask) {
        pline("You have no free %s to write with!", body_part(HAND));
        return 0;
    }

    if (jello) {
        pline("You tickle %s with your %s.", mon_nam(u.ustuck), writer);
        pline("Your message dissolves...");
        return 0;
    }
    if (otmp->oclass != WAND_CLASS && !can_reach_floor()) {
        pline("You can't reach the %s!", surface(u.ux, u.uy));
        return 0;
    }
    if (IS_ALTAR(level->locations[u.ux][u.uy].typ)) {
        pline("You make a motion towards the altar with your %s.", writer);
        altar_wrath(u.ux, u.uy);
        return 0;
    }
    if (IS_GRAVE(level->locations[u.ux][u.uy].typ)) {
        if (otmp == &zeroobj) { /* using only finger */
            pline("You would only make a small smudge on the %s.",
                  surface(u.ux, u.uy));
            return 0;
        } else if (!level->locations[u.ux][u.uy].disturbed) {
            pline("You disturb the undead!");
            level->locations[u.ux][u.uy].disturbed = 1;
            makemon(&mons[PM_GHOUL], level, u.ux, u.uy, NO_MM_FLAGS);
            return 1;
        }
    }

    /* SPFX for items */

    switch (otmp->oclass) {
    default:
    case AMULET_CLASS:
    case CHAIN_CLASS:
    case POTION_CLASS:
    case COIN_CLASS:
        break;

    case RING_CLASS:
        /* "diamond" rings and others should work */
    case GEM_CLASS:
        /* diamonds & other hard gems should work */
        if (objects[otmp->otyp].oc_tough) {
            type = ENGRAVE;
            break;
        }
        break;

    case ARMOR_CLASS:
        if (is_boots(otmp)) {
            type = DUST;
            break;
        }
        /* fall through */
        /* Objects too large to engrave with */
    case BALL_CLASS:
    case ROCK_CLASS:
        pline("You can't engrave with such a large object!");
        ptext = FALSE;
        break;

        /* Objects too silly to engrave with */
    case FOOD_CLASS:
    case SCROLL_CLASS:
    case SPBOOK_CLASS:
        pline("Your %s would get %s.", xname(otmp),
              is_ice(level, u.ux, u.uy) ? "all frosty" : "too dirty");
        ptext = FALSE;
        break;

    case RANDOM_CLASS: /* This should mean fingers */
        break;

        /* The charge is removed from the wand before prompting for the
           engraving text, because all kinds of setup decisions and
           pre-engraving messages are based upon knowing what type of engraving 
           the wand is going to do.  Also, the player will have potentially
           seen "You wrest .." message, and therefore will know they are using
           a charge. */
    case WAND_CLASS:
        if (zappable(otmp)) {
            check_unpaid(otmp);
            zapwand = TRUE;
            if (Levitation)
                ptext = FALSE;

            switch (otmp->otyp) {
                /* DUST wands */
            default:
                break;

                /* NODIR wands */
            case WAN_LIGHT:
            case WAN_SECRET_DOOR_DETECTION:
            case WAN_CREATE_MONSTER:
            case WAN_WISHING:
            case WAN_ENLIGHTENMENT:
                zapnodir(otmp);
                break;

                /* IMMEDIATE wands */
                /* If wand is "IMMEDIATE", remember to affect the previous
                   engraving even if turning to dust. */
            case WAN_STRIKING:
                post_engr_text =
                    "The wand unsuccessfully fights your attempt to write!";
                doknown_after = TRUE;
                break;
            case WAN_SLOW_MONSTER:
                if (!Blind) {
                    post_engr_text = msgprintf("The bugs on the %s slow down!",
                                               surface(u.ux, u.uy));
                    doknown_after = TRUE;
                }
                break;
            case WAN_SPEED_MONSTER:
                if (!Blind) {
                    post_engr_text = msgprintf("The bugs on the %s speed up!",
                                               surface(u.ux, u.uy));
                    doknown_after = TRUE;
                }
                break;
            case WAN_POLYMORPH:
                if (oep) {
                    if (!Blind) {
                        type = (xchar) 0;       /* random */
                        buf = random_engraving(rng_main);
                        doknown = TRUE;
                    }
                    dengr = TRUE;
                }
                break;
            case WAN_NOTHING:
            case WAN_UNDEAD_TURNING:
            case WAN_OPENING:
            case WAN_LOCKING:
            case WAN_PROBING:
                break;

                /* RAY wands */
            case WAN_MAGIC_MISSILE:
                ptext = TRUE;
                if (!Blind) {
                    post_engr_text = msgprintf(
                        "The %s is riddled by bullet holes!",
                        surface(u.ux, u.uy));
                    doknown_after = TRUE;
                }
                break;

                /* can't tell sleep from death - Eric Backus */
            case WAN_SLEEP:
            case WAN_DEATH:
                if (!Blind) {
                    post_engr_text = msgprintf(
                        "The bugs on the %s stop moving!", surface(u.ux, u.uy));
                }
                break;

            case WAN_COLD:
                if (!Blind) {
                    post_engr_text = "A few ice cubes drop from the wand.";
                    doknown_after = TRUE;
                }
                if (!oep || (oep->engr_type != BURN))
                    break;
            case WAN_CANCELLATION:
            case WAN_MAKE_INVISIBLE:
                if (oep && oep->engr_type != HEADSTONE) {
                    if (!Blind)
                        pline("The engraving on the %s vanishes!",
                              surface(u.ux, u.uy));
                    dengr = TRUE;
                }
                break;
            case WAN_TELEPORTATION:
                if (oep && oep->engr_type != HEADSTONE) {
                    if (!Blind)
                        pline("The engraving on the %s vanishes!",
                              surface(u.ux, u.uy));
                    teleengr = TRUE;
                }
                break;

                /* type = ENGRAVE wands */
            case WAN_DIGGING:
                ptext = TRUE;
                type = ENGRAVE;
                if (!objects[otmp->otyp].oc_name_known) {
                    if (flags.verbose)
                        pline("This %s is a wand of digging!", xname(otmp));
                    doknown = TRUE;
                }
                if (!Blind) {
                    post_engr_text =
                        IS_GRAVE(level->locations[u.ux][u.uy].typ) ?
                        "Chips fly out from the headstone." :
                        is_ice(level, u.ux, u.uy) ?
                        "Ice chips fly up from the ice surface!" :
                        (level->locations[u.ux][u.uy].typ == DRAWBRIDGE_DOWN) ?
                        "Splinters fly up from the bridge." :
                        "Gravel flies up from the floor.";
                }
                else
                    post_engr_text = "You hear drilling!";
                break;

                /* type = BURN wands */
            case WAN_FIRE:
                ptext = TRUE;
                type = BURN;
                if (!objects[otmp->otyp].oc_name_known) {
                    if (flags.verbose)
                        pline("This %s is a wand of fire!", xname(otmp));
                    doknown = TRUE;
                }
                post_engr_text = Blind ?
                    "You feel the wand heat up." :
                    "Flames fly from the wand.";
                break;
            case WAN_LIGHTNING:
                ptext = TRUE;
                type = BURN;
                if (!objects[otmp->otyp].oc_name_known) {
                    if (flags.verbose)
                        pline("This %s is a wand of lightning!", xname(otmp));
                    doknown = TRUE;
                }
                if (!Blind) {
                    post_engr_text = "Lightning arcs from the wand.";
                    doblind = TRUE;
                } else
                    post_engr_text = "You hear crackling!";
                break;
            
                /* type = MARK wands */
                /* type = ENGR_BLOOD wands */
            }
        } else /* end if zappable */ if (!can_reach_floor()) {
                pline("You can't reach the %s!", surface(u.ux, u.uy));
                /* If it's a wrestable wand, the player wasted a turn trying. */
                if (wrestable(otmp))
                    return 1;
                else
                    return 0;
            }
        break;
    
    case WEAPON_CLASS:
        if (is_blade(otmp)) {
            if ((int)otmp->spe > -3)
                type = ENGRAVE;
            else
                pline("Your %s too dull for engraving.", aobjnam(otmp, "are"));
        }
        break;

    case TOOL_CLASS:
        if (otmp == ublindf) {
            pline("That is a bit difficult to engrave with, don't you think?");
            return 0;
        }
        switch (otmp->otyp) {
        case MAGIC_MARKER:
            if (otmp->spe <= 0)
                pline("Your marker has dried out.");
            else
                type = MARK;
            break;
        case TOWEL:
            /* Can't really engrave with a towel */
            ptext = FALSE;
            if (oep)
                if ((oep->engr_type == DUST) || (oep->engr_type == ENGR_BLOOD)
                    || (oep->engr_type == MARK)) {
                    if (!Blind)
                        pline("You wipe out the message here.");
                    else
                        pline("Your %s %s %s.", xname(otmp),
                              otense(otmp, "get"),
                              is_ice(level, u.ux, u.uy) ? "frosty" : "dusty");
                    dengr = TRUE;
                } else
                    pline("Your %s can't wipe out this engraving.",
                          xname(otmp));
            else
                pline("Your %s %s %s.", xname(otmp), otense(otmp, "get"),
                      is_ice(level, u.ux, u.uy) ? "frosty" : "dusty");
            break;
        default:
            break;
        }
        break;

    case VENOM_CLASS:
    case ILLOBJ_CLASS:
        impossible("You're engraving with an illegal object!");
        break;
    }

    if (IS_GRAVE(level->locations[u.ux][u.uy].typ)) {
        if (type == ENGRAVE || type == 0)
            type = HEADSTONE;
        else {
            /* ensures the "cannot wipe out" case */
            type = DUST;
            dengr = FALSE;
            teleengr = FALSE;
            buf = "";
        }
    }

    /* End of implement setup */

    /* If engraving with wand, blow up the wand if cursed+unskilled */
    if (zapwand && !getwandlevel(&youmonst, otmp)) {
        backfire(otmp);
        exercise(A_STR, FALSE);
        return 1;
    }

    /* Identify stylus */
    if (doknown) {
        makeknown(otmp->otyp);
        more_experienced(0, 10);
    }

    if (teleengr) {
        rloc_engr(oep);
        oep = NULL;
    }

    if (dengr) {
        del_engr(oep, level);
        oep = NULL;
    }

    /* Something has changed the engraving here */
    if (*buf) {
        make_engr_at(level, u.ux, u.uy, buf, moves, type);
        pline("The engraving now reads: \"%s\".", buf);
        ptext = FALSE;
    }

    if (zapwand && (otmp->spe < 0)) {
        pline("%s %sturns to dust.", The(xname(otmp)),
              Blind ? "" : "glows violently, then ");
        if (!IS_GRAVE(level->locations[u.ux][u.uy].typ))
            pline("You are not going to get anywhere trying to write in the "
                  "%s with your dust.",
                  is_ice(level, u.ux, u.uy) ? "frost" : "dust");
        useup(otmp);
        ptext = FALSE;
    }

    if (!ptext) {       /* Early exit for some implements. */
        if (otmp->oclass == WAND_CLASS && !can_reach_floor())
            pline("You can't reach the %s!", surface(u.ux, u.uy));
        return 1;
    }

    /* Special effects should have deleted the current engraving (if possible)
       by now. */

    if (oep) {
        char c = 'n';

        /* Give player the choice to add to engraving. */

        if (type == HEADSTONE) {
            /* no choice, only append */
            c = 'y';
        } else if ((type == oep->engr_type) &&
                   (!Blind || (oep->engr_type == BURN) ||
                    (oep->engr_type == ENGR_LIGHTS) ||
                    (oep->engr_type == ENGRAVE))) {
            if (auto_elbereth)
                c = 'y';
            else
                c = yn_function("Do you want to add to the current engraving?",
                                ynqchars, 'y');
            if (c == 'q') {
                pline("Never mind.");
                return 0;
            }
        }

        if (c == 'n' || Blind) {

            if ((oep->engr_type == DUST) || (oep->engr_type == ENGR_BLOOD) ||
                (oep->engr_type == MARK)) {
                if (!Blind) {
                    pline("You wipe out the message that was %s here.",
                          ((oep->engr_type == DUST) ? "written in the dust" :
                           ((oep->engr_type == ENGR_BLOOD) ?
                            "scrawled in blood" : "written")));
                    del_engr(oep, level);
                    oep = NULL;
                } else
                    /* Don't delete engr until after we *know* we're engraving
                       */
                    eow = TRUE;
            } else if ((type == DUST) || (type == MARK) ||
                       (type == ENGR_BLOOD)) {
                pline("You cannot wipe out the message that is %s the %s here.",
                      oep->engr_type == BURN ? (is_ice(level, u.ux, u.uy) ?
                                                "melted into" : "burned into") :
                      "engraved in",
                      surface(u.ux, u.uy));
                return 1;
            } else if (oep->engr_type == ENGR_LIGHTS) {
                if (type == BURN) {
                    pline("The colored lights short out and go dark.");
                    eow = TRUE;
                } else {
                    pline("The colored lights distract you, and nothing "
                          "really gets written.");
                    return 1;
                }
            } else if ((type != oep->engr_type) || (c == 'n')) {
                if (!Blind || can_reach_floor())
                    pline("You will overwrite the current message.");
                eow = TRUE;
            }
        }
    }

    eloc = surface(u.ux, u.uy);
    switch (type) {
    default:
        everb = (oep &&
                 !eow ? "add to the weird writing on" : "write strangely on");
        break;
    case DUST:
        everb = (oep && !eow ? "add to the writing in" : "write in");
        eloc = is_ice(level, u.ux, u.uy) ? "frost" : "dust";
        break;
    case HEADSTONE:
        everb = (oep && !eow ? "add to the epitaph on" : "engrave on");
        break;
    case ENGRAVE:
        everb = (oep && !eow ? "add to the engraving in" : "engrave in");
        break;
    case BURN:
        everb = (oep && !eow ? (is_ice(level, u.ux, u.uy) ?
                                "add to the text melted into" :
                                "add to the text burned into") :
                 (is_ice(level, u.ux, u.uy) ? "melt into" : "burn into"));
        break;
    case MARK:
        everb = (oep && !eow ? "add to the graffiti on" : "scribble on");
        break;
    case ENGR_BLOOD:
        everb = (oep && !eow ? "add to the scrawl on" : "scrawl on");
        break;
    case ENGR_LIGHTS:
        /* This probably can't actually happen. */
        everb = (oep && !eow ? "add to the writing in" : "write in");
        eloc  = (oep && !eow ? "the colored lights"    : "colored lights");
        break;
    }

    /* Tell adventurer what is going on */
    if (otmp != &zeroobj)
        pline("You %s the %s with %s.", everb, eloc, doname(otmp));
    else
        pline("You %s the %s with your %s.", everb, eloc,
              makeplural(body_part(FINGER)));

    /* Prompt for engraving! */
    qbuf = msgprintf("What do you want to %s the %s here?", everb, eloc);
    if (auto_elbereth)
        ebuf = "Elbereth";
    else
        ebuf = getarglin(arg, qbuf);

    /* Count the actual # of chars engraved not including spaces */
    len = strlen(ebuf);
    for (esp = ebuf; *esp; esp++)
        if (isspace(*esp))
            len -= 1;

    if (len == 0 || strchr(ebuf, '\033')) {
        if (zapwand) {
            if (!Blind)
                pline("%s, then %s.", Tobjnam(otmp, "glow"),
                      otense(otmp, "fade"));
            return 1;
        } else {
            pline("Never mind.");
            if (otmp && otmp->oclass == WAND_CLASS && wrestable(otmp))
                return 1;       /* disallow zero turn wrest */
            else
                return 0;
        }
    }

    /* A single `x' is the traditional signature of an illiterate person */
    if (len != 1 || (!strchr(ebuf, 'x') && !strchr(ebuf, 'X')))
        break_conduct(conduct_illiterate);

    /* Degrade any existing text: */
    u_wipe_engr(rnd(3));

    /* Mix up the new text we are engraving if surface or state of mind is
       unsound. Note: this won't add or remove any spaces. */
    char ebuf_copy[strlen(ebuf) + 1];
    strcpy(ebuf_copy, ebuf);
    for (sp = ebuf_copy; *sp; sp++) {
        if (isspace(*sp))
            continue;
        /* NetHack Fourk balance adjustment:  writing Elbereth a whole lot of
         * times makes it harder to continue writing anything successfully.  */
        if (!rn2((((type == DUST || type == ENGR_BLOOD)) ? 150
                  : (type == ENGRAVE) ? 350 : 1500)
                 * u.ulevel / (1 + u.uconduct[conduct_elbereth])) ||
            (Blind && !rn2(11)) || (Confusion && !rn2(7)) ||
            (Stunned && !rn2(4)) || (Hallucination && !rn2(2))) {
            *sp = ' ' + rnd(96 - 2);    /* ASCII '!' thru '~' (excludes ' ' and 
                                           DEL) */
            cramps++;
        }
    }
    if ((Blind || Confusion || Hallucination || Stunned) && (cramps > 0))
        pline("You have difficulty writing in your present condition.");
    else if (cramps > 6)
        pline("Your entire %s is cramping up.  You simply cannot write any more right now.", body_part(ARM));
    else if (cramps > 4)
        pline("Your %s is cramping up very severely.", body_part(HAND));
    else if (cramps > 2)
        pline("Your %s is really cramping up.", body_part(HAND));
    else if (cramps > 1)
        pline("Your %s is cramping up.", body_part(HAND));
    else if (cramps > 0)
        pline("Your writing %s is beginning to cramp.", body_part(HAND));

    /* Previous engraving is overwritten */
    if (eow) {
        del_engr(oep, level);
        oep = NULL;
    }

    /* Figure out how long it took to engrave, and if player has engraved too
       much. */
    helpless_time = len / 10;
    helpless_endmsg = NULL;
    switch (type) {
    default:
        helpless_endmsg = "You finish your weird engraving.";
        break;
    case DUST:
        helpless_endmsg = "You finish writing in the dust.";
        break;
    case HEADSTONE:
    case ENGRAVE:
        if ((otmp->oclass == WEAPON_CLASS) &&
            ((otmp->otyp != ATHAME) || otmp->cursed)) {
            helpless_time = len;
            maxelen = ((otmp->spe + 3) * 2) + 1;
            /* -2 = 3, -1 = 5, 0 = 7, +1 = 9, +2 = 11 Note: this does not allow 
               a +0 anything (except an athame) to engrave "Elbereth" all at
               once.  However, you could now engrave "Elb", then "ere", then
               "th". */
            if (otmp->quan > 1L)
                otmp = splitobj(otmp, 1L);
            pline("Your %s dull.", aobjnam(otmp, "get"));
            if (otmp->unpaid) {
                struct monst *shkp = shop_keeper(level, *u.ushops);

                if (shkp) {
                    pline("You damage it, you pay for it!");
                    bill_dummy_object(otmp);
                }
            }
            if (len > maxelen) {
                helpless_time = maxelen;
                otmp->spe = -3;
            } else if (len > 1)
                otmp->spe -= len >> 1;
            else
                otmp->spe -= 1; /* Prevent infinite engraving */
        } else if ((otmp->oclass == RING_CLASS) || (otmp->oclass == GEM_CLASS))
bool CRestrictedObject::accessible			(const Fvector &position) const
{
	START_PROFILE("Restricted Object/Accessible");
	return						(accessible(position,EPS_L));
	STOP_PROFILE;
}
Beispiel #28
0
/*
 * Return true if the specified file can be opened for write access.
 */
static int writable(char *fname)
{
    return accessible(fname, "a");
}
Beispiel #29
0
/*
 * Let's do it.  We end up doing a lot of file opening and closing,
 * but what do we care?  This application isn't run constantly.
 */
int main(int argc, const char * const argv[])
{
    apr_file_t *fpw = NULL;
    char record[MAX_STRING_LEN];
    char line[MAX_STRING_LEN];
    char *password = NULL;
    char *pwfilename = NULL;
    char *user = NULL;
    char tn[] = "htpasswd.tmp.XXXXXX";
    char *dirname;
    char *scratch, cp[MAX_STRING_LEN];
    int found = 0;
    int i;
    int alg = ALG_APMD5;
    int mask = 0;
    apr_pool_t *pool;
    int existing_file = 0;
#if APR_CHARSET_EBCDIC
    apr_status_t rv;
    apr_xlate_t *to_ascii;
#endif

    apr_app_initialize(&argc, &argv, NULL);
    atexit(terminate);
    apr_pool_create(&pool, NULL);
    apr_file_open_stderr(&errfile, pool);

#if APR_CHARSET_EBCDIC
    rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool);
    if (rv) {
        apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv);
        exit(1);
    }
    rv = apr_SHA1InitEBCDIC(to_ascii);
    if (rv) {
        apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv);
        exit(1);
    }
    rv = apr_MD5InitEBCDIC(to_ascii);
    if (rv) {
        apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv);
        exit(1);
    }
#endif /*APR_CHARSET_EBCDIC*/

    check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);


#if defined(WIN32) || defined(NETWARE)
    if (alg == ALG_CRYPT) {
        alg = ALG_APMD5;
        apr_file_printf(errfile, "Automatically using MD5 format." NL);
    }
#endif

#if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
    if (alg == ALG_PLAIN) {
        apr_file_printf(errfile,"Warning: storing passwords as plain text "
                        "might just not work on this platform." NL);
    }
#endif

    /*
     * Only do the file checks if we're supposed to frob it.
     */
    if (!(mask & APHTP_NOFILE)) {
        existing_file = exists(pwfilename, pool);
        if (existing_file) {
            /*
             * Check that this existing file is readable and writable.
             */
            if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) {
                apr_file_printf(errfile, "%s: cannot open file %s for "
                                "read/write access" NL, argv[0], pwfilename);
                exit(ERR_FILEPERM);
            }
        }
        else {
            /*
             * Error out if -c was omitted for this non-existant file.
             */
            if (!(mask & APHTP_NEWFILE)) {
                apr_file_printf(errfile,
                        "%s: cannot modify file %s; use '-c' to create it" NL,
                        argv[0], pwfilename);
                exit(ERR_FILEPERM);
            }
            /*
             * As it doesn't exist yet, verify that we can create it.
             */
            if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) {
                apr_file_printf(errfile, "%s: cannot create file %s" NL,
                                argv[0], pwfilename);
                exit(ERR_FILEPERM);
            }
        }
    }

    /*
     * All the file access checks (if any) have been made.  Time to go to work;
     * try to create the record for the username in question.  If that
     * fails, there's no need to waste any time on file manipulations.
     * Any error message text is returned in the record buffer, since
     * the mkrecord() routine doesn't have access to argv[].
     */
    if (!(mask & APHTP_DELUSER)) {
        i = mkrecord(user, record, sizeof(record) - 1,
                     password, alg);
        if (i != 0) {
            apr_file_printf(errfile, "%s: %s" NL, argv[0], record);
            exit(i);
        }
        if (mask & APHTP_NOFILE) {
            printf("%s" NL, record);
            exit(0);
        }
    }

    /*
     * We can access the files the right way, and we have a record
     * to add or update.  Let's do it..
     */
    if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
        apr_file_printf(errfile, "%s: could not determine temp dir" NL,
                        argv[0]);
        exit(ERR_FILEPERM);
    }
    dirname = apr_psprintf(pool, "%s/%s", dirname, tn);

    if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
        apr_file_printf(errfile, "%s: unable to create temporary file %s" NL,
                        argv[0], dirname);
        exit(ERR_FILEPERM);
    }

    /*
     * If we're not creating a new file, copy records from the existing
     * one to the temporary file until we find the specified user.
     */
    if (existing_file && !(mask & APHTP_NEWFILE)) {
        if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
                          APR_OS_DEFAULT, pool) != APR_SUCCESS) {
            apr_file_printf(errfile, "%s: unable to read file %s" NL,
                            argv[0], pwfilename);
            exit(ERR_FILEPERM);
        }
        while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
            char *colon;

            strcpy(cp, line);
            scratch = cp;
            while (apr_isspace(*scratch)) {
                ++scratch;
            }

            if (!*scratch || (*scratch == '#')) {
                putline(ftemp, line);
                continue;
            }
            /*
             * See if this is our user.
             */
            colon = strchr(scratch, ':');
            if (colon != NULL) {
                *colon = '\0';
            }
            else {
                /*
                 * If we've not got a colon on the line, this could well
                 * not be a valid htpasswd file.
                 * We should bail at this point.
                 */
                apr_file_printf(errfile, "%s: The file %s does not appear "
                                         "to be a valid htpasswd file." NL,
                                argv[0], pwfilename);
                apr_file_close(fpw);
                exit(ERR_INVALID);
            }
            if (strcmp(user, scratch) != 0) {
                putline(ftemp, line);
                continue;
            }
            else {
                if (!(mask & APHTP_DELUSER)) {
                    /* We found the user we were looking for.
                     * Add him to the file.
                    */
                    apr_file_printf(errfile, "Updating ");
                    putline(ftemp, record);
                    found++;
                }
                else {
                    /* We found the user we were looking for.
                     * Delete them from the file.
                     */
                    apr_file_printf(errfile, "Deleting ");
                    found++;
                }
            }
        }
        apr_file_close(fpw);
    }
    if (!found && !(mask & APHTP_DELUSER)) {
        apr_file_printf(errfile, "Adding ");
        putline(ftemp, record);
    }
    else if (!found && (mask & APHTP_DELUSER)) {
        apr_file_printf(errfile, "User %s not found" NL, user);
        exit(0);
    }
    apr_file_printf(errfile, "password for user %s" NL, user);

    /* The temporary file has all the data, just copy it to the new location.
     */
    if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
        APR_SUCCESS) {
        apr_file_printf(errfile, "%s: unable to update file %s" NL,
                        argv[0], pwfilename);
        exit(ERR_FILEPERM);
    }
    apr_file_close(ftemp);
    return 0;
}
Beispiel #30
0
/*
 * Is (x,y) a good position of mtmp?  If mtmp is NULL, then is (x,y) good
 * for an object?
 *
 * This function will only look at mtmp->mdat, so makemon, mplayer, etc can
 * call it to generate new monster positions with fake monster structures.
 *
 * This function might be called during level generation, so should return
 * deterministic results.
 */
boolean
goodpos(struct level *lev, int x, int y, struct monst *mtmp, unsigned gpflags)
{
    const struct permonst *mdat = NULL;
    boolean ignorewater = ((gpflags & MM_IGNOREWATER) != 0);

    if (!isok(x, y))
        return FALSE;

    /* in many cases, we're trying to create a new monster, which can't go on
       top of the player or any existing monster. however, occasionally we are
       relocating engravings or objects, which could be co-located and thus get
       restricted a bit too much. oh well. */
    if (mtmp != &youmonst && x == u.ux && y == u.uy &&
        (!u.usteed || mtmp != u.usteed) && !(gpflags & MM_IGNOREMONST))
        return FALSE;

    if (mtmp) {
        struct monst *mtmp2 = (gpflags & MM_IGNOREMONST) ?
            NULL : m_at(lev, x, y);

        /* Be careful with long worms.  A monster may be placed back in its own
           location.  Normally, if m_at() returns the same monster that we're
           trying to place, the monster is being placed in its own location.
           However, that is not correct for worm segments, because all the
           segments of the worm return the same m_at(). Actually we overdo the
           check a little bit--a worm can't be placed in its own location,
           period.  If we just checked for mtmp->mx != x || mtmp->my != y, we'd
           miss the case where we're called to place the worm segment and the
           worm's head is at x,y. */
        if (mtmp2 && (mtmp2 != mtmp || mtmp->wormno))
            return FALSE;

        mdat = mtmp->data;
        if (is_pool(lev, x, y) && !ignorewater) {
            if (mtmp == &youmonst)
                return !!(HLevitation || Flying || Wwalking || Swimming ||
                          Amphibious);
            else
                return (is_flyer(mdat) || is_swimmer(mdat) || is_clinger(mdat));
        } else if (mdat->mlet == S_EEL && !ignorewater) {
            return FALSE;
        } else if (is_lava(lev, x, y)) {
            if (mtmp == &youmonst)
                return ! !HLevitation;
            else
                return is_flyer(mdat) || likes_lava(mdat);
        }
        if (IS_STWALL(lev->locations[x][y].typ)) {
            if (passes_walls(mdat) && may_passwall(lev, x, y))
                return TRUE;
            if (gpflags & MM_CHEWROCK && may_dig(lev, x, y))
                return TRUE;
            if (amorphous(mdat) && closed_door(lev, x, y))
                return TRUE;
        }
    }
    if (!accessible(lev, x, y)) {
        if (!(is_pool(lev, x, y) && ignorewater))
            return FALSE;
    }

/*  If I understand correctly, this may now be redundant, I think, maybe:
    if (!(gpflags & MM_IGNOREDOORS) && closed_door(lev, x, y) &&
        (!mdat || !amorphous(mdat)))
        return FALSE;
*/
    if (!(gpflags & MM_IGNOREDOORS) && sobj_at(BOULDER, lev, x, y) &&
        (!mdat || !throws_rocks(mdat)))
        return FALSE;
    return TRUE;
}