follower.go 17 KB

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