ReceiveEmail.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\AdditionalUsername;
  4. use App\Alias;
  5. use App\Domain;
  6. use App\EmailData;
  7. use App\Mail\ForwardEmail;
  8. use App\Mail\ReplyToEmail;
  9. use App\Notifications\NearBandwidthLimit;
  10. use App\User;
  11. use Illuminate\Console\Command;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Mail;
  14. use Illuminate\Support\Facades\Redis;
  15. use Illuminate\Support\Str;
  16. use PhpMimeMailParser\Parser;
  17. class ReceiveEmail extends Command
  18. {
  19. /**
  20. * The name and signature of the console command.
  21. *
  22. * @var string
  23. */
  24. protected $signature = 'anonaddy:receive-email
  25. {file=stream : The file of the email}
  26. {--sender= : The sender of the email}
  27. {--recipient=* : The recipient of the email}
  28. {--local_part=* : The local part of the recipient}
  29. {--extension=* : The extension of the local part of the recipient}
  30. {--domain=* : The domain of the recipient}
  31. {--size= : The size of the email in bytes}';
  32. /**
  33. * The console command description.
  34. *
  35. * @var string
  36. */
  37. protected $description = 'Receive email from postfix pipe';
  38. protected $parser;
  39. protected $size;
  40. /**
  41. * Create a new command instance.
  42. *
  43. * @return void
  44. */
  45. public function __construct()
  46. {
  47. parent::__construct();
  48. }
  49. /**
  50. * Execute the console command.
  51. *
  52. * @return mixed
  53. */
  54. public function handle()
  55. {
  56. try {
  57. $this->exitIfFromSelf();
  58. $file = $this->argument('file');
  59. $this->parser = $this->getParser($file);
  60. $recipients = $this->getRecipients();
  61. // Divide the size of the email by the number of recipients (excluding any unsubscribe recipients) to prevent it being added multiple times.
  62. $recipientCount = $recipients->where('domain', '!=', 'unsubscribe.'.config('anonaddy.domain'))->count();
  63. $this->size = $this->option('size') / ($recipientCount ? $recipientCount : 1);
  64. foreach ($recipients as $key => $recipient) {
  65. $displayTo = $this->parser->getAddresses('to')[$key]['display'] ?? null;
  66. $parentDomain = collect(config('anonaddy.all_domains'))
  67. ->filter(function ($name) use ($recipient) {
  68. return Str::endsWith($recipient['domain'], $name);
  69. })
  70. ->first();
  71. $subdomain = substr($recipient['domain'], 0, strrpos($recipient['domain'], '.'.$parentDomain));
  72. if ($subdomain === 'unsubscribe') {
  73. $this->handleUnsubscribe($recipient);
  74. continue;
  75. }
  76. $user = User::where('username', $subdomain)->first();
  77. if (is_null($user)) {
  78. // Check if this is a custom domain.
  79. if ($customDomain = Domain::where('domain', $recipient['domain'])->first()) {
  80. $user = $customDomain->user;
  81. }
  82. // Check if this is an additional username.
  83. if ($additionalUsername = AdditionalUsername::where('username', $subdomain)->first()) {
  84. $user = $additionalUsername->user;
  85. }
  86. // Check if this is a uuid generated alias.
  87. if ($alias = Alias::find($recipient['local_part'])) {
  88. $user = $alias->user;
  89. } elseif ($recipient['domain'] === $parentDomain && !empty(config('anonaddy.admin_username'))) {
  90. $user = User::where('username', config('anonaddy.admin_username'))->first();
  91. }
  92. }
  93. // If there is still no user or the user has no verified default recipient then continue.
  94. if (is_null($user) || !$user->hasVerifiedDefaultRecipient()) {
  95. continue;
  96. }
  97. $this->checkRateLimit($user);
  98. // Check whether this email is a reply or a new email to be forwarded.
  99. if ($recipient['extension'] === sha1(config('anonaddy.secret').$displayTo)) {
  100. $this->handleReply($user, $recipient, $displayTo);
  101. } else {
  102. $this->handleForward($user, $recipient, $customDomain->id ?? null);
  103. }
  104. }
  105. } catch (\Exception $e) {
  106. Log::error($e->getMessage() . PHP_EOL . $e->getTraceAsString());
  107. $this->error('4.3.0 An error has occurred, please try again later.');
  108. exit(1);
  109. }
  110. }
  111. protected function handleUnsubscribe($recipient)
  112. {
  113. $alias = Alias::find($recipient['local_part']);
  114. if (!is_null($alias) && $alias->user->isVerifiedRecipient($this->option('sender'))) {
  115. $alias->deactivate();
  116. }
  117. }
  118. protected function handleReply($user, $recipient, $displayTo)
  119. {
  120. $alias = $user->aliases()->where('email', $recipient['local_part'] . '@' . $recipient['domain'])->first();
  121. if (!is_null($alias) && filter_var($displayTo, FILTER_VALIDATE_EMAIL)) {
  122. $emailData = new EmailData($this->parser);
  123. $message = (new ReplyToEmail($user, $alias, $emailData));
  124. Mail::to($displayTo)->queue($message);
  125. if (!Mail::failures()) {
  126. $alias->increment('emails_replied');
  127. $user->bandwidth += $this->size;
  128. $user->save();
  129. if ($user->nearBandwidthLimit()) {
  130. $user->notify(new NearBandwidthLimit());
  131. }
  132. }
  133. }
  134. }
  135. protected function handleForward($user, $recipient, $customDomainId)
  136. {
  137. $alias = $user->aliases()->firstOrNew([
  138. 'email' => $recipient['local_part'] . '@' . $recipient['domain'],
  139. 'local_part' => $recipient['local_part'],
  140. 'domain' => $recipient['domain'],
  141. 'domain_id' => $customDomainId
  142. ]);
  143. if (!isset($alias->id)) {
  144. // This is a new alias.
  145. if ($user->hasExceededNewAliasLimit()) {
  146. $this->error('4.2.1 New aliases per hour limit exceeded for user ' . $user->username . '.');
  147. exit(1);
  148. }
  149. if ($recipient['extension'] !== '') {
  150. $alias->extension = $recipient['extension'];
  151. $keys = explode('.', $recipient['extension']);
  152. $recipientIds = $user
  153. ->recipients()
  154. ->oldest()
  155. ->get()
  156. ->filter(function ($item, $key) use ($keys) {
  157. return in_array($key+1, $keys) && ! is_null($item['email_verified_at']);
  158. })
  159. ->pluck('id')
  160. ->take(10)
  161. ->toArray();
  162. }
  163. }
  164. $alias->save();
  165. $alias->refresh();
  166. if (isset($recipientIds)) {
  167. $alias->recipients()->sync($recipientIds);
  168. }
  169. $emailData = new EmailData($this->parser);
  170. $alias->verifiedRecipientsOrDefault()->each(function ($recipient) use ($alias, $emailData) {
  171. $message = (new ForwardEmail($alias, $emailData, $recipient->should_encrypt ? $recipient->fingerprint : null));
  172. Mail::to($recipient->email)->queue($message);
  173. });
  174. if (!Mail::failures()) {
  175. $alias->increment('emails_forwarded');
  176. $user->bandwidth += $this->size;
  177. $user->save();
  178. if ($user->nearBandwidthLimit()) {
  179. $user->notify(new NearBandwidthLimit());
  180. }
  181. }
  182. }
  183. protected function checkRateLimit($user)
  184. {
  185. Redis::throttle("user:{$user->username}:limit:emails")
  186. ->allow(config('anonaddy.limit'))
  187. ->every(3600)
  188. ->then(
  189. function () {
  190. },
  191. function () use ($user) {
  192. $this->error('4.2.1 Rate limit exceeded for user ' . $user->username . '. Please try again later.');
  193. exit(1);
  194. }
  195. );
  196. }
  197. protected function getRecipients()
  198. {
  199. return collect($this->option('recipient'))->map(function ($item, $key) {
  200. return [
  201. 'email' => $item,
  202. 'local_part' => $this->option('local_part')[$key],
  203. 'extension' => $this->option('extension')[$key],
  204. 'domain' => $this->option('domain')[$key]
  205. ];
  206. });
  207. }
  208. protected function getParser($file)
  209. {
  210. $parser = new Parser;
  211. if ($file == 'stream') {
  212. $fd = fopen('php://stdin', 'r');
  213. $this->rawEmail = '';
  214. while (!feof($fd)) {
  215. $this->rawEmail .= fread($fd, 1024);
  216. }
  217. fclose($fd);
  218. $parser->setText($this->rawEmail);
  219. } else {
  220. $parser->setPath($file);
  221. }
  222. return $parser;
  223. }
  224. protected function exitIfFromSelf()
  225. {
  226. // To prevent recipient alias infinite nested looping.
  227. if (in_array($this->option('sender'), [config('mail.from.address'), config('anonaddy.return_path')])) {
  228. exit(0);
  229. }
  230. }
  231. }