follower.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. //sssssssssssssssss
  10. import (
  11. "2PPS/lib"
  12. "crypto/rand"
  13. "crypto/rsa"
  14. "crypto/sha256"
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "encoding/pem"
  19. "fmt"
  20. "math/big"
  21. "net"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "unsafe"
  27. "golang.org/x/crypto/nacl/box"
  28. )
  29. //this stores all neccessary information for each client
  30. type clientKeys struct {
  31. SharedSecret [32]byte
  32. PirQuery [][]byte
  33. }
  34. //uses clients publicKey as key
  35. var clientData = make(map[[32]byte]clientKeys)
  36. var topicList []byte
  37. var topicAmount int
  38. var followerPrivateKey *[32]byte
  39. var followerPublicKey *[32]byte
  40. var leaderPublicKey *[32]byte
  41. //needs to be changed at leader/follower/client at the same time
  42. const dataLength = 256
  43. const numThreads = 12
  44. //Maximum Transport Unit
  45. const mtu int = 1100
  46. var dbWriteSize int = 20000
  47. var neededSubscriptions int
  48. var round int = 0
  49. var startTime time.Time
  50. var ignoreMe []byte
  51. func main() {
  52. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  53. if err != nil {
  54. panic(err)
  55. }
  56. followerPrivateKey = generatedPrivateKey
  57. followerPublicKey = generatedPublicKey
  58. C.initializeServer(C.int(numThreads))
  59. followerConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  60. if err != nil {
  61. panic(err)
  62. }
  63. // Generate a pem block with the private key
  64. keyPem := pem.EncodeToMemory(&pem.Block{
  65. Type: "RSA PRIVATE KEY",
  66. Bytes: x509.MarshalPKCS1PrivateKey(followerConnectionPrivateKey),
  67. })
  68. tml := x509.Certificate{
  69. // you can add any attr that you need
  70. NotBefore: time.Now(),
  71. NotAfter: time.Now().AddDate(5, 0, 0),
  72. // you have to generate a different serial number each execution
  73. SerialNumber: big.NewInt(123123),
  74. Subject: pkix.Name{
  75. CommonName: "New Name",
  76. Organization: []string{"New Org."},
  77. },
  78. BasicConstraintsValid: true,
  79. }
  80. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &followerConnectionPrivateKey.PublicKey, followerConnectionPrivateKey)
  81. if err != nil {
  82. panic(err)
  83. }
  84. // Generate a pem block with the certificate
  85. certPem := pem.EncodeToMemory(&pem.Block{
  86. Type: "CERTIFICATE",
  87. Bytes: cert,
  88. })
  89. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  90. if err != nil {
  91. panic(err)
  92. }
  93. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  94. fmt.Println("start leader")
  95. //listens for leader
  96. lnLeader, err := tls.Listen("tcp", ":4442", config)
  97. if err != nil {
  98. panic(err)
  99. }
  100. defer lnLeader.Close()
  101. leaderConnection, err := lnLeader.Accept()
  102. if err != nil {
  103. panic(err)
  104. }
  105. //send publicKey to leader
  106. writeTo(leaderConnection, followerPublicKey[:])
  107. //receives leader PublicKey
  108. var tmpLeaderPubKey [32]byte
  109. _, err = leaderConnection.Read(tmpLeaderPubKey[:])
  110. if err != nil {
  111. panic(err)
  112. }
  113. neededSubscriptionsBytes := readFrom(leaderConnection, 4)
  114. neededSubscriptions = byteToInt(neededSubscriptionsBytes)
  115. leaderPublicKey = &tmpLeaderPubKey
  116. //setup ends here
  117. //locks access to DB
  118. m := &sync.RWMutex{}
  119. wg := &sync.WaitGroup{}
  120. for {
  121. round++
  122. fmt.Println("Phase 1 Round", round)
  123. //create write db for this round
  124. for i := 0; i < dbWriteSize; i++ {
  125. C.createDb(C.int(0), C.int(dataLength))
  126. }
  127. //receives the virtualAddresses
  128. virtualAddresses := make([]int, dbWriteSize+1)
  129. for i := 0; i <= dbWriteSize; i++ {
  130. virtualAddress := readFrom(leaderConnection, 4)
  131. virtualAddresses[i] = byteToInt(virtualAddress)
  132. }
  133. for i := 0; i < numThreads; i++ {
  134. wg.Add(1)
  135. leaderConnection, err := lnLeader.Accept()
  136. if err != nil {
  137. panic(err)
  138. }
  139. leaderConnection.SetDeadline(time.Time{})
  140. startTime = time.Now()
  141. go phase1(i, leaderConnection, m, wg, virtualAddresses)
  142. }
  143. wg.Wait()
  144. //Phase 2
  145. leaderConnection, err := lnLeader.Accept()
  146. if err != nil {
  147. panic(err)
  148. }
  149. leaderConnection.SetDeadline(time.Time{})
  150. phase2(leaderConnection)
  151. //Phase 3
  152. if round == 1 {
  153. //addTestTweets()
  154. }
  155. //no tweets -> continue to phase 1 and mb get tweets
  156. topicList, topicAmount = lib.GetTopicList(0)
  157. if len(topicList) == 0 {
  158. continue
  159. }
  160. for i := 0; i < numThreads; i++ {
  161. wg.Add(1)
  162. leaderConnection, err := lnLeader.Accept()
  163. if err != nil {
  164. panic(err)
  165. }
  166. leaderConnection.SetDeadline(time.Time{})
  167. startTime = time.Now()
  168. go phase3(leaderConnection, wg, m)
  169. }
  170. wg.Wait()
  171. lib.CleanUpdbR(round)
  172. }
  173. }
  174. func phase1(id int, leaderWorkerConnection net.Conn, m *sync.RWMutex, wg *sync.WaitGroup, virtualAddresses []int) {
  175. for {
  176. gotClient := readFrom(leaderWorkerConnection, 1)
  177. //this worker is done
  178. if gotClient[0] == 0 {
  179. wg.Done()
  180. return
  181. }
  182. //setup the worker-specific db
  183. dbSize := int(C.dbSize)
  184. db := make([][]byte, dbSize)
  185. for i := 0; i < dbSize; i++ {
  186. db[i] = make([]byte, int(C.db[i].dataSize))
  187. }
  188. //gets clients publicKey
  189. var clientPublicKey *[32]byte
  190. var tmpClientPublicKey [32]byte
  191. _, err := leaderWorkerConnection.Read(tmpClientPublicKey[:])
  192. if err != nil {
  193. fmt.Println("no error handling")
  194. panic(err)
  195. }
  196. clientPublicKey = &tmpClientPublicKey
  197. m.RLock()
  198. clientKeys := clientData[tmpClientPublicKey]
  199. m.RUnlock()
  200. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, leaderWorkerConnection, 0, tmpClientPublicKey, true)
  201. if errorBool {
  202. continue
  203. }
  204. getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, leaderWorkerConnection)
  205. m.Lock()
  206. clientData[*clientPublicKey] = clientKeys
  207. m.Unlock()
  208. //gets dpfQuery from leader
  209. dpfLengthBytes, errorBool := readFromWError(leaderWorkerConnection, 4)
  210. if errorBool {
  211. continue
  212. }
  213. dpfLength := byteToInt(dpfLengthBytes)
  214. dpfQueryBEncrypted, errorBool := readFromWError(leaderWorkerConnection, dpfLength)
  215. if errorBool {
  216. continue
  217. }
  218. //decrypt dpfQueryB for sorting into db
  219. var decryptNonce [24]byte
  220. copy(decryptNonce[:], dpfQueryBEncrypted[:24])
  221. dpfQueryB, ok := box.Open(nil, dpfQueryBEncrypted[24:], &decryptNonce, clientPublicKey, followerPrivateKey)
  222. if !ok {
  223. panic("dpfQueryB decryption not ok")
  224. }
  225. ds := int(C.db[0].dataSize)
  226. dataShareFollower := make([]byte, ds)
  227. pos := C.getUint128_t(C.int(virtualAddresses[dbWriteSize]))
  228. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShareFollower[0]))
  229. writeTo(leaderWorkerConnection, dataShareFollower)
  230. dataShareLeader, errorBool := readFromWError(leaderWorkerConnection, ds)
  231. if errorBool {
  232. continue
  233. }
  234. auditXOR := make([]byte, ds)
  235. passedAudit := true
  236. for i := 0; i < ds; i++ {
  237. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  238. //client tried to write to a position that is not a virtuallAddress
  239. if auditXOR[i] != 0 {
  240. passedAudit = false
  241. }
  242. }
  243. if passedAudit {
  244. //run dpf, xor into local db
  245. for i := 0; i < dbSize; i++ {
  246. ds := int(C.db[i].dataSize)
  247. dataShare := make([]byte, ds)
  248. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  249. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  250. for j := 0; j < ds; j++ {
  251. db[i][j] = db[i][j] ^ dataShare[j]
  252. }
  253. }
  254. //xor the worker's DB into the main DB
  255. for i := 0; i < dbSize; i++ {
  256. m.Lock()
  257. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  258. m.Unlock()
  259. }
  260. }
  261. }
  262. }
  263. func phase2(leaderWorkerConnection net.Conn) {
  264. //gets current seed
  265. seedFollower := make([]byte, 16)
  266. C.readSeed((*C.uchar)(&seedFollower[0]))
  267. //get data
  268. dbSize := int(C.dbSize)
  269. tmpdbFollower := make([][]byte, dbSize)
  270. for i := range tmpdbFollower {
  271. tmpdbFollower[i] = make([]byte, dataLength)
  272. }
  273. for i := 0; i < dbSize; i++ {
  274. C.readData(C.int(i), (*C.uchar)(&tmpdbFollower[i][0]))
  275. }
  276. //receive seed from leader
  277. seedLeader := readFrom(leaderWorkerConnection, 16)
  278. //receive data from leader
  279. tmpdbLeader := make([][]byte, dbSize)
  280. for i := range tmpdbLeader {
  281. tmpdbLeader[i] = make([]byte, dataLength)
  282. }
  283. for i := 0; i < dbSize; i++ {
  284. tmpdbLeader[i] = readFrom(leaderWorkerConnection, dataLength)
  285. }
  286. //writes seed to leader
  287. writeTo(leaderWorkerConnection, seedFollower)
  288. //write data to leader
  289. for i := 0; i < dbSize; i++ {
  290. writeTo(leaderWorkerConnection, tmpdbFollower[i])
  291. }
  292. //put together the db
  293. tmpdb := make([][]byte, dbSize)
  294. for i := range tmpdb {
  295. tmpdb[i] = make([]byte, dataLength)
  296. }
  297. //get own Ciphers
  298. ciphersFollowers := make([]*C.uchar, dbSize)
  299. for i := 0; i < dbSize; i++ {
  300. ciphersFollowers[i] = (*C.uchar)(C.malloc(16))
  301. }
  302. for i := 0; i < dbSize; i++ {
  303. C.getCipher(0, C.int(i), ciphersFollowers[i])
  304. }
  305. //receive ciphers from leader
  306. ciphersLeader := make([]byte, dbSize*16)
  307. for i := 0; i < dbSize; i++ {
  308. _, err := leaderWorkerConnection.Read(ciphersLeader[i*16:])
  309. if err != nil {
  310. panic(err)
  311. }
  312. }
  313. //send own Ciphers to leader
  314. for i := 0; i < dbSize; i++ {
  315. writeTo(leaderWorkerConnection, C.GoBytes(unsafe.Pointer(ciphersFollowers[i]), 16))
  316. }
  317. //put in ciphers from leader
  318. for i := 0; i < dbSize; i++ {
  319. C.putCipher(0, C.int(i), (*C.uchar)(&ciphersLeader[i*16]))
  320. }
  321. for i := 0; i < dbSize; i++ {
  322. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  323. }
  324. var tweets []lib.Tweet
  325. for i := 0; i < dbSize; i++ {
  326. //discard cover message
  327. if tmpdb[i][1] == 0 {
  328. continue
  329. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  330. continue
  331. } else {
  332. //reconstruct tweet
  333. var position int = 0
  334. var topics []string
  335. var topic string
  336. var text string
  337. for _, letter := range tmpdb[i] {
  338. if string(letter) == ";" {
  339. if topic != "" {
  340. topics = append(topics, topic)
  341. topic = ""
  342. }
  343. position++
  344. } else {
  345. if position == 0 {
  346. if string(letter) == "," {
  347. topics = append(topics, topic)
  348. topic = ""
  349. } else {
  350. //if topics are
  351. //int
  352. topic = topic + fmt.Sprint(int(letter))
  353. //string
  354. //topic = topic + string(letter)
  355. }
  356. } else if position == 1 {
  357. text = text + string(letter)
  358. }
  359. }
  360. }
  361. tweet := lib.Tweet{"", -1, topics, text, round}
  362. if text != "" {
  363. tweets = append(tweets, tweet)
  364. }
  365. }
  366. }
  367. //fmt.Println("tweets recovered: ", tweets)
  368. //sort into read db
  369. lib.NewEntries(tweets, 0)
  370. //reset write db after the tweets were moved to read db
  371. C.resetDb()
  372. //gets current dbWriteSize from leader
  373. dbWriteSizeBytes := readFrom(leaderWorkerConnection, 4)
  374. dbWriteSize = byteToInt(dbWriteSizeBytes)
  375. }
  376. func addTestTweets() {
  377. //creates test tweets
  378. tweets := make([]lib.Tweet, 5)
  379. for i := range tweets {
  380. j := i
  381. if i == 1 {
  382. j = 0
  383. }
  384. text := "Text " + strconv.Itoa(i)
  385. var topics []string
  386. topics = append(topics, "Topic "+strconv.Itoa(j))
  387. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  388. }
  389. lib.NewEntries(tweets, 0)
  390. }
  391. func phase3(leaderWorkerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  392. for {
  393. gotClient, errorBool := readFromWError(leaderWorkerConnection, 1)
  394. if errorBool {
  395. continue
  396. }
  397. //this worker is done
  398. if gotClient[0] == 0 {
  399. wg.Done()
  400. return
  401. }
  402. subPhase, errorBool := readFromWError(leaderWorkerConnection, 1)
  403. if errorBool {
  404. continue
  405. }
  406. var clientPublicKey [32]byte
  407. _, err := leaderWorkerConnection.Read(clientPublicKey[:])
  408. if err != nil {
  409. fmt.Println("no error handling")
  410. panic(err)
  411. }
  412. //gets the client data
  413. m.RLock()
  414. clientKeys := clientData[clientPublicKey]
  415. m.RUnlock()
  416. if subPhase[0] == 0 || subPhase[0] == 1 {
  417. clientKeys, _, errorBool = handlePirQuery(clientKeys, leaderWorkerConnection, int(subPhase[0]), clientPublicKey, false)
  418. if errorBool {
  419. continue
  420. }
  421. }
  422. getSendTweets(clientKeys, nil, leaderWorkerConnection, m, clientPublicKey)
  423. wantsArchive, errorBool := readFromWError(leaderWorkerConnection, 1)
  424. if errorBool {
  425. continue
  426. }
  427. if wantsArchive[0] == 1 {
  428. fmt.Println("shouldnt be called")
  429. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, leaderWorkerConnection, -1, clientPublicKey, false)
  430. if errorBool {
  431. continue
  432. }
  433. getSendTweets(clientKeys, archiveQuerys, leaderWorkerConnection, m, clientPublicKey)
  434. }
  435. //saves clientKeys
  436. m.Lock()
  437. clientData[clientPublicKey] = clientKeys
  438. m.Unlock()
  439. }
  440. }
  441. //gets tweet from db and sends them to leader
  442. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, leaderWorkerConnection net.Conn, m *sync.RWMutex, pubKey [32]byte) {
  443. //todo! repeat for archive
  444. tmpNeededSubscriptions := neededSubscriptions
  445. if tmpNeededSubscriptions > topicAmount {
  446. tmpNeededSubscriptions = topicAmount
  447. }
  448. if archiveQuerys != nil {
  449. tmpNeededSubscriptions = len(archiveQuerys)
  450. }
  451. for i := 0; i < tmpNeededSubscriptions; i++ {
  452. //gets all requested tweets
  453. var tweets []byte
  454. if archiveQuerys == nil {
  455. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, pubKey)
  456. } else {
  457. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1, pubKey)
  458. }
  459. //expand sharedSecret so it is of right length
  460. expandBy := len(tweets) / 32
  461. var expandedSharedSecret []byte
  462. for i := 0; i < expandBy; i++ {
  463. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  464. }
  465. //Xor's sharedSecret with all tweets
  466. lib.Xor(expandedSharedSecret[:], tweets)
  467. //fmt.Println("tweetsLen", len(tweets))
  468. //sends tweets to leader
  469. //fmt.Println("pubKey", pubKey, "Bytes", tweets)
  470. writeTo(leaderWorkerConnection, tweets)
  471. }
  472. }
  473. //returns true if client connection is lost
  474. func handlePirQuery(clientKeys clientKeys, leaderWorkerConnection net.Conn, subPhase int, clientPublicKey [32]byte, doAuditing bool) (clientKeys, [][]byte, bool) {
  475. archiveNeededSubscriptions := make([]byte, 4)
  476. if subPhase == -1 {
  477. archiveNeededSubscriptions, errorBool := readFromWError(leaderWorkerConnection, 4)
  478. if errorBool {
  479. return clientKeys, nil, true
  480. }
  481. ignoreMe = archiveNeededSubscriptions
  482. }
  483. //gets the msg length
  484. msgLengthBytes, errorBool := readFromWError(leaderWorkerConnection, 4)
  485. if errorBool {
  486. return clientKeys, nil, true
  487. }
  488. msgLength := byteToInt(msgLengthBytes)
  489. //gets the message
  490. message, errorBool := readFromWError(leaderWorkerConnection, msgLength)
  491. if errorBool {
  492. return clientKeys, nil, true
  493. }
  494. var decryptNonce [24]byte
  495. copy(decryptNonce[:], message[:24])
  496. decrypted, ok := box.Open(nil, message[24:], &decryptNonce, &clientPublicKey, followerPrivateKey)
  497. if !ok {
  498. fmt.Println("pirQuery decryption not ok")
  499. return clientKeys, nil, true
  500. }
  501. //gets sharedSecret
  502. if subPhase == 0 {
  503. var newSharedSecret [32]byte
  504. for index := 0; index < 32; index++ {
  505. newSharedSecret[index] = decrypted[index]
  506. }
  507. clientKeys.SharedSecret = newSharedSecret
  508. decrypted = decrypted[32:]
  509. if doAuditing {
  510. result := make([][]byte, 1)
  511. result[0] = decrypted
  512. return clientKeys, result, false
  513. }
  514. //follower updates sharedSecret
  515. } else if subPhase == 1 {
  516. sharedSecret := clientKeys.SharedSecret
  517. sharedSecret = sha256.Sum256(sharedSecret[:])
  518. clientKeys.SharedSecret = sharedSecret
  519. }
  520. //follower expects pirQuery
  521. //transforms byteArray to ints of wanted topics
  522. //todo! repeat for archive
  523. tmpNeededSubscriptions := neededSubscriptions
  524. if tmpNeededSubscriptions > topicAmount {
  525. tmpNeededSubscriptions = topicAmount
  526. }
  527. tmpTopicAmount := topicAmount
  528. if subPhase == -1 {
  529. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  530. _, tmpTopicAmount = lib.GetTopicList(1)
  531. }
  532. pirQueryFlattened := decrypted
  533. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  534. for i := range pirQuerys {
  535. pirQuerys[i] = make([]byte, tmpTopicAmount)
  536. }
  537. for i := 0; i < tmpNeededSubscriptions; i++ {
  538. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  539. }
  540. //sets the pirQuery for the client in case whe are not archiving
  541. if subPhase != -1 {
  542. clientKeys.PirQuery = pirQuerys
  543. }
  544. return clientKeys, pirQuerys, false
  545. }
  546. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, leaderWorkerConnection net.Conn) {
  547. //xores all requested addresses into virtuallAddress
  548. virtualAddress := make([]byte, 4)
  549. for index, num := range pirQuery {
  550. if num == 1 {
  551. currentAddress := intToByte(virtualAddresses[index])
  552. for i := 0; i < 4; i++ {
  553. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  554. }
  555. }
  556. }
  557. //xores the sharedSecret
  558. for i := 0; i < 4; i++ {
  559. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  560. }
  561. writeTo(leaderWorkerConnection, virtualAddress)
  562. }
  563. //sends the array to the connection
  564. func writeTo(connection net.Conn, array []byte) {
  565. remainingLength := len(array)
  566. for remainingLength > 0 {
  567. if remainingLength >= mtu {
  568. _, err := connection.Write(array[:mtu])
  569. if err != nil {
  570. panic(err)
  571. }
  572. array = array[mtu:]
  573. remainingLength -= mtu
  574. } else {
  575. _, err := connection.Write(array)
  576. if err != nil {
  577. panic(err)
  578. }
  579. remainingLength = 0
  580. }
  581. }
  582. }
  583. //reads an array which is returned and of size "size" from the connection
  584. //returned bool is one if connection to client was lost
  585. func readFrom(connection net.Conn, size int) []byte {
  586. var array []byte
  587. remainingSize := size
  588. for remainingSize > 0 {
  589. var err error
  590. toAppend := make([]byte, mtu)
  591. if remainingSize > mtu {
  592. _, err = connection.Read(toAppend)
  593. array = append(array, toAppend...)
  594. remainingSize -= mtu
  595. } else {
  596. _, err = connection.Read(toAppend[:remainingSize])
  597. array = append(array, toAppend[:remainingSize]...)
  598. remainingSize = 0
  599. }
  600. if err != nil {
  601. panic(err)
  602. }
  603. }
  604. return array
  605. }
  606. //reads an array which is returned and of size "size" from the connection
  607. //returns true if connection to client is lost
  608. func readFromWError(connection net.Conn, size int) ([]byte, bool) {
  609. var array []byte
  610. remainingSize := size + 1
  611. for remainingSize > 0 {
  612. var err error
  613. toAppend := make([]byte, mtu)
  614. if remainingSize > mtu {
  615. _, err = connection.Read(toAppend)
  616. array = append(array, toAppend...)
  617. remainingSize -= mtu
  618. } else {
  619. _, err = connection.Read(toAppend[:remainingSize])
  620. array = append(array, toAppend[:remainingSize]...)
  621. remainingSize = 0
  622. }
  623. if err != nil {
  624. panic(err)
  625. }
  626. }
  627. if array[0] == 1 {
  628. return nil, true
  629. }
  630. return array[1:], false
  631. /*
  632. array := make([]byte, size+1)
  633. _, err := connection.Read(array)
  634. if err != nil {
  635. panic(err)
  636. }
  637. if array[0] == 1 {
  638. return nil, true
  639. }
  640. return array[1:], false
  641. */
  642. }
  643. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  644. var topics []string
  645. var topic string
  646. var position int = 0
  647. for _, letter := range topicsAsBytes {
  648. if string(letter) == "," {
  649. topics[position] = topic
  650. topic = ""
  651. position++
  652. } else {
  653. topic = topic + string(letter)
  654. }
  655. }
  656. return topics
  657. }
  658. func byteToInt(myBytes []byte) (x int) {
  659. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  660. return
  661. }
  662. func intToByte(myInt int) (retBytes []byte) {
  663. retBytes = make([]byte, 4)
  664. retBytes[3] = byte((myInt >> 24) & 0xff)
  665. retBytes[2] = byte((myInt >> 16) & 0xff)
  666. retBytes[1] = byte((myInt >> 8) & 0xff)
  667. retBytes[0] = byte(myInt & 0xff)
  668. return
  669. }