public function executeAcquireLease(DrydockResource $resource, DrydockLease $lease) { $key = Filesystem::readRandomCharacters(12); $ports = $resource->getAttribute('ports', array()); for ($ii = 2000;; $ii++) { if (empty($ports[$ii])) { $ports[$ii] = $lease->getID(); $port = $ii; break; } } $resource->setAttribute('ports', $ports); $resource->save(); $host = $resource->getAttribute('host'); $lease->setAttribute('port', $port); $lease->setAttribute('key', $key); $lease->save(); $config = <<<EOCONFIG Listen *:{$port} <VirtualHost *:{$port}> DocumentRoot /opt/drydock/webroot/{$key}/ ServerName {$host} </VirtualHost> EOCONFIG; $cmd = $this->getInterface($resource, $lease, 'command'); $cmd->execx(<<<EOSETUP sudo mkdir -p %s && sudo sh -c %s && sudo /etc/init.d/httpd restart EOSETUP , "/opt/drydock/webroot/{$key}/", csprintf('echo %s > %s', $config, "/etc/httpd/conf.d/drydock-{$key}.conf")); $lease->setAttribute('uri', "http://{$host}:{$port}/"); $lease->save(); }
public function save() { if (!$this->verificationCode) { $this->setVerificationCode(Filesystem::readRandomCharacters(24)); } return parent::save(); }
public function save() { if (!$this->mailKey) { $this->mailKey = Filesystem::readRandomCharacters(20); } return parent::save(); }
/** * Writes file data into Amazon S3. */ public function writeFile($data, array $params) { $s3 = $this->newS3API(); // Generate a random name for this file. We add some directories to it // (e.g. 'abcdef123456' becomes 'ab/cd/ef123456') to make large numbers of // files more browsable with web/debugging tools like the S3 administration // tool. $seed = Filesystem::readRandomCharacters(20); $parts = array(); $parts[] = 'phabricator'; $instance_name = PhabricatorEnv::getEnvConfig('cluster.instance'); if (strlen($instance_name)) { $parts[] = $instance_name; } $parts[] = substr($seed, 0, 2); $parts[] = substr($seed, 2, 2); $parts[] = substr($seed, 4); $name = implode('/', $parts); AphrontWriteGuard::willWrite(); $profiler = PhutilServiceProfiler::getInstance(); $call_id = $profiler->beginServiceCall(array('type' => 's3', 'method' => 'putObject')); $s3->setParametersForPutObject($name, $data)->resolve(); $profiler->endServiceCall($call_id, array()); return $name; }
public function save() { if (!$this->getAccountSecret()) { $this->setAccountSecret(Filesystem::readRandomCharacters(32)); } return parent::save(); }
public function save() { if (!$this->getMailKey()) { $this->setMailKey(Filesystem::readRandomCharacters(20)); } return parent::save(); }
public static function initializeNewSMS($body) { // NOTE: these values will be updated to correct values when the // SMS is sent for the first time. In particular, the ProviderShortName // and ProviderSMSID are totally garbage data before a send it attempted. return id(new PhabricatorSMS())->setBody($body)->setSendStatus(PhabricatorSMS::STATUS_UNSENT)->setProviderShortName(PhabricatorSMS::SHORTNAME_PLACEHOLDER)->setProviderSMSID(Filesystem::readRandomCharacters(40)); }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession($viewer, $this->getRequest(), '/'); // Ideally we'd like to verify this, but it's fine to leave it unguarded // for now and verifying it would need some Ajax junk or for the user to // click a button or similar. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $old_token = id(new PhabricatorConduitCertificateToken())->loadOneWhere('userPHID = %s', $viewer->getPHID()); if ($old_token) { $old_token->delete(); } $token = id(new PhabricatorConduitCertificateToken())->setUserPHID($viewer->getPHID())->setToken(Filesystem::readRandomCharacters(40))->save(); unset($unguarded); $pre_instructions = pht('Copy and paste this token into the prompt given to you by ' . '`arc install-certificate`'); $post_instructions = pht('After you copy and paste this token, `arc` will complete ' . 'the certificate install process for you.'); Javelin::initBehavior('select-on-click'); $form = id(new AphrontFormView())->setUser($viewer)->appendRemarkupInstructions($pre_instructions)->appendChild(id(new AphrontFormTextAreaControl())->setLabel(pht('Token'))->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)->setReadonly(true)->setSigil('select-on-click')->setValue($token->getToken()))->appendRemarkupInstructions($post_instructions); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('Install Certificate')); $crumbs->setBorder(true); $object_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Certificate Token'))->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setForm($form); $title = pht('Certificate Install Token'); $header = id(new PHUIHeaderView())->setHeader($title); $view = id(new PHUITwoColumnView())->setHeader($header)->setFooter($object_box); return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild($view); }
/** * Write file data into S3. * @task impl */ public function writeFile($data, array $params) { $s3 = $this->newS3API(); $name = 'phabricator/' . Filesystem::readRandomCharacters(20); AphrontWriteGuard::willWrite(); $s3->putObject($data, $this->getBucketName(), $name, $acl = 'private'); return $name; }
public static function generateNewPHID($type) { if (!$type) { throw new Exception("Can not generate PHID with no type."); } $uniq = Filesystem::readRandomCharacters(20); return 'PHID-' . $type . '-' . $uniq; }
public function save() { AlmanacNames::validateName($this->getName()); $this->nameIndex = PhabricatorHash::digestForIndex($this->getName()); if (!$this->mailKey) { $this->mailKey = Filesystem::readRandomCharacters(20); } return parent::save(); }
private function generateTestFile(PhabricatorUser $actor) { $engine = new PhabricatorTestStorageEngine(); $data = Filesystem::readRandomCharacters(64); $params = array('name' => 'test.' . $actor->getPHID(), 'viewPolicy' => $actor->getPHID(), 'authorPHID' => $actor->getPHID(), 'storageEngines' => array($engine)); $file = PhabricatorFile::newFromFileData($data, $params); $file->save(); return $file; }
public static function newHTTPAuthorization(PhabricatorRepository $repository, PhabricatorUser $viewer, $operation) { $lfs_user = self::HTTP_USERNAME; $lfs_pass = Filesystem::readRandomCharacters(32); $lfs_hash = PhabricatorHash::digest($lfs_pass); $ttl = PhabricatorTime::getNow() + phutil_units('1 day in seconds'); $token = id(new PhabricatorAuthTemporaryToken())->setTokenResource($repository->getPHID())->setTokenType(self::TOKENTYPE)->setTokenCode($lfs_hash)->setUserPHID($viewer->getPHID())->setTemporaryTokenProperty('lfs.operation', $operation)->setTokenExpires($ttl)->save(); $authorization_header = base64_encode($lfs_user . ':' . $lfs_pass); return 'Basic ' . $authorization_header; }
/** * Set the client ID cookie. This is a random cookie used like a CSRF value * during authentication workflows. * * @param AphrontRequest Request to modify. * @return void * @task clientid */ public static function setClientIDCookie(AphrontRequest $request) { // NOTE: See T3471 for some discussion. Some browsers and browser extensions // can make duplicate requests, so we overwrite this cookie only if it is // not present in the request. The cookie lifetime is limited by making it // temporary and clearing it when users log out. $value = $request->getCookie(self::COOKIE_CLIENTID); if (!strlen($value)) { $request->setTemporaryCookie(self::COOKIE_CLIENTID, Filesystem::readRandomCharacters(16)); } }
public static function initializeNewToken($object_phid, $token_type) { $token = new PhabricatorConduitToken(); $token->objectPHID = $object_phid; $token->tokenType = $token_type; $token->expires = $token->getTokenExpires($token_type); $secret = $token_type . '-' . Filesystem::readRandomCharacters(32); $secret = substr($secret, 0, 32); $token->token = $secret; return $token; }
protected function getExprGrammarSet() { $expr = parent::getExprGrammarSet(); $expr['expr'][] = 'new [classname]([funccallparam])'; $expr['expr'][] = '[methodcall]'; $expr['expr'][] = '[methodcall]'; $expr['expr'][] = '[methodcall]'; $expr['expr'][] = '[methodcall]'; // Add some 'char's for ($ii = 0; $ii < 2; $ii++) { $expr['expr'][] = "'" . Filesystem::readRandomCharacters(1) . "'"; } return $expr; }
public function testIsolation() { $conn = $this->newIsolatedConnection(); $test_phid = 'PHID-TEST-' . Filesystem::readRandomCharacters(20); queryfx($conn, 'INSERT INTO phabricator_phid.phid (phid) VALUES (%s)', $test_phid); try { $real_phid = id(new PhabricatorPHID())->loadOneWhere('phid = %s', $test_phid); $this->assertEqual(null, $real_phid, 'Expect fake PHID to exist only in isolation.'); } catch (AphrontQueryConnectionException $ex) { // If we can't connect to the database, conclude that the isolated // connection actually is isolated. Philosophically, this perhaps allows // us to claim this test does not depend on the database? } }
public static function generateNewPHID($type, $subtype = null) { if (!$type) { throw new Exception(pht('Can not generate PHID with no type.')); } if ($subtype === null) { $uniq_len = 20; $type_str = "{$type}"; } else { $uniq_len = 15; $type_str = "{$type}-{$subtype}"; } $uniq = Filesystem::readRandomCharacters($uniq_len); return "PHID-{$type_str}-{$uniq}"; }
/** * Writes file data into Amazon S3. */ public function writeFile($data, array $params) { $s3 = $this->newS3API(); // Generate a random name for this file. We add some directories to it // (e.g. 'abcdef123456' becomes 'ab/cd/ef123456') to make large numbers of // files more browsable with web/debugging tools like the S3 administration // tool. $seed = Filesystem::readRandomCharacters(20); $parts = array(substr($seed, 0, 2), substr($seed, 2, 2), substr($seed, 4)); $name = 'phabricator/' . implode('/', $parts); AphrontWriteGuard::willWrite(); $profiler = PhutilServiceProfiler::getInstance(); $call_id = $profiler->beginServiceCall(array('type' => 's3', 'method' => 'putObject')); $s3->putObject($data, $this->getBucketName(), $name, $acl = 'private'); $profiler->endServiceCall($call_id, array()); return $name; }
public static function generateNewPHID($type, array $config = array()) { $owner = idx($config, 'owner'); $parent = idx($config, 'parent'); if (!$type) { throw new Exception("Can not generate PHID with no type."); } $uniq = Filesystem::readRandomCharacters(20); $phid = 'PHID-' . $type . '-' . $uniq; $phid_rec = new PhabricatorPHID(); $phid_rec->setPHIDType($type); $phid_rec->setOwnerPHID($owner); $phid_rec->setParentPHID($parent); $phid_rec->setPHID($phid); $phid_rec->save(); return $phid; }
public function processRequest() { $user = $this->getRequest()->getUser(); // Ideally we'd like to verify this, but it's fine to leave it unguarded // for now and verifying it would need some Ajax junk or for the user to // click a button or similar. $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $old_token = id(new PhabricatorConduitCertificateToken())->loadOneWhere('userPHID = %s', $user->getPHID()); if ($old_token) { $old_token->delete(); } $token = id(new PhabricatorConduitCertificateToken())->setUserPHID($user->getPHID())->setToken(Filesystem::readRandomCharacters(40))->save(); $panel = new AphrontPanelView(); $panel->setHeader('Certificate Install Token'); $panel->setWidth(AphrontPanelView::WIDTH_FORM); $panel->appendChild('<p class="aphront-form-instructions">Copy and paste this token into ' . 'the prompt given to you by "arc install-certificate":</p>' . '<p style="padding: 0 0 1em 4em;">' . '<strong>' . phutil_escape_html($token->getToken()) . '</strong>' . '</p>' . '<p class="aphront-form-instructions">arc will then complete the ' . 'install process for you.</p>'); return $this->buildStandardPageResponse($panel, array('title' => 'Certificate Install Token')); }
public function execute(PhutilArgumentParser $args) { $type = $args->getArg('type'); if (!strlen($type)) { throw new PhutilArgumentUsageException(pht('Specify the type of key to generate with --type.')); } $format = PhabricatorFileStorageFormat::getFormat($type); if (!$format) { throw new PhutilArgumentUsageException(pht('No key type "%s" exists.', $type)); } if (!$format->canGenerateNewKeyMaterial()) { throw new PhutilArgumentUsageException(pht('Storage format "%s" can not generate keys.', $format->getStorageFormatName())); } $material = $format->generateNewKeyMaterial(); $structure = array('name' => 'generated-key-' . Filesystem::readRandomCharacters(12), 'type' => $type, 'material.base64' => $material); $json = id(new PhutilJSON())->encodeFormatted($structure); echo tsprintf("%s: %s\n\n%B\n", pht('Key Material'), $format->getStorageFormatName(), $json); return 0; }
public function testRequestCache() { $cache = PhabricatorCaches::getRequestCache(); $test_key = 'unit.' . Filesystem::readRandomCharacters(8); $default_value = pht('Default'); $new_value = pht('New Value'); $this->assertEqual($default_value, $cache->getKey($test_key, $default_value)); // Set a key, verify it persists. $cache = PhabricatorCaches::getRequestCache(); $cache->setKey($test_key, $new_value); $this->assertEqual($new_value, $cache->getKey($test_key, $default_value)); // Refetch the cache, verify it's really a cache. $cache = PhabricatorCaches::getRequestCache(); $this->assertEqual($new_value, $cache->getKey($test_key, $default_value)); // Destroy the cache. PhabricatorCaches::destroyRequestCache(); // Now, the value should be missing again. $cache = PhabricatorCaches::getRequestCache(); $this->assertEqual($default_value, $cache->getKey($test_key, $default_value)); }
public function testReadableTransactions() { // TODO: When we have semi-durable fixtures, use those instead. This is // extremely hacky. LiskDAO::endIsolateAllLiskEffectsToTransactions(); try { $data = Filesystem::readRandomCharacters(32); $obj = new HarbormasterScratchTable(); $obj->openTransaction(); $obj->setData($data); $obj->save(); $loaded = id(new HarbormasterScratchTable())->loadOneWhere('data = %s', $data); $obj->killTransaction(); $this->assertTrue($loaded !== null, 'Reads inside transactions should have transaction visibility.'); LiskDAO::beginIsolateAllLiskEffectsToTransactions(); } catch (Exception $ex) { LiskDAO::beginIsolateAllLiskEffectsToTransactions(); throw $ex; } }
/** * Overridden version of `buildTestFuture` so that the unit test can be run * via `cscover`, which instruments assemblies and reports on code coverage. * * @param string Name of the test assembly. * @return array The future, output filename and coverage filename * stored in an array. */ protected function buildTestFuture($test_assembly) { if ($this->getEnableCoverage() === false) { return parent::buildTestFuture($test_assembly); } // FIXME: Can't use TempFile here as xUnit doesn't like // UNIX-style full paths. It sees the leading / as the // start of an option flag, even when quoted. $xunit_temp = Filesystem::readRandomCharacters(10) . '.results.xml'; if (file_exists($xunit_temp)) { unlink($xunit_temp); } $cover_temp = new TempFile(); $cover_temp->setPreserveFile(true); $xunit_cmd = $this->runtimeEngine; $xunit_args = null; if ($xunit_cmd === '') { $xunit_cmd = $this->testEngine; $xunit_args = csprintf('%s /xml %s', $test_assembly, $xunit_temp); } else { $xunit_args = csprintf('%s %s /xml %s', $this->testEngine, $test_assembly, $xunit_temp); } $assembly_dir = dirname($test_assembly); $assemblies_to_instrument = array(); foreach (Filesystem::listDirectory($assembly_dir) as $file) { if (substr($file, -4) == '.dll' || substr($file, -4) == '.exe') { if ($this->assemblyShouldBeInstrumented($file)) { $assemblies_to_instrument[] = $assembly_dir . DIRECTORY_SEPARATOR . $file; } } } if (count($assemblies_to_instrument) === 0) { return parent::buildTestFuture($test_assembly); } $future = new ExecFuture('%C -o %s -c %s -a %s -w %s %Ls', trim($this->runtimeEngine . ' ' . $this->coverEngine), $cover_temp, $xunit_cmd, $xunit_args, $assembly_dir, $assemblies_to_instrument); $future->setCWD(Filesystem::resolvePath($this->projectRoot)); return array($future, $assembly_dir . DIRECTORY_SEPARATOR . $xunit_temp, $cover_temp); }
public function getKey(AphrontRequest $request) { $plugins = $this->getPlugins(); foreach ($plugins as $plugin) { $plugin->setRequest($request); $plugin->willShutdown(); } foreach ($plugins as $plugin) { $plugin->didShutdown(); } foreach ($plugins as $plugin) { $plugin->setData($plugin->generateData()); } $plugins = msort($plugins, 'getOrderKey'); $key = Filesystem::readRandomCharacters(24); $tabs = array(); $data = array(); foreach ($plugins as $plugin) { $class = get_class($plugin); $tabs[] = array('class' => $class, 'name' => $plugin->getName(), 'color' => $plugin->getColor()); $data[$class] = $this->sanitizeForJSON($plugin->getData()); } $storage = array('vers' => self::STORAGE_VERSION, 'tabs' => $tabs, 'data' => $data, 'user' => $request->getUser() ? $request->getUser()->getPHID() : null); $cache = new PhabricatorKeyValueDatabaseCache(); $cache = new PhutilKeyValueCacheProfiler($cache); $cache->setProfiler(PhutilServiceProfiler::getInstance()); // This encoding may fail if there are, e.g., database queries which // include binary data. It would be a little cleaner to try to strip these, // but just do something non-broken here if we end up with unrepresentable // data. $json = @json_encode($storage); if (!$json) { $json = '{}'; } $cache->setKeys(array('darkconsole:' . $key => $json), $ttl = 60 * 60 * 6); return $key; }
protected function newStorageFixture() { $bytes = Filesystem::readRandomCharacters(24); $name = self::NAMESPACE_PREFIX . $bytes; return new PhabricatorStorageFixtureScopeGuard($name); }
/** * @task token */ public function generateAccessToken() { $token = Filesystem::readRandomCharacters(32); $access_token = new PhabricatorOAuthServerAccessToken(); $access_token->setToken($token); $access_token->setUserPHID($this->getUser()->getPHID()); $access_token->setClientPHID($this->getClient()->getPHID()); $access_token->save(); return $access_token; }
/** * Generate a unique ID for this daemon. * * @return string A unique daemon ID. */ private function generateDaemonID() { return substr(getmypid() . ':' . Filesystem::readRandomCharacters(12), 0, 12); }
public function save() { if (!$this->mailKey) { $this->mailKey = Filesystem::readRandomCharacters(20); } $result = parent::save(); if ($this->projectsNeedUpdate) { // If we've changed the project PHIDs for this task, update the link // table. ManiphestTaskProject::updateTaskProjects($this); $this->projectsNeedUpdate = false; } if ($this->subscribersNeedUpdate) { // If we've changed the subscriber PHIDs for this task, update the link // table. ManiphestTaskSubscriber::updateTaskSubscribers($this); $this->subscribersNeedUpdate = false; } if ($this->auxiliaryDirty) { $this->writeAuxiliaryUpdates(); $this->auxiliaryDirty = array(); } return $result; }