1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

# Copyright 2013-2016 The Distro Tracker Developers 

# See the COPYRIGHT file at the top-level directory of this distribution and 

# at https://deb.li/DTAuthors 

# 

# This file is part of Distro Tracker. It is subject to the license terms 

# in the LICENSE file found in the top-level directory of this 

# distribution and at https://deb.li/DTLicense. No part of Distro Tracker, 

# including this file, may be copied, modified, propagated, or distributed 

# except according to the terms contained in the LICENSE file. 

""" 

Implements the processing of received package messages in order to dispatch 

them to subscribers. 

""" 

import logging 

import re 

from copy import deepcopy 

from datetime import datetime 

 

from django.conf import settings 

from django.core.mail import EmailMessage, get_connection 

from django.utils import timezone 

 

from distro_tracker import vendor 

from distro_tracker.core.models import Keyword, PackageName, Team 

from distro_tracker.core.utils import ( 

distro_tracker_render_to_string, 

extract_email_address_from_header, 

get_decoded_message_payload, 

get_or_none, 

verp 

) 

from distro_tracker.core.utils.email_messages import ( 

CustomEmailMessage, 

patch_message_for_django_compat 

) 

from distro_tracker.mail.models import UserEmailBounceStats 

 

DISTRO_TRACKER_CONTROL_EMAIL = settings.DISTRO_TRACKER_CONTROL_EMAIL 

DISTRO_TRACKER_FQDN = settings.DISTRO_TRACKER_FQDN 

 

logger = logging.getLogger(__name__) 

 

 

class SkipMessage(Exception): 

"""This exception can be raised by the vendor provided classify_message() 

to tell the dispatch code to skip processing this message being processed. 

The mail is then silently dropped.""" 

 

 

def _get_logdata(msg, package, keyword, team): 

return { 

'from': extract_email_address_from_header(msg.get('From', '')), 

'msgid': msg.get('Message-ID', 'no-msgid-present@localhost'), 

'package': package or '<unknown>', 

'keyword': keyword or '<unknown>', 

'team': team or '<unknown>', 

} 

 

 

def _must_discard(msg, logdata): 

# Check loop 

dispatch_email = 'dispatch@{}'.format(DISTRO_TRACKER_FQDN) 

if dispatch_email in msg.get_all('X-Loop', ()): 

# Bad X-Loop, discard the message 

logger.info('dispatch :: discarded %(msgid)s due to X-Loop', logdata) 

return True 

return False 

 

 

def process(msg, package=None, keyword=None): 

""" 

Dispatches received messages by identifying where they should 

be sent and then by forwarding them. 

 

:param msg: The received message 

:type msg: :py:class:`email.message.Message` 

 

:param str package: The package to which the message was sent. 

 

:param str keyword: The keyword under which the message must be dispatched. 

""" 

logdata = _get_logdata(msg, package, keyword, None) 

logger.info("dispatch :: received from %(from)s :: %(msgid)s", 

logdata) 

try: 

package, keyword = classify_message(msg, package, keyword) 

except SkipMessage: 

logger.info('dispatch :: skipping %(msgid)s', logdata) 

return 

 

if package is None: 

logger.warning('dispatch :: no package identified for %(msgid)s', 

logdata) 

return 

 

if _must_discard(msg, logdata): 

return 

 

if isinstance(package, (list, set)): 

for pkg in package: 

forward(msg, pkg, keyword) 

else: 

forward(msg, package, keyword) 

 

 

def forward(msg, package, keyword): 

""" 

Forwards a received message to the various subscribers of the 

given package/keyword combination. 

 

:param msg: The received message 

:type msg: :py:class:`email.message.Message` 

 

:param str package: The package name. 

 

:param str keyword: The keyword under which the message must be forwarded. 

""" 

logdata = _get_logdata(msg, package, keyword, None) 

 

logger.info("dispatch :: forward to %(package)s %(keyword)s :: %(msgid)s", 

logdata) 

 

# Default keywords require special approvement 

if keyword == 'default' and not approved_default(msg): 

logger.info('dispatch :: discarded non-approved message %(msgid)s', 

logdata) 

return 

 

# Now send the message to subscribers 

add_new_headers(msg, package_name=package, keyword=keyword) 

send_to_subscribers(msg, package, keyword) 

send_to_teams(msg, package, keyword) 

 

 

def process_for_team(msg, team_slug): 

"""Dispatch a message sent to a team.""" 

logdata = _get_logdata(msg, None, None, team_slug) 

logger.info("dispatch :: received for team %(team)s " 

"from %(from)s :: %(msgid)s", logdata) 

 

if _must_discard(msg, logdata): 

return 

 

try: 

team = Team.objects.get(slug=team_slug) 

except Team.DoesNotExist: 

logger.info("dispatch :: discarded %(msgid)s for team %(team)s " 

"since team doesn't exist", logdata) 

return 

 

package, keyword = classify_message(msg) 

if package: 

logger.info("dispatch :: discarded %(msgid)s for team %(team)s " 

"as an automatic mail", logdata) 

return 

 

forward_to_team(msg, team) 

 

 

def forward_to_team(msg, team): 

"""Forward a message to a team, adding headers as required.""" 

logdata = _get_logdata(msg, None, None, team.slug) 

logger.info("dispatch :: forward to team %(team)s :: %(msgid)s", 

logdata) 

 

add_new_headers(msg, keyword="contact", team=team.slug) 

send_to_team(msg, team, keyword="contact") 

 

 

def classify_message(msg, package=None, keyword=None): 

""" 

Analyzes a message to identify what package it is about and 

what keyword is appropriate. 

 

:param msg: The received message 

:type msg: :py:class:`email.message.Message` 

 

:param str package: The suggested package name. 

 

:param str keyword: The suggested keyword under which the message can be 

forwarded. 

 

""" 

if package is None: 

package = msg.get('X-Distro-Tracker-Package') 

if keyword is None: 

keyword = msg.get('X-Distro-Tracker-Keyword') 

 

result, implemented = vendor.call('classify_message', msg, 

package=package, keyword=keyword) 

if implemented: 

package, keyword = result 

if package and keyword is None: 

keyword = 'default' 

return (package, keyword) 

 

 

def approved_default(msg): 

""" 

The function checks whether a message tagged with the default keyword should 

be approved, meaning that it gets forwarded to subscribers. 

 

:param msg: The received package message 

:type msg: :py:class:`email.message.Message` or an equivalent interface 

object 

""" 

if 'X-Distro-Tracker-Approved' in msg: 

return True 

 

approved, implemented = vendor.call('approve_default_message', msg) 

211 ↛ 214line 211 didn't jump to line 214, because the condition on line 211 was never false if implemented: 

return approved 

else: 

return False 

 

 

def add_new_headers(received_message, package_name=None, keyword=None, 

team=None): 

""" 

The function adds new distro-tracker specific headers to the received 

message. This is used before forwarding the message to subscribers. 

 

The headers added by this function are used regardless whether the 

message is forwarded due to direct package subscriptions or a team 

subscription. 

 

:param received_message: The received package message 

:type received_message: :py:class:`email.message.Message` or an equivalent 

interface object 

 

:param package_name: The name of the package for which this message was 

intended. 

:type package_name: string 

 

:param keyword: The keyword with which the message should be tagged 

:type keyword: string 

""" 

new_headers = [ 

('X-Loop', 'dispatch@{}'.format(DISTRO_TRACKER_FQDN)), 

] 

241 ↛ 243line 241 didn't jump to line 243, because the condition on line 241 was never false if keyword: 

new_headers.append(('X-Distro-Tracker-Keyword', keyword)) 

if package_name: 

new_headers.extend([ 

('X-Distro-Tracker-Package', package_name), 

('List-Id', '<{}.{}>'.format(package_name, DISTRO_TRACKER_FQDN)), 

]) 

if team: 

new_headers.append(('X-Distro-Tracker-Team', team)) 

 

extra_vendor_headers, implemented = vendor.call( 

'add_new_headers', received_message, package_name, keyword, team) 

if implemented: 

new_headers.extend(extra_vendor_headers) 

 

for header_name, header_value in new_headers: 

received_message[header_name] = header_value 

 

 

def add_direct_subscription_headers(received_message, package_name, keyword): 

""" 

The function adds headers to the received message which are specific for 

messages to be sent to users that are directly subscribed to the package. 

""" 

new_headers = [ 

('Precedence', 'list'), 

('List-Unsubscribe', 

'<mailto:{control_email}?body=unsubscribe%20{package}>'.format( 

control_email=DISTRO_TRACKER_CONTROL_EMAIL, 

package=package_name)), 

] 

for header_name, header_value in new_headers: 

received_message[header_name] = header_value 

 

 

def add_team_membership_headers(received_message, keyword, team): 

""" 

The function adds headers to the received message which are specific for 

messages to be sent to users that are members of a team. 

""" 

received_message['X-Distro-Tracker-Team'] = team.slug 

 

 

def send_to_teams(received_message, package_name, keyword): 

""" 

Sends the given email message to all members of each team that has the 

given package. 

 

The message is only sent to those users who have not muted the team 

and have the given keyword in teir set of keywords for the team 

membership. 

 

:param received_message: The modified received package message to be sent 

to the subscribers. 

:type received_message: :py:class:`email.message.Message` or an equivalent 

interface object 

 

:param package_name: The name of the package for which this message was 

intended. 

:type package_name: string 

 

:param keyword: The keyword with which the message should be tagged 

:type keyword: string 

""" 

keyword = get_or_none(Keyword, name=keyword) 

package = get_or_none(PackageName, name=package_name) 

if not keyword or not package: 

return 

# Get all teams that have the given package 

teams = Team.objects.filter(packages=package) 

teams = teams.prefetch_related('team_membership_set') 

 

for team in teams: 

send_to_team(received_message, team, keyword, package.name) 

 

 

def send_to_team(received_message, team, keyword, package_name=None): 

"""Send a message to a team.""" 

keyword = get_or_none(Keyword, name=keyword) 

package = get_or_none(PackageName, name=package_name) 

date = timezone.now().date() 

messages_to_send = [] 

logger.info('dispatch :: sending to team %s', team.slug) 

team_message = deepcopy(received_message) 

add_team_membership_headers(team_message, keyword.name, team) 

 

# Send the message to each member of the team 

for membership in team.team_membership_set.all(): 

# Do not send messages to muted memberships 

if membership.is_muted(package): 

continue 

# Do not send the message if the user has disabled the keyword 

if keyword not in membership.get_keywords(package): 

continue 

 

messages_to_send.append(prepare_message( 

team_message, membership.user_email.email, date)) 

 

send_messages(messages_to_send, date) 

 

 

def send_to_subscribers(received_message, package_name, keyword): 

""" 

Sends the given email message to all subscribers of the package with the 

given name and those that accept messages tagged with the given keyword. 

 

:param received_message: The modified received package message to be sent 

to the subscribers. 

:type received_message: :py:class:`email.message.Message` or an equivalent 

interface object 

 

:param package_name: The name of the package for which this message was 

intended. 

:type package_name: string 

 

:param keyword: The keyword with which the message should be tagged 

:type keyword: string 

""" 

# Make a copy of the message to be sent and add any headers which are 

# specific for users that are directly subscribed to the package. 

received_message = deepcopy(received_message) 

add_direct_subscription_headers(received_message, package_name, keyword) 

package = get_or_none(PackageName, name=package_name) 

if not package: 

return 

# Build a list of all messages to be sent 

date = timezone.now().date() 

messages_to_send = [ 

prepare_message(received_message, 

subscription.email_settings.user_email.email, 

date) 

for subscription in package.subscription_set.all_active(keyword) 

] 

send_messages(messages_to_send, date) 

 

 

def send_messages(messages_to_send, date): 

""" 

Sends all the given email messages over a single SMTP connection. 

""" 

connection = get_connection() 

connection.send_messages(messages_to_send) 

 

for message in messages_to_send: 

logger.info("dispatch => %s", message.to[0]) 

UserEmailBounceStats.objects.add_sent_for_user(email=message.to[0], 

date=date) 

 

 

def prepare_message(received_message, to_email, date): 

""" 

Converts a message which is to be sent to a subscriber to a 

:py:class:`CustomEmailMessage 

<distro_tracker.core.utils.email_messages.CustomEmailMessage>` 

so that it can be sent out using Django's API. 

It also sets the required evelope-to value in order to track the bounce for 

the message. 

 

:param received_message: The modified received package message to be sent 

to the subscribers. 

:type received_message: :py:class:`email.message.Message` or an equivalent 

interface object 

 

:param to_email: The email of the subscriber to whom the message is to be 

sent 

:type to_email: string 

 

:param date: The date which should be used as the message's sent date. 

:type date: :py:class:`datetime.datetime` 

""" 

bounce_address = 'bounces+{date}@{distro_tracker_fqdn}'.format( 

date=date.strftime('%Y%m%d'), 

distro_tracker_fqdn=DISTRO_TRACKER_FQDN) 

message = CustomEmailMessage( 

msg=patch_message_for_django_compat(received_message), 

from_email=verp.encode(bounce_address, to_email), 

to=[to_email]) 

return message 

 

 

def bounce_is_for_spam(message): 

"""Return True if the bounce has been generated by spam, False otherwise.""" 

spam_bounce_re = [ 

# Google blocks executables files 

# 552-5.7.0 This message was blocked because its content presents a[...] 

# 552-5.7.0 security issue. Please visit 

# 552-5.7.0 https://support.google.com/mail/?p=BlockedMessage to [...] 

# 552 5.7.0 message content and attachment content guidelines. [...] 

r"552-5.7.0 This message was blocked", 

# host ...: 550 High probability of spam 

# host ...: 554 5.7.1 Message rejected because it contains malware 

# 550 Executable files are not allowed in compressed files. 

r"55[0-9][- ].*(?:spam|malware|virus|[Ee]xecutable files)", 

] 

# XXX: Handle delivery report properly 

for part in message.walk(): 

437 ↛ 438line 437 didn't jump to line 438, because the condition on line 437 was never true if not part or part.is_multipart(): 

continue 

text = get_decoded_message_payload(part) 

if text is None: 

continue 

442 ↛ 436line 442 didn't jump to line 436, because the loop on line 442 didn't complete for line in text.splitlines()[0:15]: 

for rule in spam_bounce_re: 

if re.search(rule, line): 

return True 

 

return False 

 

 

def handle_bounces(sent_to_address, message): 

""" 

Handles a received bounce message. 

 

:param sent_to_address: The envelope-to (return path) address to which the 

bounced email was returned. 

:type sent_to_address: string 

""" 

try: 

bounce_email, user_email = verp.decode(sent_to_address) 

except ValueError: 

logger.warning('bounces :: no VERP data to extract from %s', 

sent_to_address) 

return 

match = re.match(r'^bounces\+(\d{8})@' + DISTRO_TRACKER_FQDN, bounce_email) 

465 ↛ 466line 465 didn't jump to line 466, because the condition on line 465 was never true if not match: 

logger.warning('bounces :: invalid address %s', bounce_email) 

return 

try: 

date = datetime.strptime(match.group(1), '%Y%m%d') 

except ValueError: 

logger.warning('bounces :: invalid date in address %s', bounce_email) 

return 

 

logger.info('bounces :: received one for %s/%s', user_email, date) 

try: 

user = UserEmailBounceStats.objects.get(email__iexact=user_email) 

except UserEmailBounceStats.DoesNotExist: 

logger.warning('bounces :: unknown user email %s', user_email) 

return 

 

if bounce_is_for_spam(message): 

logger.info('bounces :: discarded spam bounce for %s/%s', 

user_email, date) 

return 

 

UserEmailBounceStats.objects.add_bounce_for_user(email=user_email, 

date=date) 

 

if user.has_too_many_bounces(): 

logger.info('bounces => %s has too many bounces', user_email) 

 

packages = list(user.emailsettings.packagename_set.all()) 

teams = [m.team for m in user.membership_set.all()] 

email_body = distro_tracker_render_to_string( 

'dispatch/unsubscribed-due-to-bounces-email.txt', { 

'email': user_email, 

'packages': packages, 

'teams': teams, 

}) 

EmailMessage( 

subject='All your package subscriptions have been cancelled', 

from_email=settings.DISTRO_TRACKER_BOUNCES_LIKELY_SPAM_EMAIL, 

to=[user_email], 

cc=[settings.DISTRO_TRACKER_CONTACT_EMAIL], 

body=email_body, 

headers={ 

'From': settings.DISTRO_TRACKER_CONTACT_EMAIL, 

}, 

).send() 

 

user.emailsettings.unsubscribe_all() 

for package in packages: 

logger.info('bounces :: removed %s from %s', user_email, 

package.name) 

user.membership_set.all().update(muted=True) 

for team in teams: 

logger.info('bounces :: muted membership of %s in team %s', 

user_email, team.slug)