What defines "Friendly territory?"

It's complicated.

Fortify/Sleep/Alert - You can do this anywhere. This does two things. First, you are not prompted to move the unit on future turns unless an enemy unit shows up nearby. Second, melee, archer, and gunpowder units receive a defensive bonus.

Heal - Land units can heal anywhere, though they heal faster in your/allied city states territory. Naval units only heal if they are within the borders of a civilization (including city states) you are not at war with, unless the naval unit has the supply promotion, which allows the promoted naval unit to heal anywhere.

Upgrade - You can only upgrade units in your territory (and maybe allied city states)