ApiController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Controller;
  12. use Composer\Factory;
  13. use Composer\IO\BufferIO;
  14. use Composer\Package\Loader\ArrayLoader;
  15. use Composer\Package\Loader\ValidatingArrayLoader;
  16. use Composer\Repository\InvalidRepositoryException;
  17. use Composer\Repository\VcsRepository;
  18. use Packagist\WebBundle\Entity\Package;
  19. use Packagist\WebBundle\Entity\User;
  20. use Packagist\WebBundle\Package\Updater;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  24. use Symfony\Component\Console\Output\OutputInterface;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. /**
  29. * @author Jordi Boggiano <j.boggiano@seld.be>
  30. */
  31. class ApiController extends Controller
  32. {
  33. /**
  34. * @Template()
  35. * @Route("/packages.json", name="packages", defaults={"_format" = "json"})
  36. */
  37. public function packagesAction(Request $req)
  38. {
  39. // fallback if any of the dumped files exist
  40. $rootJson = $this->container->getParameter('kernel.root_dir').'/../web/packages_root.json';
  41. if (file_exists($rootJson)) {
  42. return new Response(file_get_contents($rootJson));
  43. }
  44. $rootJson = $this->container->getParameter('kernel.root_dir').'/../web/packages.json';
  45. if (file_exists($rootJson)) {
  46. return new Response(file_get_contents($rootJson));
  47. }
  48. $this->get('logger')->alert('packages.json is missing and the fallback controller is being hit, you need to use app/console packagist:dump');
  49. return new Response('Horrible misconfiguration or the dumper script messed up, you need to use app/console packagist:dump', 404);
  50. }
  51. /**
  52. * @Route("/api/update-package", name="generic_postreceive", defaults={"_format" = "json"})
  53. * @Route("/api/github", name="github_postreceive", defaults={"_format" = "json"})
  54. * @Route("/api/bitbucket", name="bitbucket_postreceive", defaults={"_format" = "json"})
  55. * @Method({"POST"})
  56. */
  57. public function updatePackageAction(Request $request)
  58. {
  59. // parse the payload
  60. $payload = json_decode($request->request->get('payload'), true);
  61. if (!$payload && $request->headers->get('Content-Type') === 'application/json') {
  62. $payload = json_decode($request->getContent(), true);
  63. }
  64. if (!$payload) {
  65. return new JsonResponse(array('status' => 'error', 'message' => 'Missing payload parameter'), 406);
  66. }
  67. if (isset($payload['repository']['url'])) { // github/gitlab/anything hook
  68. $urlRegex = '{^(?:ssh://git@|https?://|git://|git@)?(?P<host>[a-z0-9.-]+)[:/](?P<path>[\w.-]+/[\w.-]+?)(?:\.git)?$}i';
  69. $url = $payload['repository']['url'];
  70. } elseif (isset($payload['canon_url']) && isset($payload['repository']['absolute_url'])) { // bitbucket hook
  71. $urlRegex = '{^(?:https?://|git://|git@)?(?P<host>bitbucket\.org)[/:](?P<path>[\w.-]+/[\w.-]+?)(\.git)?/?$}i';
  72. $url = $payload['canon_url'].$payload['repository']['absolute_url'];
  73. } else {
  74. return new JsonResponse(array('status' => 'error', 'message' => 'Missing or invalid payload'), 406);
  75. }
  76. return $this->receivePost($request, $url, $urlRegex);
  77. }
  78. /**
  79. * @Route("/downloads/{name}", name="track_download", requirements={"name"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"}, defaults={"_format" = "json"})
  80. * @Method({"POST"})
  81. */
  82. public function trackDownloadAction(Request $request, $name)
  83. {
  84. $result = $this->getPackageAndVersionId($name, $request->request->get('version_normalized'));
  85. if (!$result) {
  86. return new JsonResponse(array('status' => 'error', 'message' => 'Package not found'), 200);
  87. }
  88. $this->trackDownload($result['id'], $result['vid'], $request->getClientIp());
  89. return new JsonResponse(array('status' => 'success'), 201);
  90. }
  91. /**
  92. * Expects a json like:
  93. *
  94. * {
  95. * "downloads": [
  96. * {"name": "foo/bar", "version": "1.0.0.0"},
  97. * // ...
  98. * ]
  99. * }
  100. *
  101. * The version must be the normalized one
  102. *
  103. * @Route("/downloads/", name="track_download_batch", defaults={"_format" = "json"})
  104. * @Method({"POST"})
  105. */
  106. public function trackDownloadsAction(Request $request)
  107. {
  108. $contents = json_decode($request->getContent(), true);
  109. if (empty($contents['downloads']) || !is_array($contents['downloads'])) {
  110. return new JsonResponse(array('status' => 'error', 'message' => 'Invalid request format, must be a json object containing a downloads key filled with an array of name/version objects'), 200);
  111. }
  112. $failed = array();
  113. foreach ($contents['downloads'] as $package) {
  114. $result = $this->getPackageAndVersionId($package['name'], $package['version']);
  115. if (!$result) {
  116. $failed[] = $package;
  117. continue;
  118. }
  119. $this->trackDownload($result['id'], $result['vid'], $request->getClientIp());
  120. }
  121. if ($failed) {
  122. return new JsonResponse(array('status' => 'partial', 'message' => 'Packages '.json_encode($failed).' not found'), 200);
  123. }
  124. return new JsonResponse(array('status' => 'success'), 201);
  125. }
  126. protected function getPackageAndVersionId($name, $version)
  127. {
  128. return $this->get('doctrine.dbal.default_connection')->fetchAssoc(
  129. 'SELECT p.id, v.id vid
  130. FROM package p
  131. LEFT JOIN package_version v ON p.id = v.package_id
  132. WHERE p.name = ?
  133. AND v.normalizedVersion = ?
  134. LIMIT 1',
  135. array($name, $version)
  136. );
  137. }
  138. protected function trackDownload($id, $vid, $ip)
  139. {
  140. $redis = $this->get('snc_redis.default');
  141. $manager = $this->get('packagist.download_manager');
  142. $throttleKey = 'dl:'.$id.':'.$ip.':'.date('Ymd');
  143. $requests = $redis->incr($throttleKey);
  144. if (1 === $requests) {
  145. $redis->expire($throttleKey, 86400);
  146. }
  147. if ($requests <= 10) {
  148. $manager->addDownload($id, $vid);
  149. }
  150. }
  151. /**
  152. * Perform the package update
  153. *
  154. * @param Request $request the current request
  155. * @param string $url the repository's URL (deducted from the request)
  156. * @param string $urlRegex the regex used to split the user packages into domain and path
  157. * @return Response
  158. */
  159. protected function receivePost(Request $request, $url, $urlRegex)
  160. {
  161. // try to parse the URL first to avoid the DB lookup on malformed requests
  162. if (!preg_match($urlRegex, $url)) {
  163. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not parse payload repository URL')), 406);
  164. }
  165. // find the user
  166. $user = $this->findUser($request);
  167. if (!$user) {
  168. return new Response(json_encode(array('status' => 'error', 'message' => 'Invalid credentials')), 403);
  169. }
  170. // try to find the user package
  171. $packages = $this->findPackagesByUrl($user, $url, $urlRegex);
  172. if (!$packages) {
  173. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not find a package that matches this request (does user maintain the package?)')), 404);
  174. }
  175. // don't die if this takes a while
  176. set_time_limit(3600);
  177. // put both updating the database and scanning the repository in a transaction
  178. $em = $this->get('doctrine.orm.entity_manager');
  179. $updater = $this->get('packagist.package_updater');
  180. $config = Factory::createConfig();
  181. $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE);
  182. $io->loadConfiguration($config);
  183. try {
  184. foreach ($packages as $package) {
  185. $em->transactional(function($em) use ($package, $updater, $io, $config) {
  186. // prepare dependencies
  187. $loader = new ValidatingArrayLoader(new ArrayLoader());
  188. // prepare repository
  189. $repository = new VcsRepository(array('url' => $package->getRepository()), $io, $config);
  190. $repository->setLoader($loader);
  191. // perform the actual update (fetch and re-scan the repository's source)
  192. $updater->update($io, $config, $package, $repository);
  193. // update the package entity
  194. $package->setAutoUpdated(true);
  195. $em->flush();
  196. });
  197. }
  198. } catch (\Exception $e) {
  199. if ($e instanceof InvalidRepositoryException) {
  200. $this->get('packagist.package_manager')->notifyUpdateFailure($package, $e, $io->getOutput());
  201. }
  202. return new Response(json_encode(array(
  203. 'status' => 'error',
  204. 'message' => '['.get_class($e).'] '.$e->getMessage(),
  205. 'details' => '<pre>'.$io->getOutput().'</pre>'
  206. )), 400);
  207. }
  208. return new JsonResponse(array('status' => 'success'), 202);
  209. }
  210. /**
  211. * Find a user by his username and API token
  212. *
  213. * @param Request $request
  214. * @return User|null the found user or null otherwise
  215. */
  216. protected function findUser(Request $request)
  217. {
  218. $username = $request->request->has('username') ?
  219. $request->request->get('username') :
  220. $request->query->get('username');
  221. $apiToken = $request->request->has('apiToken') ?
  222. $request->request->get('apiToken') :
  223. $request->query->get('apiToken');
  224. $user = $this->get('packagist.user_repository')
  225. ->findOneBy(array('username' => $username, 'apiToken' => $apiToken));
  226. return $user;
  227. }
  228. /**
  229. * Find a user package given by its full URL
  230. *
  231. * @param User $user
  232. * @param string $url
  233. * @param string $urlRegex
  234. * @return array the packages found
  235. */
  236. protected function findPackagesByUrl(User $user, $url, $urlRegex)
  237. {
  238. if (!preg_match($urlRegex, $url, $matched)) {
  239. return array();
  240. }
  241. $packages = array();
  242. foreach ($user->getPackages() as $package) {
  243. if (preg_match($urlRegex, $package->getRepository(), $candidate)
  244. && $candidate['host'] === $matched['host']
  245. && $candidate['path'] === $matched['path']
  246. ) {
  247. $packages[] = $package;
  248. }
  249. }
  250. return $packages;
  251. }
  252. }