inbox.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. __filename__ = "inbox.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "1.0.0"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. import json
  9. import os
  10. import datetime
  11. import time
  12. import json
  13. import commentjson
  14. from shutil import copyfile
  15. from utils import urlPermitted
  16. from utils import createInboxQueueDir
  17. from utils import getStatusNumber
  18. from utils import getDomainFromActor
  19. from utils import getNicknameFromActor
  20. from utils import domainPermitted
  21. from utils import locatePost
  22. from utils import deletePost
  23. from utils import removeAttachment
  24. from utils import removeModerationPostFromIndex
  25. from httpsig import verifyPostHeaders
  26. from session import createSession
  27. from session import getJson
  28. from follow import receiveFollowRequest
  29. from follow import getFollowersOfActor
  30. from follow import unfollowerOfPerson
  31. from pprint import pprint
  32. from cache import getPersonFromCache
  33. from cache import storePersonInCache
  34. from acceptreject import receiveAcceptReject
  35. from capabilities import getOcapFilename
  36. from capabilities import CapablePost
  37. from capabilities import capabilitiesReceiveUpdate
  38. from like import updateLikesCollection
  39. from like import undoLikesCollectionEntry
  40. from blocking import isBlocked
  41. from filters import isFiltered
  42. from announce import updateAnnounceCollection
  43. from httpsig import messageContentDigest
  44. from blocking import isBlockedDomain
  45. def validInbox(baseDir: str,nickname: str,domain: str) -> bool:
  46. """Checks whether files were correctly saved to the inbox
  47. """
  48. if ':' in domain:
  49. domain=domain.split(':')[0]
  50. inboxDir=baseDir+'/accounts/'+nickname+'@'+domain+'/inbox'
  51. if not os.path.isdir(inboxDir):
  52. return True
  53. for subdir, dirs, files in os.walk(inboxDir):
  54. for f in files:
  55. filename = os.path.join(subdir, f)
  56. if not os.path.isfile(filename):
  57. print('filename: '+filename)
  58. return False
  59. if 'postNickname' in open(filename).read():
  60. print('queue file incorrectly saved to '+filename)
  61. return False
  62. return True
  63. def validInboxFilenames(baseDir: str,nickname: str,domain: str, \
  64. expectedDomain: str,expectedPort: int) -> bool:
  65. """Used by unit tests to check that the port number gets appended to
  66. domain names within saved post filenames
  67. """
  68. if ':' in domain:
  69. domain=domain.split(':')[0]
  70. inboxDir=baseDir+'/accounts/'+nickname+'@'+domain+'/inbox'
  71. if not os.path.isdir(inboxDir):
  72. return True
  73. expectedStr=expectedDomain+':'+str(expectedPort)
  74. for subdir, dirs, files in os.walk(inboxDir):
  75. for f in files:
  76. filename = os.path.join(subdir, f)
  77. if not os.path.isfile(filename):
  78. print('filename: '+filename)
  79. return False
  80. if not expectedStr in filename:
  81. print('Expected: '+expectedStr)
  82. print('Invalid filename: '+filename)
  83. return False
  84. return True
  85. def getPersonPubKey(baseDir: str,session,personUrl: str, \
  86. personCache: {},debug: bool, \
  87. projectVersion: str,httpPrefix: str,domain: str) -> str:
  88. if not personUrl:
  89. return None
  90. personUrl=personUrl.replace('#main-key','')
  91. if personUrl.endswith('/users/inbox'):
  92. if debug:
  93. print('DEBUG: Obtaining public key for shared inbox')
  94. personUrl=personUrl.replace('/users/inbox','/inbox')
  95. personJson = getPersonFromCache(baseDir,personUrl,personCache)
  96. if not personJson:
  97. if debug:
  98. print('DEBUG: Obtaining public key for '+personUrl)
  99. asHeader = {'Accept': 'application/activity+json; profile="https://www.w3.org/ns/activitystreams"'}
  100. personJson = getJson(session,personUrl,asHeader,None,projectVersion,httpPrefix,domain)
  101. if not personJson:
  102. return None
  103. pubKey=None
  104. if personJson.get('publicKey'):
  105. if personJson['publicKey'].get('publicKeyPem'):
  106. pubKey=personJson['publicKey']['publicKeyPem']
  107. else:
  108. if personJson.get('publicKeyPem'):
  109. pubKey=personJson['publicKeyPem']
  110. if not pubKey:
  111. if debug:
  112. print('DEBUG: Public key not found for '+personUrl)
  113. storePersonInCache(baseDir,personUrl,personJson,personCache)
  114. return pubKey
  115. def inboxMessageHasParams(messageJson: {}) -> bool:
  116. """Checks whether an incoming message contains expected parameters
  117. """
  118. expectedParams=['type','actor','object']
  119. for param in expectedParams:
  120. if not messageJson.get(param):
  121. return False
  122. if not messageJson.get('to'):
  123. allowedWithoutToParam=['Like','Follow','Request','Accept','Capability','Undo']
  124. if messageJson['type'] not in allowedWithoutToParam:
  125. return False
  126. return True
  127. def inboxPermittedMessage(domain: str,messageJson: {}, \
  128. federationList: []) -> bool:
  129. """ check that we are receiving from a permitted domain
  130. """
  131. testParam='actor'
  132. if not messageJson.get(testParam):
  133. return False
  134. actor=messageJson[testParam]
  135. # always allow the local domain
  136. if domain in actor:
  137. return True
  138. if not urlPermitted(actor,federationList,"inbox:write"):
  139. return False
  140. if messageJson['type']!='Follow' and \
  141. messageJson['type']!='Like' and \
  142. messageJson['type']!='Delete' and \
  143. messageJson['type']!='Announce':
  144. if messageJson.get('object'):
  145. if not isinstance(messageJson['object'], dict):
  146. return False
  147. if messageJson['object'].get('inReplyTo'):
  148. inReplyTo=messageJson['object']['inReplyTo']
  149. if not urlPermitted(inReplyTo,federationList,"inbox:write"):
  150. return False
  151. return True
  152. def validPublishedDate(published: str) -> bool:
  153. currTime=datetime.datetime.utcnow()
  154. pubDate=datetime.datetime.strptime(published,"%Y-%m-%dT%H:%M:%SZ")
  155. daysSincePublished = (currTime - pubTime).days
  156. if daysSincePublished>30:
  157. return False
  158. return True
  159. def savePostToInboxQueue(baseDir: str,httpPrefix: str, \
  160. nickname: str, domain: str, \
  161. postJsonObject: {}, \
  162. messageBytes: str, \
  163. httpHeaders: {}, \
  164. postPath: str,debug: bool) -> str:
  165. """Saves the give json to the inbox queue for the person
  166. keyId specifies the actor sending the post
  167. """
  168. originalDomain=domain
  169. if ':' in domain:
  170. domain=domain.split(':')[0]
  171. # block at the ealiest stage possible, which means the data
  172. # isn't written to file
  173. postNickname=None
  174. postDomain=None
  175. actor=None
  176. if postJsonObject.get('actor'):
  177. actor=postJsonObject['actor']
  178. postNickname=getNicknameFromActor(postJsonObject['actor'])
  179. if not postNickname:
  180. print('No post Nickname in actor '+postJsonObject['actor'])
  181. return None
  182. postDomain,postPort=getDomainFromActor(postJsonObject['actor'])
  183. if not postDomain:
  184. pprint(postJsonObject)
  185. print('No post Domain in actor')
  186. return None
  187. if isBlocked(baseDir,nickname,domain,postNickname,postDomain):
  188. if debug:
  189. print('DEBUG: post from '+postNickname+' blocked')
  190. return None
  191. if postPort:
  192. if postPort!=80 and postPort!=443:
  193. if ':' not in postDomain:
  194. postDomain=postDomain+':'+str(postPort)
  195. if postJsonObject.get('object'):
  196. if isinstance(postJsonObject['object'], dict):
  197. if postJsonObject['object'].get('inReplyTo'):
  198. if isinstance(postJsonObject['object']['inReplyTo'], str):
  199. replyNickname=getNicknameFromActor(postJsonObject['object']['inReplyTo'])
  200. replyDomain,replyPort=getDomainFromActor(postJsonObject['object']['inReplyTo'])
  201. if replyNickname and replyDomain:
  202. if isBlocked(baseDir,nickname,domain,replyNickname,replyDomain):
  203. print('WARN: post contains reply to a blocked account: '+replyNickname+'@'+replyDomain)
  204. return None
  205. else:
  206. print('WARN: post is a reply to an unidentified account: '+postJsonObject['object']['inReplyTo'])
  207. return None
  208. if postJsonObject['object'].get('content'):
  209. if isinstance(postJsonObject['object']['content'], str):
  210. if isFiltered(baseDir,nickname,domain,postJsonObject['object']['content']):
  211. print('WARN: post was filtered out due to content')
  212. return None
  213. originalPostId=None
  214. if postJsonObject.get('id'):
  215. originalPostId=postJsonObject['id'].replace('/activity','').replace('/undo','')
  216. currTime=datetime.datetime.utcnow()
  217. postId=None
  218. if postJsonObject.get('id'):
  219. #if '/statuses/' not in postJsonObject['id']:
  220. postId=postJsonObject['id'].replace('/activity','').replace('/undo','')
  221. published=currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  222. if not postId:
  223. statusNumber,published = getStatusNumber()
  224. if actor:
  225. postId=actor+'/statuses/'+statusNumber
  226. else:
  227. postId=httpPrefix+'://'+originalDomain+'/users/'+nickname+'/statuses/'+statusNumber
  228. # NOTE: don't change postJsonObject['id'] before signature check
  229. inboxQueueDir=createInboxQueueDir(nickname,domain,baseDir)
  230. handle=nickname+'@'+domain
  231. destination=baseDir+'/accounts/'+handle+'/inbox/'+postId.replace('/','#')+'.json'
  232. #if os.path.isfile(destination):
  233. # if debug:
  234. # print(destination)
  235. # print('DEBUG: inbox item already exists')
  236. # return None
  237. filename=inboxQueueDir+'/'+postId.replace('/','#')+'.json'
  238. sharedInboxItem=False
  239. if nickname=='inbox':
  240. nickname=originalDomain
  241. sharedInboxItem=True
  242. newQueueItem = {
  243. 'originalId': originalPostId,
  244. 'id': postId,
  245. 'actor': actor,
  246. 'nickname': nickname,
  247. 'domain': domain,
  248. 'postNickname': postNickname,
  249. 'postDomain': postDomain,
  250. 'sharedInbox': sharedInboxItem,
  251. 'published': published,
  252. 'httpHeaders': httpHeaders,
  253. 'path': postPath,
  254. 'post': postJsonObject,
  255. 'digest': messageContentDigest(messageBytes),
  256. 'filename': filename,
  257. 'destination': destination
  258. }
  259. if debug:
  260. print('Inbox queue item created')
  261. pprint(newQueueItem)
  262. with open(filename, 'w') as fp:
  263. commentjson.dump(newQueueItem, fp, indent=4, sort_keys=False)
  264. return filename
  265. def inboxCheckCapabilities(baseDir :str,nickname :str,domain :str, \
  266. actor: str,queue: [],queueJson: {}, \
  267. capabilityId: str,debug : bool) -> bool:
  268. if nickname=='inbox':
  269. return True
  270. ocapFilename= \
  271. getOcapFilename(baseDir, \
  272. queueJson['nickname'],queueJson['domain'], \
  273. actor,'accept')
  274. if not ocapFilename:
  275. return False
  276. if not os.path.isfile(ocapFilename):
  277. if debug:
  278. print('DEBUG: capabilities for '+ \
  279. actor+' do not exist')
  280. os.remove(queueFilename)
  281. queue.pop(0)
  282. return False
  283. with open(ocapFilename, 'r') as fp:
  284. oc=commentjson.load(fp)
  285. if not oc.get('id'):
  286. if debug:
  287. print('DEBUG: capabilities for '+actor+' do not contain an id')
  288. os.remove(queueFilename)
  289. queue.pop(0)
  290. return False
  291. if oc['id']!=capabilityId:
  292. if debug:
  293. print('DEBUG: capability id mismatch')
  294. os.remove(queueFilename)
  295. queue.pop(0)
  296. return False
  297. if not oc.get('capability'):
  298. if debug:
  299. print('DEBUG: missing capability list')
  300. os.remove(queueFilename)
  301. queue.pop(0)
  302. return False
  303. if not CapablePost(queueJson['post'],oc['capability'],debug):
  304. if debug:
  305. print('DEBUG: insufficient capabilities to write to inbox from '+actor)
  306. os.remove(queueFilename)
  307. queue.pop(0)
  308. return False
  309. if debug:
  310. print('DEBUG: object capabilities check success')
  311. return True
  312. def inboxPostRecipientsAdd(baseDir :str,httpPrefix :str,toList :[], \
  313. recipientsDict :{}, \
  314. domainMatch: str,domain :str, \
  315. actor :str,debug: bool) -> bool:
  316. """Given a list of post recipients (toList) from 'to' or 'cc' parameters
  317. populate a recipientsDict with the handle and capabilities id for each
  318. """
  319. followerRecipients=False
  320. for recipient in toList:
  321. if not recipient:
  322. continue
  323. # is this a to a local account?
  324. if domainMatch in recipient:
  325. # get the handle for the local account
  326. nickname=recipient.split(domainMatch)[1]
  327. handle=nickname+'@'+domain
  328. if os.path.isdir(baseDir+'/accounts/'+handle):
  329. # are capabilities granted for this account to the
  330. # sender (actor) of the post?
  331. ocapFilename=baseDir+'/accounts/'+handle+'/ocap/accept/'+actor.replace('/','#')+'.json'
  332. if os.path.isfile(ocapFilename):
  333. # read the granted capabilities and obtain the id
  334. with open(ocapFilename, 'r') as fp:
  335. ocapJson=commentjson.load(fp)
  336. if ocapJson.get('id'):
  337. # append with the capabilities id
  338. recipientsDict[handle]=ocapJson['id']
  339. else:
  340. recipientsDict[handle]=None
  341. else:
  342. if debug:
  343. print('DEBUG: '+ocapFilename+' not found')
  344. recipientsDict[handle]=None
  345. else:
  346. if debug:
  347. print('DEBUG: '+baseDir+'/accounts/'+handle+' does not exist')
  348. else:
  349. if debug:
  350. print('DEBUG: '+recipient+' is not local to '+domainMatch)
  351. print(str(toList))
  352. if recipient.endswith('followers'):
  353. if debug:
  354. print('DEBUG: followers detected as post recipients')
  355. followerRecipients=True
  356. return followerRecipients,recipientsDict
  357. def inboxPostRecipients(baseDir :str,postJsonObject :{}, \
  358. httpPrefix :str,domain : str,port :int, \
  359. debug :bool) -> ([],[]):
  360. """Returns dictionaries containing the recipients of the given post
  361. The shared dictionary contains followers
  362. """
  363. recipientsDict={}
  364. recipientsDictFollowers={}
  365. if not postJsonObject.get('actor'):
  366. if debug:
  367. pprint(postJsonObject)
  368. print('WARNING: inbox post has no actor')
  369. return recipientsDict,recipientsDictFollowers
  370. if ':' in domain:
  371. domain=domain.split(':')[0]
  372. domainBase=domain
  373. if port:
  374. if port!=80 and port!=443:
  375. if ':' not in domain:
  376. domain=domain+':'+str(port)
  377. domainMatch='/'+domain+'/users/'
  378. actor = postJsonObject['actor']
  379. # first get any specific people which the post is addressed to
  380. followerRecipients=False
  381. if postJsonObject.get('object'):
  382. if isinstance(postJsonObject['object'], dict):
  383. if postJsonObject['object'].get('to'):
  384. if isinstance(postJsonObject['object']['to'], list):
  385. recipientsList=postJsonObject['object']['to']
  386. else:
  387. recipientsList=[postJsonObject['object']['to']]
  388. if debug:
  389. print('DEBUG: resolving "to"')
  390. includesFollowers,recipientsDict= \
  391. inboxPostRecipientsAdd(baseDir,httpPrefix, \
  392. recipientsList, \
  393. recipientsDict, \
  394. domainMatch,domainBase, \
  395. actor,debug)
  396. if includesFollowers:
  397. followerRecipients=True
  398. else:
  399. if debug:
  400. print('DEBUG: inbox post has no "to"')
  401. if postJsonObject['object'].get('cc'):
  402. if isinstance(postJsonObject['object']['cc'], list):
  403. recipientsList=postJsonObject['object']['cc']
  404. else:
  405. recipientsList=[postJsonObject['object']['cc']]
  406. includesFollowers,recipientsDict= \
  407. inboxPostRecipientsAdd(baseDir,httpPrefix, \
  408. recipientsList, \
  409. recipientsDict, \
  410. domainMatch,domainBase, \
  411. actor,debug)
  412. if includesFollowers:
  413. followerRecipients=True
  414. else:
  415. if debug:
  416. print('DEBUG: inbox post has no cc')
  417. else:
  418. if debug:
  419. if isinstance(postJsonObject['object'], str):
  420. if '/statuses/' in postJsonObject['object']:
  421. print('DEBUG: inbox item is a link to a post')
  422. else:
  423. if '/users/' in postJsonObject['object']:
  424. print('DEBUG: inbox item is a link to an actor')
  425. if postJsonObject.get('to'):
  426. if isinstance(postJsonObject['to'], list):
  427. recipientsList=postJsonObject['to']
  428. else:
  429. recipientsList=[postJsonObject['to']]
  430. includesFollowers,recipientsDict= \
  431. inboxPostRecipientsAdd(baseDir,httpPrefix, \
  432. recipientsList, \
  433. recipientsDict, \
  434. domainMatch,domainBase, \
  435. actor,debug)
  436. if includesFollowers:
  437. followerRecipients=True
  438. if postJsonObject.get('cc'):
  439. if isinstance(postJsonObject['cc'], list):
  440. recipientsList=postJsonObject['cc']
  441. else:
  442. recipientsList=[postJsonObject['cc']]
  443. includesFollowers,recipientsDict= \
  444. inboxPostRecipientsAdd(baseDir,httpPrefix, \
  445. recipientsList, \
  446. recipientsDict, \
  447. domainMatch,domainBase, \
  448. actor,debug)
  449. if includesFollowers:
  450. followerRecipients=True
  451. if not followerRecipients:
  452. if debug:
  453. print('DEBUG: no followers were resolved')
  454. return recipientsDict,recipientsDictFollowers
  455. # now resolve the followers
  456. recipientsDictFollowers= \
  457. getFollowersOfActor(baseDir,actor,debug)
  458. return recipientsDict,recipientsDictFollowers
  459. def receiveUndoFollow(session,baseDir: str,httpPrefix: str, \
  460. port: int,messageJson: {}, \
  461. federationList: [], \
  462. debug : bool) -> bool:
  463. if not messageJson['object'].get('actor'):
  464. if debug:
  465. print('DEBUG: follow request has no actor within object')
  466. return False
  467. if '/users/' not in messageJson['object']['actor'] and '/profile/' not in messageJson['object']['actor']:
  468. if debug:
  469. print('DEBUG: "users" or "profile" missing from actor within object')
  470. return False
  471. if messageJson['object']['actor'] != messageJson['actor']:
  472. if debug:
  473. print('DEBUG: actors do not match')
  474. return False
  475. nicknameFollower=getNicknameFromActor(messageJson['object']['actor'])
  476. if not nicknameFollower:
  477. print('WARN: unable to find nickname in '+messageJson['object']['actor'])
  478. return False
  479. domainFollower,portFollower=getDomainFromActor(messageJson['object']['actor'])
  480. domainFollowerFull=domainFollower
  481. if portFollower:
  482. if portFollower!=80 and portFollower!=443:
  483. if ':' not in domainFollower:
  484. domainFollowerFull=domainFollower+':'+str(portFollower)
  485. nicknameFollowing=getNicknameFromActor(messageJson['object']['object'])
  486. if not nicknameFollowing:
  487. print('WARN: unable to find nickname in '+messageJson['object']['object'])
  488. return False
  489. domainFollowing,portFollowing=getDomainFromActor(messageJson['object']['object'])
  490. domainFollowingFull=domainFollowing
  491. if portFollowing:
  492. if portFollowing!=80 and portFollowing!=443:
  493. if ':' not in domainFollowing:
  494. domainFollowingFull=domainFollowing+':'+str(portFollowing)
  495. if unfollowerOfPerson(baseDir, \
  496. nicknameFollowing,domainFollowingFull, \
  497. nicknameFollower,domainFollowerFull, \
  498. debug):
  499. if debug:
  500. print('DEBUG: Follower '+nicknameFollower+'@'+domainFollowerFull+' was removed')
  501. return True
  502. if debug:
  503. print('DEBUG: Follower '+nicknameFollower+'@'+domainFollowerFull+' was not removed')
  504. return False
  505. def receiveUndo(session,baseDir: str,httpPrefix: str, \
  506. port: int,sendThreads: [],postLog: [], \
  507. cachedWebfingers: {},personCache: {}, \
  508. messageJson: {},federationList: [], \
  509. debug : bool, \
  510. acceptedCaps=["inbox:write","objects:read"]) -> bool:
  511. """Receives an undo request within the POST section of HTTPServer
  512. """
  513. if not messageJson['type'].startswith('Undo'):
  514. return False
  515. if debug:
  516. print('DEBUG: Undo activity received')
  517. if not messageJson.get('actor'):
  518. if debug:
  519. print('DEBUG: follow request has no actor')
  520. return False
  521. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  522. if debug:
  523. print('DEBUG: "users" or "profile" missing from actor')
  524. return False
  525. if not messageJson.get('object'):
  526. if debug:
  527. print('DEBUG: '+messageJson['type']+' has no object')
  528. return False
  529. if not isinstance(messageJson['object'], dict):
  530. if debug:
  531. print('DEBUG: '+messageJson['type']+' object is not a dict')
  532. return False
  533. if not messageJson['object'].get('type'):
  534. if debug:
  535. print('DEBUG: '+messageJson['type']+' has no object type')
  536. return False
  537. if not messageJson['object'].get('object'):
  538. if debug:
  539. print('DEBUG: '+messageJson['type']+' has no object within object')
  540. return False
  541. if not isinstance(messageJson['object']['object'], str):
  542. if debug:
  543. print('DEBUG: '+messageJson['type']+' object within object is not a string')
  544. return False
  545. if messageJson['object']['type']=='Follow':
  546. return receiveUndoFollow(session,baseDir,httpPrefix, \
  547. port,messageJson, \
  548. federationList, \
  549. debug)
  550. return False
  551. def personReceiveUpdate(baseDir: str, \
  552. domain: str,port: int, \
  553. updateNickname: str,updateDomain: str,updatePort: int, \
  554. personJson: {},personCache: {},debug: bool) -> bool:
  555. """Changes an actor. eg: avatar or display name change
  556. """
  557. if debug:
  558. print('DEBUG: receiving actor update for '+personJson['url'])
  559. domainFull=domain
  560. if port:
  561. if port!=80 and port!=443:
  562. domainFull=domain+':'+str(port)
  563. updateDomainFull=updateDomain
  564. if updatePort:
  565. if updatePort!=80 and updatePort!=443:
  566. updateDomainFull=updateDomain+':'+str(updatePort)
  567. actor=updateDomainFull+'/users/'+updateNickname
  568. if actor not in personJson['id']:
  569. if debug:
  570. print('actor: '+actor)
  571. print('id: '+personJson['id'])
  572. print('DEBUG: Actor does not match id')
  573. return False
  574. if updateDomainFull==domainFull:
  575. if debug:
  576. print('DEBUG: You can only receive actor updates for domains other than your own')
  577. return False
  578. if not personJson.get('publicKey'):
  579. if debug:
  580. print('DEBUG: actor update does not contain a public key')
  581. return False
  582. if not personJson['publicKey'].get('publicKeyPem'):
  583. if debug:
  584. print('DEBUG: actor update does not contain a public key Pem')
  585. return False
  586. actorFilename=baseDir+'/cache/actors/'+personJson['id'].replace('/','#')+'.json'
  587. # check that the public keys match.
  588. # If they don't then this may be a nefarious attempt to hack an account
  589. if personCache.get(personJson['id']):
  590. if personCache[personJson['id']]['actor']['publicKey']['publicKeyPem']!=personJson['publicKey']['publicKeyPem']:
  591. if debug:
  592. print('WARN: Public key does not match when updating actor')
  593. return False
  594. else:
  595. if os.path.isfile(actorFilename):
  596. with open(actorFilename, 'r') as fp:
  597. existingPersonJson=commentjson.load(fp)
  598. if existingPersonJson['publicKey']['publicKeyPem']!=personJson['publicKey']['publicKeyPem']:
  599. if debug:
  600. print('WARN: Public key does not match cached actor when updating')
  601. return False
  602. # save to cache in memory
  603. storePersonInCache(baseDir,personJson['id'],personJson,personCache)
  604. # save to cache on file
  605. with open(actorFilename, 'w') as fp:
  606. commentjson.dump(personJson, fp, indent=4, sort_keys=False)
  607. print('actor updated for '+personJson['id'])
  608. return True
  609. def receiveUpdate(session,baseDir: str, \
  610. httpPrefix: str,domain :str,port: int, \
  611. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  612. personCache: {},messageJson: {},federationList: [], \
  613. debug : bool) -> bool:
  614. """Receives an Update activity within the POST section of HTTPServer
  615. """
  616. if messageJson['type']!='Update':
  617. return False
  618. if not messageJson.get('actor'):
  619. if debug:
  620. print('DEBUG: '+messageJson['type']+' has no actor')
  621. return False
  622. if not messageJson.get('object'):
  623. if debug:
  624. print('DEBUG: '+messageJson['type']+' has no object')
  625. return False
  626. if not isinstance(messageJson['object'], dict):
  627. if debug:
  628. print('DEBUG: '+messageJson['type']+' object is not a dict')
  629. return False
  630. if not messageJson['object'].get('type'):
  631. if debug:
  632. print('DEBUG: '+messageJson['type']+' object has no type')
  633. return False
  634. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  635. if debug:
  636. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type'])
  637. return False
  638. if messageJson['object']['type']=='Person' or \
  639. messageJson['object']['type']=='Application' or \
  640. messageJson['object']['type']=='Service':
  641. if messageJson['object'].get('url') and messageJson['object'].get('id'):
  642. print('Request to update actor: '+messageJson['actor'])
  643. updateNickname=getNicknameFromActor(messageJson['actor'])
  644. if updateNickname:
  645. updateDomain,updatePort=getDomainFromActor(messageJson['actor'])
  646. if personReceiveUpdate(baseDir, \
  647. domain,port, \
  648. updateNickname,updateDomain,updatePort, \
  649. messageJson['object'], \
  650. personCache,debug):
  651. if debug:
  652. print('DEBUG: Profile update was received for '+messageJson['object']['url'])
  653. return True
  654. if messageJson['object'].get('capability') and messageJson['object'].get('scope'):
  655. nickname=getNicknameFromActor(messageJson['object']['scope'])
  656. if nickname:
  657. domain,tempPort=getDomainFromActor(messageJson['object']['scope'])
  658. if messageJson['object']['type']=='Capability':
  659. if capabilitiesReceiveUpdate(baseDir,nickname,domain,port,
  660. messageJson['actor'], \
  661. messageJson['object']['id'], \
  662. messageJson['object']['capability'], \
  663. debug):
  664. if debug:
  665. print('DEBUG: An update was received')
  666. return True
  667. return False
  668. def receiveLike(session,handle: str,baseDir: str, \
  669. httpPrefix: str,domain :str,port: int, \
  670. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  671. personCache: {},messageJson: {},federationList: [], \
  672. debug : bool) -> bool:
  673. """Receives a Like activity within the POST section of HTTPServer
  674. """
  675. if messageJson['type']!='Like':
  676. return False
  677. if not messageJson.get('actor'):
  678. if debug:
  679. print('DEBUG: '+messageJson['type']+' has no actor')
  680. return False
  681. if not messageJson.get('object'):
  682. if debug:
  683. print('DEBUG: '+messageJson['type']+' has no object')
  684. return False
  685. if not isinstance(messageJson['object'], str):
  686. if debug:
  687. print('DEBUG: '+messageJson['type']+' object is not a string')
  688. return False
  689. if not messageJson.get('to'):
  690. if debug:
  691. print('DEBUG: '+messageJson['type']+' has no "to" list')
  692. return False
  693. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  694. if debug:
  695. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type'])
  696. return False
  697. if '/statuses/' not in messageJson['object']:
  698. if debug:
  699. print('DEBUG: "statuses" missing from object in '+messageJson['type'])
  700. return False
  701. if not os.path.isdir(baseDir+'/accounts/'+handle):
  702. print('DEBUG: unknown recipient of like - '+handle)
  703. # if this post in the outbox of the person?
  704. postFilename=locatePost(baseDir,handle.split('@')[0],handle.split('@')[1],messageJson['object'])
  705. if not postFilename:
  706. if debug:
  707. print('DEBUG: post not found in inbox or outbox')
  708. print(messageJson['object'])
  709. return True
  710. if debug:
  711. print('DEBUG: liked post found in inbox')
  712. updateLikesCollection(postFilename,messageJson['object'],messageJson['actor'],debug)
  713. return True
  714. def receiveUndoLike(session,handle: str,baseDir: str, \
  715. httpPrefix: str,domain :str,port: int, \
  716. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  717. personCache: {},messageJson: {},federationList: [], \
  718. debug : bool) -> bool:
  719. """Receives an undo like activity within the POST section of HTTPServer
  720. """
  721. if messageJson['type']!='Undo':
  722. return False
  723. if not messageJson.get('actor'):
  724. return False
  725. if not messageJson.get('object'):
  726. return False
  727. if not isinstance(messageJson['object'], dict):
  728. return False
  729. if not messageJson['object'].get('type'):
  730. return False
  731. if messageJson['object']['type']!='Like':
  732. return False
  733. if not messageJson['object'].get('object'):
  734. if debug:
  735. print('DEBUG: '+messageJson['type']+' like has no object')
  736. return False
  737. if not isinstance(messageJson['object']['object'], str):
  738. if debug:
  739. print('DEBUG: '+messageJson['type']+' like object is not a string')
  740. return False
  741. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  742. if debug:
  743. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type']+' like')
  744. return False
  745. if '/statuses/' not in messageJson['object']['object']:
  746. if debug:
  747. print('DEBUG: "statuses" missing from like object in '+messageJson['type'])
  748. return False
  749. if not os.path.isdir(baseDir+'/accounts/'+handle):
  750. print('DEBUG: unknown recipient of undo like - '+handle)
  751. # if this post in the outbox of the person?
  752. postFilename=locatePost(baseDir,handle.split('@')[0],handle.split('@')[1],messageJson['object']['object'])
  753. if not postFilename:
  754. if debug:
  755. print('DEBUG: unliked post not found in inbox or outbox')
  756. print(messageJson['object']['object'])
  757. return True
  758. if debug:
  759. print('DEBUG: liked post found in inbox. Now undoing.')
  760. undoLikesCollectionEntry(postFilename,messageJson['object'],messageJson['actor'],debug)
  761. return True
  762. def receiveDelete(session,handle: str,baseDir: str, \
  763. httpPrefix: str,domain :str,port: int, \
  764. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  765. personCache: {},messageJson: {},federationList: [], \
  766. debug : bool,allowDeletion: bool) -> bool:
  767. """Receives a Delete activity within the POST section of HTTPServer
  768. """
  769. if messageJson['type']!='Delete':
  770. return False
  771. if not messageJson.get('actor'):
  772. if debug:
  773. print('DEBUG: '+messageJson['type']+' has no actor')
  774. return False
  775. if debug:
  776. print('DEBUG: Delete activity arrived')
  777. if not messageJson.get('object'):
  778. if debug:
  779. print('DEBUG: '+messageJson['type']+' has no object')
  780. return False
  781. if not isinstance(messageJson['object'], str):
  782. if debug:
  783. print('DEBUG: '+messageJson['type']+' object is not a string')
  784. return False
  785. domainFull=domain
  786. if port:
  787. if port!=80 and port!=443:
  788. if ':' not in domain:
  789. domainFull=domain+':'+str(port)
  790. deletePrefix=httpPrefix+'://'+domainFull+'/'
  791. if not allowDeletion and \
  792. (not messageJson['object'].startswith(deletePrefix) or \
  793. not messageJson['actor'].startswith(deletePrefix)):
  794. if debug:
  795. print('DEBUG: delete not permitted from other instances')
  796. return False
  797. if not messageJson.get('to'):
  798. if debug:
  799. print('DEBUG: '+messageJson['type']+' has no "to" list')
  800. return False
  801. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  802. if debug:
  803. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type'])
  804. return False
  805. if '/statuses/' not in messageJson['object']:
  806. if debug:
  807. print('DEBUG: "statuses" missing from object in '+messageJson['type'])
  808. return False
  809. if messageJson['actor'] not in messageJson['object']:
  810. if debug:
  811. print('DEBUG: actor is not the owner of the post to be deleted')
  812. if not os.path.isdir(baseDir+'/accounts/'+handle):
  813. print('DEBUG: unknown recipient of like - '+handle)
  814. # if this post in the outbox of the person?
  815. messageId=messageJson['object'].replace('/activity','').replace('/undo','')
  816. removeModerationPostFromIndex(baseDir,messageId,debug)
  817. postFilename=locatePost(baseDir,handle.split('@')[0],handle.split('@')[1],messageId)
  818. if not postFilename:
  819. if debug:
  820. print('DEBUG: delete post not found in inbox or outbox')
  821. print(messageId)
  822. return True
  823. deletePost(baseDir,httpPrefix,handle.split('@')[0],handle.split('@')[1],postFilename,debug)
  824. if debug:
  825. print('DEBUG: post deleted - '+postFilename)
  826. return True
  827. def receiveAnnounce(session,handle: str,baseDir: str, \
  828. httpPrefix: str,domain :str,port: int, \
  829. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  830. personCache: {},messageJson: {},federationList: [], \
  831. debug : bool) -> bool:
  832. """Receives an announce activity within the POST section of HTTPServer
  833. """
  834. if messageJson['type']!='Announce':
  835. return False
  836. if not messageJson.get('actor'):
  837. if debug:
  838. print('DEBUG: '+messageJson['type']+' has no actor')
  839. return False
  840. if debug:
  841. print('DEBUG: receiving announce on '+handle)
  842. if not messageJson.get('object'):
  843. if debug:
  844. print('DEBUG: '+messageJson['type']+' has no object')
  845. return False
  846. if not isinstance(messageJson['object'], str):
  847. if debug:
  848. print('DEBUG: '+messageJson['type']+' object is not a string')
  849. return False
  850. if not messageJson.get('to'):
  851. if debug:
  852. print('DEBUG: '+messageJson['type']+' has no "to" list')
  853. return False
  854. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  855. if debug:
  856. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type'])
  857. return False
  858. if '/users/' not in messageJson['object'] and '/profile/' not in messageJson['object']:
  859. if debug:
  860. print('DEBUG: "users" or "profile" missing in '+messageJson['type'])
  861. return False
  862. if '/statuses/' not in messageJson['object']:
  863. if debug:
  864. print('DEBUG: "statuses" missing from object in '+messageJson['type'])
  865. return False
  866. objectDomain=messageJson['object'].replace('https://','').replace('http://','').replace('dat://','')
  867. if '/' in objectDomain:
  868. objectDomain=objectDomain.split('/')[0]
  869. if isBlockedDomain(baseDir,objectDomain):
  870. if debug:
  871. print('DEBUG: announced domain is blocked')
  872. return False
  873. if not os.path.isdir(baseDir+'/accounts/'+handle):
  874. print('DEBUG: unknown recipient of announce - '+handle)
  875. # is this post in the outbox of the person?
  876. postFilename=locatePost(baseDir,handle.split('@')[0],handle.split('@')[1],messageJson['object'])
  877. if not postFilename:
  878. if debug:
  879. print('DEBUG: announce post not found in inbox or outbox')
  880. print(messageJson['object'])
  881. return True
  882. updateAnnounceCollection(postFilename,messageJson['actor'],debug)
  883. if debug:
  884. print('DEBUG: announced/repeated post found in inbox')
  885. return True
  886. def receiveUndoAnnounce(session,handle: str,baseDir: str, \
  887. httpPrefix: str,domain :str,port: int, \
  888. sendThreads: [],postLog: [],cachedWebfingers: {}, \
  889. personCache: {},messageJson: {},federationList: [], \
  890. debug : bool) -> bool:
  891. """Receives an undo announce activity within the POST section of HTTPServer
  892. """
  893. if messageJson['type']!='Undo':
  894. return False
  895. if not messageJson.get('actor'):
  896. return False
  897. if not messageJson.get('object'):
  898. return False
  899. if not isinstance(messageJson['object'], dict):
  900. return False
  901. if not messageJson['object'].get('object'):
  902. return False
  903. if not isinstance(messageJson['object']['object'], str):
  904. return False
  905. if messageJson['object']['type']!='Announce':
  906. return False
  907. if '/users/' not in messageJson['actor'] and '/profile/' not in messageJson['actor']:
  908. if debug:
  909. print('DEBUG: "users" or "profile" missing from actor in '+messageJson['type']+' announce')
  910. return False
  911. if '/statuses/' not in messageJson['object']:
  912. if debug:
  913. print('DEBUG: "statuses" missing from object in '+messageJson['type']+' announce')
  914. return False
  915. if not os.path.isdir(baseDir+'/accounts/'+handle):
  916. print('DEBUG: unknown recipient of undo announce - '+handle)
  917. # if this post in the outbox of the person?
  918. postFilename=locatePost(baseDir,handle.split('@')[0],handle.split('@')[1],messageJson['object'])
  919. if not postFilename:
  920. if debug:
  921. print('DEBUG: undo announce post not found in inbox or outbox')
  922. print(messageJson['object']['object'])
  923. return True
  924. if debug:
  925. print('DEBUG: announced/repeated post to be undone found in inbox')
  926. with open(postFilename, 'r') as fp:
  927. postJsonObject=commentjson.load(fp)
  928. if not postJsonObject.get('type'):
  929. if postJsonObject['type']!='Announce':
  930. if debug:
  931. print("DEBUG: Attempt to undo something which isn't an announcement")
  932. return False
  933. undoAnnounceCollectionEntry(postFilename,messageJson['actor'],debug)
  934. os.remove(postFilename)
  935. return True
  936. def populateReplies(baseDir :str,httpPrefix :str,domain :str, \
  937. messageJson :{},maxReplies: int,debug :bool) -> bool:
  938. """Updates the list of replies for a post on this domain if
  939. a reply to it arrives
  940. """
  941. if not messageJson.get('id'):
  942. return False
  943. if not messageJson.get('object'):
  944. return False
  945. if not isinstance(messageJson['object'], dict):
  946. return False
  947. if not messageJson['object'].get('inReplyTo'):
  948. return False
  949. if not messageJson['object'].get('to'):
  950. return False
  951. replyTo=messageJson['object']['inReplyTo']
  952. if debug:
  953. print('DEBUG: post contains a reply')
  954. # is this a reply to a post on this domain?
  955. if not replyTo.startswith(httpPrefix+'://'+domain+'/'):
  956. if debug:
  957. print('DEBUG: post is a reply to another not on this domain')
  958. print(replyTo)
  959. print('Expected: '+httpPrefix+'://'+domain+'/')
  960. return False
  961. replyToNickname=getNicknameFromActor(replyTo)
  962. if not replyToNickname:
  963. print('DEBUG: no nickname found for '+replyTo)
  964. return False
  965. replyToDomain,replyToPort=getDomainFromActor(replyTo)
  966. if not replyToDomain:
  967. if debug:
  968. print('DEBUG: no domain found for '+replyTo)
  969. return False
  970. postFilename=locatePost(baseDir,replyToNickname,replyToDomain,replyTo)
  971. if not postFilename:
  972. if debug:
  973. print('DEBUG: post may have expired - '+replyTo)
  974. return False
  975. # populate a text file containing the ids of replies
  976. postRepliesFilename=postFilename.replace('.json','.replies')
  977. messageId=messageJson['id'].replace('/activity','').replace('/undo','')
  978. if os.path.isfile(postRepliesFilename):
  979. numLines = sum(1 for line in open(postRepliesFilename))
  980. if numLines>maxReplies:
  981. return False
  982. if messageId not in open(postRepliesFilename).read():
  983. repliesFile=open(postRepliesFilename, "a")
  984. repliesFile.write(messageId+'\n')
  985. repliesFile.close()
  986. else:
  987. repliesFile=open(postRepliesFilename, "w")
  988. repliesFile.write(messageId+'\n')
  989. repliesFile.close()
  990. return True
  991. def inboxAfterCapabilities(session,keyId: str,handle: str,messageJson: {}, \
  992. baseDir: str,httpPrefix: str,sendThreads: [], \
  993. postLog: [],cachedWebfingers: {},personCache: {}, \
  994. queue: [],domain: str,port: int,useTor: bool, \
  995. federationList: [],ocapAlways: bool,debug: bool, \
  996. acceptedCaps: [], \
  997. queueFilename :str,destinationFilename :str, \
  998. maxReplies: int,allowDeletion: bool) -> bool:
  999. """ Anything which needs to be done after capabilities checks have passed
  1000. """
  1001. if receiveLike(session,handle, \
  1002. baseDir,httpPrefix, \
  1003. domain,port, \
  1004. sendThreads,postLog, \
  1005. cachedWebfingers, \
  1006. personCache, \
  1007. messageJson, \
  1008. federationList, \
  1009. debug):
  1010. if debug:
  1011. print('DEBUG: Like accepted from '+keyId)
  1012. return False
  1013. if receiveUndoLike(session,handle, \
  1014. baseDir,httpPrefix, \
  1015. domain,port, \
  1016. sendThreads,postLog, \
  1017. cachedWebfingers, \
  1018. personCache, \
  1019. messageJson, \
  1020. federationList, \
  1021. debug):
  1022. if debug:
  1023. print('DEBUG: Undo like accepted from '+keyId)
  1024. return False
  1025. if receiveAnnounce(session,handle, \
  1026. baseDir,httpPrefix, \
  1027. domain,port, \
  1028. sendThreads,postLog, \
  1029. cachedWebfingers, \
  1030. personCache, \
  1031. messageJson, \
  1032. federationList, \
  1033. debug):
  1034. if debug:
  1035. print('DEBUG: Announce accepted from '+keyId)
  1036. if receiveUndoAnnounce(session,handle, \
  1037. baseDir,httpPrefix, \
  1038. domain,port, \
  1039. sendThreads,postLog, \
  1040. cachedWebfingers, \
  1041. personCache, \
  1042. messageJson, \
  1043. federationList, \
  1044. debug):
  1045. if debug:
  1046. print('DEBUG: Undo announce accepted from '+keyId)
  1047. return False
  1048. if receiveDelete(session,handle, \
  1049. baseDir,httpPrefix, \
  1050. domain,port, \
  1051. sendThreads,postLog, \
  1052. cachedWebfingers, \
  1053. personCache, \
  1054. messageJson, \
  1055. federationList, \
  1056. debug,allowDeletion):
  1057. if debug:
  1058. print('DEBUG: Delete accepted from '+keyId)
  1059. return False
  1060. populateReplies(baseDir,httpPrefix,domain,messageJson,maxReplies,debug)
  1061. if debug:
  1062. print('DEBUG: object capabilities passed')
  1063. print('copy queue file from '+queueFilename+' to '+destinationFilename)
  1064. if messageJson.get('postNickname'):
  1065. with open(destinationFilename, 'w+') as fp:
  1066. commentjson.dump(messageJson['post'], fp, indent=4, sort_keys=False)
  1067. else:
  1068. with open(destinationFilename, 'w+') as fp:
  1069. commentjson.dump(messageJson, fp, indent=4, sort_keys=False)
  1070. if not os.path.isfile(destinationFilename):
  1071. return False
  1072. return True
  1073. def restoreQueueItems(baseDir: str,queue: []) -> None:
  1074. """Checks the queue for each account and appends filenames
  1075. """
  1076. queue.clear()
  1077. for subdir,dirs,files in os.walk(baseDir+'/accounts'):
  1078. for account in dirs:
  1079. queueDir=baseDir+'/accounts/'+account+'/queue'
  1080. if os.path.isdir(queueDir):
  1081. for queuesubdir,queuedirs,queuefiles in os.walk(queueDir):
  1082. for qfile in queuefiles:
  1083. queue.append(os.path.join(queueDir, qfile))
  1084. if len(queue)>0:
  1085. print('Restored '+str(len(queue))+' inbox queue items')
  1086. def runInboxQueueWatchdog(projectVersion: str,httpd) -> None:
  1087. """This tries to keep the inbox thread running even if it dies
  1088. """
  1089. print('Starting inbox queue watchdog')
  1090. inboxQueueOriginal=httpd.thrInboxQueue.clone(runInboxQueue)
  1091. #httpd.thrInboxQueue=inboxQueueOriginal
  1092. httpd.thrInboxQueue.start()
  1093. while True:
  1094. time.sleep(20)
  1095. if not httpd.thrInboxQueue.isAlive():
  1096. httpd.thrInboxQueue.kill()
  1097. httpd.thrInboxQueue=inboxQueueOriginal.clone(runInboxQueue)
  1098. httpd.thrInboxQueue.start()
  1099. print('Restarting inbox queue...')
  1100. def runInboxQueue(projectVersion: str, \
  1101. baseDir: str,httpPrefix: str,sendThreads: [],postLog: [], \
  1102. cachedWebfingers: {},personCache: {},queue: [], \
  1103. domain: str,port: int,useTor: bool,federationList: [], \
  1104. ocapAlways: bool,maxReplies: int, \
  1105. domainMaxPostsPerDay: int,accountMaxPostsPerDay: int, \
  1106. allowDeletion: bool,debug: bool, \
  1107. acceptedCaps=["inbox:write","objects:read"]) -> None:
  1108. """Processes received items and moves them to
  1109. the appropriate directories
  1110. """
  1111. currSessionTime=int(time.time())
  1112. sessionLastUpdate=currSessionTime
  1113. session=createSession(domain,port,useTor)
  1114. inboxHandle='inbox@'+domain
  1115. if debug:
  1116. print('DEBUG: Inbox queue running')
  1117. # if queue processing was interrupted (eg server crash)
  1118. # then this loads any outstanding items back into the queue
  1119. restoreQueueItems(baseDir,queue)
  1120. # keep track of numbers of incoming posts per unit of time
  1121. quotasLastUpdate=int(time.time())
  1122. quotas={
  1123. 'domains': {},
  1124. 'accounts': {}
  1125. }
  1126. # keep track of the number of queue item read failures
  1127. # so that if a file is corrupt then it will eventually
  1128. # be ignored rather than endlessly retried
  1129. itemReadFailed=0
  1130. heartBeatCtr=0
  1131. queueRestoreCtr=0
  1132. while True:
  1133. time.sleep(1)
  1134. # heartbeat to monitor whether the inbox queue is running
  1135. heartBeatCtr+=1
  1136. if heartBeatCtr>=10:
  1137. print('>>> Heartbeat Q:'+str(len(queue))+' '+datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))
  1138. heartBeatCtr=0
  1139. if len(queue)==0:
  1140. # restore any remaining queue items
  1141. queueRestoreCtr+=1
  1142. if queueRestoreCtr>=30:
  1143. queueRestoreCtr=0
  1144. restoreQueueItems(baseDir,queue)
  1145. else:
  1146. currTime=int(time.time())
  1147. # recreate the session periodically
  1148. if not session or currTime-sessionLastUpdate>1200:
  1149. print('Creating inbox session')
  1150. session=createSession(domain,port,useTor)
  1151. sessionLastUpdate=currTime
  1152. # oldest item first
  1153. queue.sort()
  1154. queueFilename=queue[0]
  1155. if not os.path.isfile(queueFilename):
  1156. if debug:
  1157. print("DEBUG: queue item rejected because it has no file: "+queueFilename)
  1158. queue.pop(0)
  1159. continue
  1160. print('Loading queue item '+queueFilename)
  1161. # Load the queue json
  1162. try:
  1163. with open(queueFilename, 'r') as fp:
  1164. queueJson=commentjson.load(fp)
  1165. except:
  1166. itemReadFailed+=1
  1167. print('WARN: Failed to load inbox queue item '+queueFilename+' (try '+str(itemReadFailed)+')')
  1168. if itemReadFailed>4:
  1169. # After a few tries we can assume that the file
  1170. # is probably corrupt/unreadable
  1171. queue.pop(0)
  1172. itemReadFailed=0
  1173. # delete the queue file
  1174. os.remove(queueFilename)
  1175. continue
  1176. itemReadFailed=0
  1177. # clear the daily quotas for maximum numbers of received posts
  1178. if currTime-quotasLastUpdate>60*60*24:
  1179. quotas={
  1180. 'domains': {},
  1181. 'accounts': {}
  1182. }
  1183. quotasLastUpdate=currTime
  1184. # limit the number of posts which can arrive per domain per day
  1185. postDomain=queueJson['postDomain']
  1186. if postDomain:
  1187. if domainMaxPostsPerDay>0:
  1188. if quotas['domains'].get(postDomain):
  1189. if quotas['domains'][postDomain]>domainMaxPostsPerDay:
  1190. if debug:
  1191. print('DEBUG: Maximum posts for '+postDomain+' reached')
  1192. queue.pop(0)
  1193. continue
  1194. quotas['domains'][postDomain]+=1
  1195. else:
  1196. quotas['domains'][postDomain]=1
  1197. if accountMaxPostsPerDay>0:
  1198. postHandle=queueJson['postNickname']+'@'+postDomain
  1199. if quotas['accounts'].get(postHandle):
  1200. if quotas['accounts'][postHandle]>accountMaxPostsPerDay:
  1201. if debug:
  1202. print('DEBUG: Maximum posts for '+postHandle+' reached')
  1203. queue.pop(0)
  1204. continue
  1205. quotas['accounts'][postHandle]+=1
  1206. else:
  1207. quotas['accounts'][postHandle]=1
  1208. if debug:
  1209. if accountMaxPostsPerDay>0 or domainMaxPostsPerDay>0:
  1210. pprint(quotas)
  1211. print('Obtaining public key for actor '+queueJson['actor'])
  1212. # Try a few times to obtain the public key
  1213. pubKey=None
  1214. keyId=None
  1215. for tries in range(8):
  1216. keyId=None
  1217. signatureParams=queueJson['httpHeaders']['signature'].split(',')
  1218. for signatureItem in signatureParams:
  1219. if signatureItem.startswith('keyId='):
  1220. if '"' in signatureItem:
  1221. keyId=signatureItem.split('"')[1]
  1222. break
  1223. if not keyId:
  1224. if debug:
  1225. print('DEBUG: No keyId in signature: '+ \
  1226. queueJson['httpHeaders']['signature'])
  1227. os.remove(queueFilename)
  1228. queue.pop(0)
  1229. continue
  1230. pubKey= \
  1231. getPersonPubKey(baseDir,session,keyId, \
  1232. personCache,debug, \
  1233. projectVersion,httpPrefix,domain)
  1234. if pubKey:
  1235. print('DEBUG: public key: '+str(pubKey))
  1236. break
  1237. if debug:
  1238. print('DEBUG: Retry '+str(tries+1)+ \
  1239. ' obtaining public key for '+keyId)
  1240. time.sleep(5)
  1241. if not pubKey:
  1242. if debug:
  1243. print('DEBUG: public key could not be obtained from '+keyId)
  1244. os.remove(queueFilename)
  1245. queue.pop(0)
  1246. continue
  1247. # check the signature
  1248. if debug:
  1249. print('DEBUG: checking http headers')
  1250. pprint(queueJson['httpHeaders'])
  1251. if not verifyPostHeaders(httpPrefix, \
  1252. pubKey, \
  1253. queueJson['httpHeaders'], \
  1254. queueJson['path'],False, \
  1255. queueJson['digest'], \
  1256. json.dumps(queueJson['post'])):
  1257. if debug:
  1258. print('DEBUG: Header signature check failed')
  1259. os.remove(queueFilename)
  1260. queue.pop(0)
  1261. continue
  1262. if debug:
  1263. print('DEBUG: Signature check success')
  1264. # set the id to the same as the post filename
  1265. # This makes the filename and the id consistent
  1266. #if queueJson['post'].get('id'):
  1267. # queueJson['post']['id']=queueJson['id']
  1268. if receiveUndo(session, \
  1269. baseDir,httpPrefix,port, \
  1270. sendThreads,postLog, \
  1271. cachedWebfingers,
  1272. personCache, \
  1273. queueJson['post'], \
  1274. federationList, \
  1275. debug, \
  1276. acceptedCaps=["inbox:write","objects:read"]):
  1277. if debug:
  1278. print('DEBUG: Undo accepted from '+keyId)
  1279. os.remove(queueFilename)
  1280. queue.pop(0)
  1281. continue
  1282. if debug:
  1283. print('DEBUG: checking for follow requests')
  1284. if receiveFollowRequest(session, \
  1285. baseDir,httpPrefix,port, \
  1286. sendThreads,postLog, \
  1287. cachedWebfingers,
  1288. personCache, \
  1289. queueJson['post'], \
  1290. federationList, \
  1291. debug,projectVersion, \
  1292. acceptedCaps=["inbox:write","objects:read"]):
  1293. os.remove(queueFilename)
  1294. queue.pop(0)
  1295. if debug:
  1296. print('DEBUG: Follow activity for '+keyId+' removed from accepted from queue')
  1297. continue
  1298. else:
  1299. if debug:
  1300. print('DEBUG: No follow requests')
  1301. if receiveAcceptReject(session, \
  1302. baseDir,httpPrefix,domain,port, \
  1303. sendThreads,postLog, \
  1304. cachedWebfingers, \
  1305. personCache, \
  1306. queueJson['post'], \
  1307. federationList, \
  1308. debug):
  1309. if debug:
  1310. print('DEBUG: Accept/Reject received from '+keyId)
  1311. os.remove(queueFilename)
  1312. queue.pop(0)
  1313. continue
  1314. if receiveUpdate(session, \
  1315. baseDir,httpPrefix, \
  1316. domain,port, \
  1317. sendThreads,postLog, \
  1318. cachedWebfingers, \
  1319. personCache, \
  1320. queueJson['post'], \
  1321. federationList, \
  1322. debug):
  1323. if debug:
  1324. print('DEBUG: Update accepted from '+keyId)
  1325. os.remove(queueFilename)
  1326. queue.pop(0)
  1327. continue
  1328. # get recipients list
  1329. recipientsDict,recipientsDictFollowers= \
  1330. inboxPostRecipients(baseDir,queueJson['post'], \
  1331. httpPrefix,domain,port,debug)
  1332. if len(recipientsDict.items())==0 and \
  1333. len(recipientsDictFollowers.items())==0:
  1334. if debug:
  1335. pprint(queueJson['post'])
  1336. print('DEBUG: no recipients were resolved for post arriving in inbox')
  1337. os.remove(queueFilename)
  1338. queue.pop(0)
  1339. continue
  1340. # if there are only a small number of followers then process them as if they
  1341. # were specifically addresses to particular accounts
  1342. noOfFollowItems=len(recipientsDictFollowers.items())
  1343. if noOfFollowItems>0:
  1344. if noOfFollowItems<5:
  1345. if debug:
  1346. print('DEBUG: moving '+str(noOfFollowItems)+ \
  1347. ' inbox posts addressed to followers')
  1348. for handle,postItem in recipientsDictFollowers.items():
  1349. recipientsDict[handle]=postItem
  1350. recipientsDictFollowers={}
  1351. recipientsList=[recipientsDict,recipientsDictFollowers]
  1352. if debug:
  1353. print('*************************************')
  1354. print('Resolved recipients list:')
  1355. pprint(recipientsDict)
  1356. print('Resolved followers list:')
  1357. pprint(recipientsDictFollowers)
  1358. print('*************************************')
  1359. if queueJson['post'].get('capability'):
  1360. if not isinstance(queueJson['post']['capability'], list):
  1361. if debug:
  1362. print('DEBUG: capability on post should be a list')
  1363. os.remove(queueFilename)
  1364. queue.pop(0)
  1365. continue
  1366. # Copy any posts addressed to followers into the shared inbox
  1367. # this avoid copying file multiple times to potentially many
  1368. # individual inboxes
  1369. # This obviously bypasses object capabilities and so
  1370. # any checking will needs to be handled at the time when inbox
  1371. # GET happens on individual accounts.
  1372. # See posts.py/createBoxBase
  1373. if len(recipientsDictFollowers)>0:
  1374. with open(queueJson['destination'].replace(inboxHandle,inboxHandle), 'w') as fp:
  1375. commentjson.dump(queueJson['post'],fp,indent=4, \
  1376. sort_keys=False)
  1377. # for posts addressed to specific accounts
  1378. for handle,capsId in recipientsDict.items():
  1379. destination=queueJson['destination'].replace(inboxHandle,handle)
  1380. # check that capabilities are accepted
  1381. if queueJson['post'].get('capability'):
  1382. capabilityIdList=queueJson['post']['capability']
  1383. # does the capability id list within the post contain the id
  1384. # of the recipient with this handle?
  1385. # Here the capability id begins with the handle, so this could also
  1386. # be matched separately, but it's probably not necessary
  1387. if capsId in capabilityIdList:
  1388. inboxAfterCapabilities(session,keyId,handle, \
  1389. queueJson['post'], \
  1390. baseDir,httpPrefix, \
  1391. sendThreads,postLog, \
  1392. cachedWebfingers, \
  1393. personCache,queue,domain, \
  1394. port,useTor, \
  1395. federationList,ocapAlways, \
  1396. debug,acceptedCaps, \
  1397. queueFilename,destination, \
  1398. maxReplies,allowDeletion)
  1399. else:
  1400. if debug:
  1401. print('DEBUG: object capabilities check has failed')
  1402. pprint(queueJson['post'])
  1403. else:
  1404. if not ocapAlways:
  1405. inboxAfterCapabilities(session,keyId,handle, \
  1406. queueJson['post'], \
  1407. baseDir,httpPrefix, \
  1408. sendThreads,postLog, \
  1409. cachedWebfingers, \
  1410. personCache,queue,domain, \
  1411. port,useTor, \
  1412. federationList,ocapAlways, \
  1413. debug,acceptedCaps, \
  1414. queueFilename,destination, \
  1415. maxReplies,allowDeletion)
  1416. if debug:
  1417. pprint(queueJson['post'])
  1418. print('No capability list within post')
  1419. print('ocapAlways: '+str(ocapAlways))
  1420. print('DEBUG: object capabilities check failed')
  1421. if debug:
  1422. print('DEBUG: Queue post accepted')
  1423. os.remove(queueFilename)
  1424. queue.pop(0)