Official cwtch.im peer and server implementations. https://cwtch.im
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

263 lines
8.6 KiB

  1. package storage
  2. import (
  3. "cwtch.im/cwtch/event"
  4. "cwtch.im/cwtch/model"
  5. "cwtch.im/cwtch/protocol"
  6. "encoding/json"
  7. "git.openprivacy.ca/openprivacy/libricochet-go/log"
  8. "github.com/golang/protobuf/proto"
  9. "os"
  10. "time"
  11. )
  12. const profileFilename = "profile"
  13. type profileStore struct {
  14. fs FileStore
  15. streamStores map[string]StreamStore
  16. directory string
  17. password string
  18. profile *model.Profile
  19. eventManager event.Manager
  20. queue *event.Queue
  21. writer bool
  22. }
  23. // ProfileStore is an interface to managing the storage of Cwtch Profiles
  24. type ProfileStore interface {
  25. Load() error
  26. Shutdown()
  27. GetProfileCopy(timeline bool) *model.Profile
  28. GetNewPeerMessage() *event.Event
  29. GetStatusMessages() []*event.Event
  30. }
  31. // NewProfileWriterStore returns a profile store backed by a filestore listening for events and saving them
  32. // directory should be $appDir/profiles/$rand
  33. func NewProfileWriterStore(eventManager event.Manager, directory, password string, profile *model.Profile) ProfileStore {
  34. os.Mkdir(directory, 0700)
  35. ps := &profileStore{fs: NewFileStore(directory, profileFilename, password), password: password, directory: directory, profile: profile, eventManager: eventManager, streamStores: map[string]StreamStore{}, writer: true}
  36. ps.queue = event.NewEventQueue(100)
  37. if profile != nil {
  38. ps.save()
  39. }
  40. go ps.eventHandler()
  41. ps.eventManager.Subscribe(event.BlockPeer, ps.queue.EventChannel)
  42. ps.eventManager.Subscribe(event.PeerCreated, ps.queue.EventChannel)
  43. ps.eventManager.Subscribe(event.GroupCreated, ps.queue.EventChannel)
  44. ps.eventManager.Subscribe(event.SetProfileName, ps.queue.EventChannel)
  45. ps.eventManager.Subscribe(event.SetAttribute, ps.queue.EventChannel)
  46. ps.eventManager.Subscribe(event.SetPeerAttribute, ps.queue.EventChannel)
  47. ps.eventManager.Subscribe(event.SetGroupAttribute, ps.queue.EventChannel)
  48. ps.eventManager.Subscribe(event.AcceptGroupInvite, ps.queue.EventChannel)
  49. ps.eventManager.Subscribe(event.NewGroupInvite, ps.queue.EventChannel)
  50. ps.eventManager.Subscribe(event.NewMessageFromGroup, ps.queue.EventChannel)
  51. ps.eventManager.Subscribe(event.PeerStateChange, ps.queue.EventChannel)
  52. ps.eventManager.Subscribe(event.ServerStateChange, ps.queue.EventChannel)
  53. ps.eventManager.Subscribe(event.DeleteContact, ps.queue.EventChannel)
  54. ps.eventManager.Subscribe(event.DeleteGroup, ps.queue.EventChannel)
  55. return ps
  56. }
  57. // ReadProfile reads a profile from storqage and returns the profile
  58. // directory should be $appDir/profiles/$rand
  59. func ReadProfile(directory, password string) (*model.Profile, error) {
  60. os.Mkdir(directory, 0700)
  61. ps := &profileStore{fs: NewFileStore(directory, profileFilename, password), password: password, directory: directory, profile: nil, eventManager: nil, streamStores: map[string]StreamStore{}, writer: true}
  62. err := ps.Load()
  63. if err != nil {
  64. return nil, err
  65. }
  66. profile := ps.GetProfileCopy(true)
  67. return profile, nil
  68. }
  69. // NewProfile creates a new profile for use in the profile store.
  70. func NewProfile(name string) *model.Profile {
  71. profile := model.GenerateNewProfile(name)
  72. return profile
  73. }
  74. // GetNewPeerMessage is for AppService to call on Reload events, to reseed the AppClient with the loaded peers
  75. func (ps *profileStore) GetNewPeerMessage() *event.Event {
  76. message := event.NewEventList(event.NewPeer, event.Identity, ps.profile.LocalID, event.Password, ps.password, event.Status, "running")
  77. return &message
  78. }
  79. func (ps *profileStore) GetStatusMessages() []*event.Event {
  80. messages := []*event.Event{}
  81. for _, contact := range ps.profile.Contacts {
  82. message := event.NewEvent(event.PeerStateChange, map[event.Field]string{
  83. event.RemotePeer: string(contact.Onion),
  84. event.ConnectionState: contact.State,
  85. })
  86. messages = append(messages, &message)
  87. }
  88. doneServers := make(map[string]bool)
  89. for _, group := range ps.profile.Groups {
  90. if _, exists := doneServers[group.GroupServer]; !exists {
  91. message := event.NewEvent(event.ServerStateChange, map[event.Field]string{
  92. event.GroupServer: string(group.GroupServer),
  93. event.ConnectionState: group.State,
  94. })
  95. messages = append(messages, &message)
  96. doneServers[group.GroupServer] = true
  97. }
  98. }
  99. return messages
  100. }
  101. func (ps *profileStore) save() error {
  102. if ps.writer {
  103. bytes, _ := json.Marshal(ps.profile)
  104. return ps.fs.Save(bytes)
  105. }
  106. return nil
  107. }
  108. // Load instantiates a cwtchPeer from the file store
  109. func (ps *profileStore) Load() error {
  110. decrypted, err := ps.fs.Load()
  111. if err != nil {
  112. return err
  113. }
  114. cp := new(model.Profile)
  115. err = json.Unmarshal(decrypted, &cp)
  116. if err == nil {
  117. ps.profile = cp
  118. for gid, group := range cp.Groups {
  119. ss := NewStreamStore(ps.directory, group.LocalID, ps.password)
  120. cp.Groups[gid].Timeline.SetMessages(ss.Read())
  121. ps.streamStores[group.GroupID] = ss
  122. }
  123. }
  124. return err
  125. }
  126. func (ps *profileStore) GetProfileCopy(timeline bool) *model.Profile {
  127. return ps.profile.GetCopy(timeline)
  128. }
  129. func (ps *profileStore) eventHandler() {
  130. for {
  131. ev := ps.queue.Next()
  132. switch ev.EventType {
  133. case event.BlockPeer:
  134. contact, exists := ps.profile.GetContact(ev.Data[event.RemotePeer])
  135. if exists {
  136. contact.Blocked = true
  137. ps.save()
  138. }
  139. case event.PeerCreated:
  140. var pp *model.PublicProfile
  141. json.Unmarshal([]byte(ev.Data[event.Data]), &pp)
  142. ps.profile.AddContact(ev.Data[event.RemotePeer], pp)
  143. // TODO: configure - allow peers to be configured to turn on limited storage
  144. /*ss := NewStreamStore(ps.directory, pp.LocalID, ps.password)
  145. pp.Timeline.SetMessages(ss.Read())
  146. ps.streamStores[pp.Onion] = ss
  147. ps.save()*/
  148. case event.GroupCreated:
  149. var group *model.Group
  150. json.Unmarshal([]byte(ev.Data[event.Data]), &group)
  151. ps.profile.AddGroup(group)
  152. ps.streamStores[group.GroupID] = NewStreamStore(ps.directory, group.LocalID, ps.password)
  153. ps.save()
  154. case event.SetProfileName:
  155. ps.profile.Name = ev.Data[event.ProfileName]
  156. ps.profile.SetAttribute("name", ev.Data[event.ProfileName])
  157. ps.save()
  158. case event.SetAttribute:
  159. ps.profile.SetAttribute(ev.Data[event.Key], ev.Data[event.Data])
  160. ps.save()
  161. case event.SetPeerAttribute:
  162. contact, exists := ps.profile.GetContact(ev.Data[event.RemotePeer])
  163. if exists {
  164. contact.SetAttribute(ev.Data[event.Key], ev.Data[event.Data])
  165. ps.save()
  166. } else {
  167. log.Errorf("error setting attribute on peer %v peer does not exist", ev)
  168. }
  169. case event.SetGroupAttribute:
  170. group := ps.profile.GetGroupByGroupID(ev.Data[event.GroupID])
  171. if group != nil {
  172. group.SetAttribute(ev.Data[event.Key], ev.Data[event.Data])
  173. ps.save()
  174. } else {
  175. log.Errorf("error setting attribute on group %v group does not exist", ev)
  176. }
  177. case event.AcceptGroupInvite:
  178. err := ps.profile.AcceptInvite(ev.Data[event.GroupID])
  179. if err == nil {
  180. ps.save()
  181. } else {
  182. log.Errorf("error accepting group invite")
  183. }
  184. case event.NewGroupInvite:
  185. var gci protocol.GroupChatInvite
  186. err := proto.Unmarshal([]byte(ev.Data[event.GroupInvite]), &gci)
  187. if err == nil {
  188. ps.profile.ProcessInvite(&gci, ev.Data[event.RemotePeer])
  189. ps.save()
  190. group := ps.profile.Groups[gci.GetGroupName()]
  191. ps.streamStores[group.GroupID] = NewStreamStore(ps.directory, group.LocalID, ps.password)
  192. } else {
  193. log.Errorf("error storing new group invite: %v %v", ev, err)
  194. }
  195. case event.NewMessageFromGroup:
  196. groupid := ev.Data[event.GroupID]
  197. received, _ := time.Parse(time.RFC3339Nano, ev.Data[event.TimestampReceived])
  198. sent, _ := time.Parse(time.RFC3339Nano, ev.Data[event.TimestampSent])
  199. message := model.Message{Received: received, Timestamp: sent, Message: ev.Data[event.Data], PeerID: ev.Data[event.RemotePeer], Signature: []byte(ev.Data[event.Signature]), PreviousMessageSig: []byte(ev.Data[event.PreviousSignature])}
  200. ss, exists := ps.streamStores[groupid]
  201. if exists {
  202. ss.Write(message)
  203. } else {
  204. log.Errorf("error storing new group message: %v stream store does not exist", ev)
  205. }
  206. case event.PeerStateChange:
  207. if _, exists := ps.profile.Contacts[ev.Data[event.RemotePeer]]; exists {
  208. ps.profile.Contacts[ev.Data[event.RemotePeer]].State = ev.Data[event.ConnectionState]
  209. }
  210. case event.ServerStateChange:
  211. for _, group := range ps.profile.Groups {
  212. if group.GroupServer == ev.Data[event.GroupServer] {
  213. group.State = ev.Data[event.ConnectionState]
  214. }
  215. }
  216. case event.DeleteContact:
  217. onion := ev.Data[event.RemotePeer]
  218. ps.profile.DeleteContact(onion)
  219. ps.save()
  220. case event.DeleteGroup:
  221. groupID := ev.Data[event.GroupID]
  222. ps.profile.DeleteGroup(groupID)
  223. ps.save()
  224. ss, exists := ps.streamStores[groupID]
  225. if exists {
  226. ss.Delete()
  227. delete(ps.streamStores, groupID)
  228. }
  229. default:
  230. return
  231. }
  232. }
  233. }
  234. func (ps *profileStore) Shutdown() {
  235. if ps.queue != nil {
  236. ps.queue.Shutdown()
  237. }
  238. }