client.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. package main
  2. /*
  3. #cgo CFLAGS: -O2
  4. #cgo LDFLAGS: -lcrypto -lm
  5. #include "../c/dpf.h"
  6. #include "../c/okvClient.h"
  7. #include "../c/dpf.c"
  8. #include "../c/okvClient.c"
  9. */
  10. import "C"
  11. import (
  12. "2PPS/lib"
  13. "bufio"
  14. "bytes"
  15. "crypto/rand"
  16. "crypto/sha256"
  17. "crypto/tls"
  18. "encoding/json"
  19. "fmt"
  20. "math/big"
  21. mr "math/rand"
  22. "net"
  23. "os"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "time"
  29. "unsafe"
  30. "golang.org/x/crypto/nacl/box"
  31. )
  32. type tweet struct {
  33. Topics []string
  34. Text string
  35. }
  36. const leader string = "127.0.0.1:4441"
  37. //needs to be changed at leader/follower/client at the same time
  38. const numClients = 500
  39. //mylimit=8000
  40. //sudo prlimit --nofile=$mylimit --pid $$; ulimit -n $mylimit
  41. //for every terminal
  42. const dataLength int = 256
  43. //Maximum Transport Unit
  44. const mtu int = 1100
  45. var dbWriteSize int
  46. var round int
  47. var topicList []string
  48. var archiveTopicList []string
  49. var neededSubscriptions int
  50. var publisherAmount int
  51. var goodPadding int
  52. var timeBounds []int
  53. var speedUp int = 1000
  54. var maxTimePerRound time.Duration = 10 * time.Second
  55. var startTime int
  56. var archiveInterests = make([]int, 1)
  57. var sharedSecret [numClients][2][32]byte = createSharedSecret()
  58. var wantsArchive = make([]byte, 1)
  59. var leaderPublicKey *[32]byte
  60. var followerPublicKey *[32]byte
  61. var clientPrivateKey [numClients]*[32]byte
  62. var clientPublicKey [numClients]*[32]byte
  63. func main() {
  64. wg := &sync.WaitGroup{}
  65. getTimeBounds()
  66. for i := 0; i < numClients; i++ {
  67. wg.Add(1)
  68. go client(i)
  69. time.Sleep(1 * time.Millisecond)
  70. }
  71. wg.Wait()
  72. }
  73. func client(clientNumber int) {
  74. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  75. if err != nil {
  76. panic(err)
  77. }
  78. clientPrivateKey[clientNumber] = generatedPrivateKey
  79. clientPublicKey[clientNumber] = generatedPublicKey
  80. C.initializeCipher()
  81. //initializes the connection to the leader
  82. conf := &tls.Config{
  83. InsecureSkipVerify: true,
  84. }
  85. leaderConn, err := tls.Dial("tcp", leader, conf)
  86. if err != nil {
  87. fmt.Println("clientNumber", clientNumber)
  88. panic(err)
  89. }
  90. leaderConn.SetDeadline(time.Time{})
  91. //receives topics first so client can participate asap
  92. receiveTopicLists(leaderConn)
  93. //gets the public keys of both servers
  94. var tmpLeaderPubKey [32]byte
  95. _, err = leaderConn.Read(tmpLeaderPubKey[:])
  96. if err != nil {
  97. panic(err)
  98. }
  99. leaderPublicKey = &tmpLeaderPubKey
  100. var tmpFollowerPubKey [32]byte
  101. _, err = leaderConn.Read(tmpFollowerPubKey[:])
  102. if err != nil {
  103. panic(err)
  104. }
  105. followerPublicKey = &tmpFollowerPubKey
  106. //sends own public key
  107. writeTo(leaderConn, clientPublicKey[clientNumber][:])
  108. neededSubscriptionsBytes := readFrom(leaderConn, 4)
  109. neededSubscriptions = byteToInt(neededSubscriptionsBytes)
  110. startTimeBytes := readFrom(leaderConn, 4)
  111. startTime = byteToInt(startTimeBytes)
  112. //setup ends above
  113. //while client is active he is always connected and has to participate
  114. for {
  115. //gets current phase
  116. phase := readFrom(leaderConn, 1)
  117. if phase[0] == 1 {
  118. //gets current dbWriteSize from leader
  119. dbWriteSizeBytes := readFrom(leaderConn, 4)
  120. dbWriteSize = byteToInt(dbWriteSizeBytes)
  121. //roundAsBytes := readFrom(leaderConn, 4)
  122. roundAsBytes := make([]byte, 4)
  123. _, err = leaderConn.Read(roundAsBytes)
  124. if err != nil {
  125. panic(err)
  126. }
  127. round = byteToInt(roundAsBytes)
  128. if clientNumber == 0 {
  129. fmt.Println("Round ", round)
  130. }
  131. //request virtualAddress from leader via pirQuery
  132. encryptedQueryLeader, encryptedQueryFollower := createAuditPIRQuery(clientNumber)
  133. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  134. pos := receiveVirtualAddress(sharedSecret[clientNumber], leaderConn)
  135. tweet := getRealTweet(clientNumber)
  136. if clientNumber == numClients-1 {
  137. fmt.Println("publisherAmount", publisherAmount)
  138. fmt.Println("goodPadding", goodPadding)
  139. }
  140. //prep the query
  141. dataSize := len(tweet)
  142. querySize := make([]byte, 4)
  143. cQuerySize := C.int(byteToInt(querySize))
  144. var dpfQueryA *C.uchar
  145. var dpfQueryB *C.uchar
  146. C.prepQuery(C.int(pos), C.int(dbWriteSize), (*C.uchar)(&tweet[0]), C.int(dataSize), &cQuerySize, &dpfQueryA, &dpfQueryB)
  147. intQuerySize := int(cQuerySize) //byteToInt(querySize)
  148. //write the query
  149. queryAPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryA), C.int(intQuerySize))
  150. //encrypts queryA and appends it to message
  151. var nonce [24]byte
  152. //fill nonce with randomness
  153. _, err = rand.Read(nonce[:])
  154. if err != nil {
  155. panic("couldn't get randomness for nonce!")
  156. }
  157. dpfQueryAEncrypted := box.Seal(nonce[:], queryAPlaintext, &nonce, leaderPublicKey, clientPrivateKey[clientNumber])
  158. //encrypts queryB and appends it to message
  159. queryBPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryB), C.int(intQuerySize))
  160. //fill nonce with randomness
  161. _, err = rand.Read(nonce[:])
  162. if err != nil {
  163. panic("couldn't get randomness for nonce!")
  164. }
  165. dpfQueryBEncrypted := box.Seal(nonce[:], queryBPlaintext, &nonce, followerPublicKey, clientPrivateKey[clientNumber])
  166. //writes the dpfQuery to the leader
  167. dpfLengthBytes := intToByte(len(dpfQueryAEncrypted))
  168. writeTo(leaderConn, dpfLengthBytes)
  169. writeTo(leaderConn, dpfQueryAEncrypted)
  170. writeTo(leaderConn, dpfQueryBEncrypted)
  171. C.free(unsafe.Pointer(dpfQueryA))
  172. C.free(unsafe.Pointer(dpfQueryB))
  173. } else if phase[0] == 3 {
  174. /*
  175. possible Values
  176. 0 : new client
  177. leader expects sharedSecrets, expects pirQuery
  178. 1 : update needed
  179. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  180. 2 : no update needed
  181. nothing
  182. */
  183. subPhase := readFrom(leaderConn, 1)
  184. var encryptedQueryLeader, encryptedQueryFollower []byte
  185. //first time participating
  186. if subPhase[0] == 0 {
  187. receiveTopicLists(leaderConn)
  188. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  189. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  190. }
  191. //updates the topic list and what client is interested in
  192. if subPhase[0] == 1 {
  193. receiveTopicLists(leaderConn)
  194. //updates local secret
  195. for index := 0; index < 2; index++ {
  196. sharedSecret[clientNumber][index] = sha256.Sum256(sharedSecret[clientNumber][index][:])
  197. }
  198. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  199. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  200. }
  201. receiveTweets(sharedSecret[clientNumber], leaderConn, false, clientNumber)
  202. if len(archiveTopicList) > 0 {
  203. wantsArchive[0] = 1
  204. } else {
  205. wantsArchive[0] = 0
  206. }
  207. writeTo(leaderConn, wantsArchive)
  208. //fmt.Println("list", archiveTopicList)
  209. if wantsArchive[0] == 1 && len(archiveTopicList) > 0 {
  210. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(-1, clientNumber)
  211. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, true)
  212. receiveTweets(sharedSecret[clientNumber], leaderConn, true, clientNumber)
  213. }
  214. } else {
  215. fmt.Println("Phase", phase)
  216. panic("somethin went wrong")
  217. }
  218. }
  219. }
  220. //creates and sends the pirQuerys for each server
  221. func createPIRQuery(subPhase int, clientNumber int) ([]byte, []byte) {
  222. //later this will be taken from gui, this is only for testing
  223. topicsOfInterest := make([]int, 1)
  224. topicsOfInterest[0] = mr.Intn(10)
  225. archiveInterests[0] = mr.Intn(10)
  226. tmpNeededSubscriptions := neededSubscriptions
  227. if tmpNeededSubscriptions > len(topicList) {
  228. tmpNeededSubscriptions = len(topicList)
  229. }
  230. tmptopicsOfInterest := make([]int, len(topicsOfInterest))
  231. copy(tmptopicsOfInterest, topicsOfInterest)
  232. tmpTopicList := make([]string, len(topicList))
  233. copy(tmpTopicList, topicList)
  234. if wantsArchive[0] == 1 && subPhase == -1 {
  235. tmpNeededSubscriptions = len(archiveInterests)
  236. if tmpNeededSubscriptions > len(archiveTopicList) {
  237. tmpNeededSubscriptions = len(archiveTopicList)
  238. }
  239. tmptopicsOfInterest = archiveInterests //!todo take archiveInterests from gui
  240. tmpTopicList = archiveTopicList
  241. }
  242. //creates fake topicsOfInterest if client is boooring
  243. if len(tmptopicsOfInterest) < tmpNeededSubscriptions && subPhase != -1 {
  244. tmptopicsOfInterest = addFakeInterests(len(tmpTopicList), tmptopicsOfInterest, false)
  245. }
  246. //pirQuery [topicsOfInterest][serverAmount][topicAmount]byte
  247. pirQuerys := make([][][]byte, len(tmptopicsOfInterest))
  248. for i := range pirQuerys {
  249. pirQuerys[i] = make([][]byte, 2)
  250. for j := range pirQuerys[i] {
  251. pirQuerys[i][j] = make([]byte, len(tmpTopicList))
  252. }
  253. }
  254. //for leader
  255. //pirQuery will be filled with random bits
  256. for topic := range tmptopicsOfInterest {
  257. for index := range tmpTopicList {
  258. bit, err := rand.Int(rand.Reader, big.NewInt(2))
  259. if err != nil {
  260. panic(err)
  261. }
  262. pirQuerys[topic][0][index] = byte(bit.Int64())
  263. }
  264. }
  265. tmptopicsOfInterestBytes := make([]byte, len(tmpTopicList))
  266. for index := range tmptopicsOfInterest {
  267. if tmptopicsOfInterest[index] == 1 {
  268. tmptopicsOfInterestBytes[index] = 1
  269. }
  270. }
  271. for topicIndex, topic := range tmptopicsOfInterest {
  272. for index := range tmpTopicList {
  273. if topic == index {
  274. if pirQuerys[topicIndex][0][index] == 1 {
  275. pirQuerys[topicIndex][1][index] = 0
  276. } else {
  277. pirQuerys[topicIndex][1][index] = 1
  278. }
  279. } else {
  280. if pirQuerys[topicIndex][0][index] == 0 {
  281. pirQuerys[topicIndex][1][index] = 0
  282. } else {
  283. pirQuerys[topicIndex][1][index] = 1
  284. }
  285. }
  286. }
  287. }
  288. //flattens the querys to be able to send them more efficently
  289. messagesFlattened := make([][]byte, 2)
  290. //adds the sharedSecret to the first pirQuery when first time participating
  291. if subPhase == 0 {
  292. for server := 0; server < 2; server++ {
  293. messagesFlattened[server] = append(messagesFlattened[server], sharedSecret[clientNumber][server][:]...)
  294. }
  295. }
  296. for server := range messagesFlattened {
  297. for topic := range pirQuerys {
  298. messagesFlattened[server] = append(messagesFlattened[server], pirQuerys[topic][server]...)
  299. }
  300. }
  301. var nonce [24]byte
  302. _, err := rand.Read(nonce[:])
  303. if err != nil {
  304. panic("couldn't get randomness for nonce!")
  305. }
  306. encryptedQueryLeader := box.Seal(nonce[:], messagesFlattened[0], &nonce, leaderPublicKey, clientPrivateKey[clientNumber])
  307. _, err = rand.Read(nonce[:])
  308. if err != nil {
  309. panic("couldn't get randomness for nonce!")
  310. }
  311. encryptedQueryFollower := box.Seal(nonce[:], messagesFlattened[1], &nonce, followerPublicKey, clientPrivateKey[clientNumber])
  312. return encryptedQueryLeader, encryptedQueryFollower
  313. }
  314. func sendQuerys(encryptedQueryLeader, encryptedQueryFollower []byte, leaderConn net.Conn, getArchive bool) {
  315. encryptedLength := len(encryptedQueryLeader)
  316. //sends the pirQuerysLength to the leader
  317. writeTo(leaderConn, intToByte(encryptedLength))
  318. //sends the pirQuerys to the leader
  319. writeTo(leaderConn, encryptedQueryLeader)
  320. writeTo(leaderConn, encryptedQueryFollower)
  321. if getArchive {
  322. writeTo(leaderConn, intToByte(len(archiveInterests)))
  323. }
  324. }
  325. func receiveVirtualAddress(sharedSecret [2][32]byte, leaderConn net.Conn) int {
  326. virtualAddressByte := readFrom(leaderConn, 4)
  327. //xores the sharedSecret
  328. for h := 0; h < 2; h++ {
  329. for i := 0; i < 4; i++ {
  330. virtualAddressByte[i] = virtualAddressByte[i] ^ sharedSecret[h][i]
  331. }
  332. }
  333. return byteToInt(virtualAddressByte)
  334. }
  335. func receiveTweets(sharedSecret [2][32]byte, leaderConn net.Conn, getArchive bool, clientNumber int) {
  336. tmpNeededSubscriptions := neededSubscriptions
  337. if tmpNeededSubscriptions > len(topicList) {
  338. tmpNeededSubscriptions = len(topicList)
  339. }
  340. if getArchive {
  341. tmpNeededSubscriptions = len(archiveInterests)
  342. if tmpNeededSubscriptions > len(archiveTopicList) {
  343. tmpNeededSubscriptions = len(archiveTopicList)
  344. }
  345. }
  346. for i := 0; i < tmpNeededSubscriptions; i++ {
  347. //client receives tweets
  348. tweetsLengthBytes := readFrom(leaderConn, 4)
  349. tweetsLength := byteToInt(tweetsLengthBytes)
  350. tweets := readFrom(leaderConn, tweetsLength)
  351. //fmt.Println(tweets[:10])
  352. //expand sharedSecret so it is of right length
  353. expandBy := len(tweets) / 32
  354. expandedSharedSecrets := make([][]byte, 2)
  355. for i := 0; i < 2; i++ {
  356. for j := 0; j < expandBy; j++ {
  357. expandedSharedSecrets[i] = append(expandedSharedSecrets[i], sharedSecret[i][:]...)
  358. }
  359. }
  360. //xors the received messge into the message to display
  361. for i := 0; i < 2; i++ {
  362. lib.Xor(expandedSharedSecrets[i][:], tweets)
  363. }
  364. //fmt.Println("PubKey", clientPublicKey[clientNumber], "Bytes", tweets)
  365. index := strings.Index(string(tweets), ";;")
  366. if index != -1 {
  367. textArr := strings.Split(string(tweets), ";;;")
  368. text := textArr[:len(textArr)-1]
  369. //fmt.Println("Round", round, text[0], "Length", len(tweets))
  370. if text[1] != "" {
  371. text[1] = text[1][1:]
  372. }
  373. ok := strings.Contains(text[0], text[1])
  374. if ok {
  375. goodPadding++
  376. //fmt.Println("Round", round, text[0], "Length", len(tweets))
  377. //fmt.Println("padding", text[1])
  378. }
  379. } else if index == -1 && tweets[0] != 0 {
  380. fmt.Println("error")
  381. fmt.Println("round", round, string(tweets), "length", len(tweets))
  382. return
  383. //panic("received text not of correct format")
  384. }
  385. }
  386. }
  387. //creates a shared secret for each server
  388. func createSharedSecret() [numClients][2][32]byte {
  389. var tmpSharedSecret [numClients][2][32]byte
  390. for i := 0; i < numClients; i++ {
  391. for j := 0; j < 2; j++ {
  392. _, err := rand.Read(tmpSharedSecret[i][j][:])
  393. if err != nil {
  394. panic("couldn't get randomness for sharedSecret!")
  395. }
  396. }
  397. }
  398. return tmpSharedSecret
  399. }
  400. func createAuditPIRQuery(clientNumber int) ([]byte, []byte) {
  401. //pirQuery [serverAmount][dbWriteSize]byte
  402. pirQuerys := make([][]byte, 2)
  403. for i := range pirQuerys {
  404. pirQuerys[i] = make([]byte, dbWriteSize)
  405. }
  406. //for leader
  407. //pirQuery will be filled with random bits
  408. for index := range pirQuerys[0] {
  409. bit := mr.Intn(2)
  410. pirQuerys[0][index] = byte(bit)
  411. }
  412. copy(pirQuerys[1], pirQuerys[0])
  413. //the positon the virtual address will be taken from
  414. pos := mr.Intn(dbWriteSize)
  415. pirQuerys[0][pos] = 1
  416. pirQuerys[1][pos] = 0
  417. //flattens the querys to be able to send them more efficently
  418. messagesFlattened := make([][]byte, 2)
  419. //adds the sharedSecret to the pirQuery
  420. for server := 0; server < 2; server++ {
  421. messagesFlattened[server] = append(messagesFlattened[server], sharedSecret[clientNumber][server][:]...)
  422. }
  423. for server := 0; server < 2; server++ {
  424. messagesFlattened[server] = append(messagesFlattened[server], pirQuerys[server][:]...)
  425. }
  426. var nonce [24]byte
  427. _, err := rand.Read(nonce[:])
  428. if err != nil {
  429. panic("couldn't get randomness for nonce!")
  430. }
  431. encryptedQueryLeader := box.Seal(nonce[:], messagesFlattened[0], &nonce, leaderPublicKey, clientPrivateKey[clientNumber])
  432. _, err = rand.Read(nonce[:])
  433. if err != nil {
  434. panic("couldn't get randomness for nonce!")
  435. }
  436. encryptedQueryFollower := box.Seal(nonce[:], messagesFlattened[1], &nonce, followerPublicKey, clientPrivateKey[clientNumber])
  437. return encryptedQueryLeader, encryptedQueryFollower
  438. }
  439. //generates a topicOfInterest array with random values
  440. func addFakeInterests(max int, topicsOfInterest []int, doAuditing bool) []int {
  441. tmpNeededSubscriptions := neededSubscriptions
  442. if tmpNeededSubscriptions > len(topicList) {
  443. tmpNeededSubscriptions = len(topicList)
  444. }
  445. faketopicsOfInterest := make([]int, tmpNeededSubscriptions)
  446. maxInt := max
  447. //fills the array with unique random ascending values ranging from 0 to max
  448. for i := 0; i < tmpNeededSubscriptions; i++ {
  449. faketopicsOfInterest[i] = mr.Intn(maxInt)
  450. for j := 0; j < i; j++ {
  451. if faketopicsOfInterest[i] == faketopicsOfInterest[j] {
  452. i--
  453. break
  454. }
  455. }
  456. }
  457. if doAuditing {
  458. sort.Ints(faketopicsOfInterest)
  459. return faketopicsOfInterest
  460. }
  461. //adds unique and new random numbers to topicOfInterests until length is satisfied
  462. for _, number := range faketopicsOfInterest {
  463. if !inList(number, topicsOfInterest) {
  464. topicsOfInterest = append(topicsOfInterest, number)
  465. }
  466. if len(topicsOfInterest) == tmpNeededSubscriptions {
  467. break
  468. }
  469. }
  470. sort.Ints(topicsOfInterest)
  471. return topicsOfInterest
  472. }
  473. func inList(number int, list []int) bool {
  474. for _, element := range list {
  475. if element == number {
  476. return true
  477. }
  478. }
  479. return false
  480. }
  481. func receiveTopicLists(leaderConn net.Conn) {
  482. for i := 0; i < 2; i++ {
  483. topicListLength := readFrom(leaderConn, 4)
  484. recTopicList := readFrom(leaderConn, byteToInt(topicListLength))
  485. var tmpTopicList []string
  486. arrayReader := bytes.NewReader(recTopicList[:])
  487. json.NewDecoder(arrayReader).Decode(&tmpTopicList)
  488. if i == 0 {
  489. topicList = tmpTopicList
  490. } else {
  491. archiveTopicList = tmpTopicList
  492. }
  493. }
  494. }
  495. func getRealTweet(clientNumber int) []byte {
  496. fUserList, err := os.Open("/home/simon/goCode/tweets/userList")
  497. if err != nil {
  498. panic(err)
  499. }
  500. defer fUserList.Close()
  501. currentLine := 0
  502. scanner := bufio.NewScanner(fUserList)
  503. userID := ""
  504. for scanner.Scan() {
  505. if currentLine == clientNumber {
  506. userID = scanner.Text()
  507. break
  508. }
  509. currentLine++
  510. }
  511. if userID == "" {
  512. panic("no userID picked")
  513. }
  514. fTweets, err := os.Open("/home/simon/goCode/tweets/userTweets/" + userID)
  515. if err != nil {
  516. panic(err)
  517. }
  518. defer fTweets.Close()
  519. scanner = bufio.NewScanner(fTweets)
  520. lowerBound := timeBounds[round-1]
  521. upperBound := timeBounds[round]
  522. var tweet []byte
  523. for scanner.Scan() {
  524. lineArr := strings.Split(scanner.Text(), ", \"hashtags\"")
  525. lineArr = strings.Split(lineArr[0], ": ")
  526. lineArr = strings.Split(lineArr[1], " \"")
  527. timestamp, _ := strconv.Atoi(lineArr[0])
  528. //transforms timestamp to current time
  529. timestamp -= 1351742400
  530. timestamp += startTime
  531. if timestamp > lowerBound && timestamp < upperBound {
  532. lineArr = strings.Split(scanner.Text(), "[\"")
  533. line := lineArr[1]
  534. lineArr = strings.Split(line, "\"]")
  535. line = lineArr[0]
  536. lineArr = strings.Split(line, ",")
  537. line = strings.Join(lineArr, "")
  538. topicLine := strings.Split(line, "\"")
  539. var topics []byte
  540. for index, topic := range topicLine {
  541. if index%2 == 1 {
  542. continue
  543. }
  544. if len(topics)+len(topic) > dataLength-10 {
  545. break
  546. }
  547. topics = append(topics, []byte(topic)[:]...)
  548. topics = append(topics, []byte(",")[0])
  549. }
  550. topics = topics[:len(topics)-1]
  551. //fmt.Println(string(topics))
  552. tweet = append(tweet, topics...)
  553. tweet = append(tweet, []byte(";")[0])
  554. r := mr.New(mr.NewSource(time.Now().UnixNano()))
  555. num := r.Intn(10000)
  556. if num == 0 {
  557. num = 1
  558. }
  559. tweet = append(tweet, []byte(strconv.Itoa(num) + ";;")[:]...)
  560. //fmt.Println("tweet", string(tweet))
  561. //adds padding
  562. length := dataLength - len(tweet)
  563. padding := make([]byte, length)
  564. rand.Read(padding)
  565. tweet = append(tweet, padding...)
  566. publisherAmount++
  567. return tweet
  568. }
  569. }
  570. tweet = make([]byte, dataLength)
  571. return tweet
  572. }
  573. func getTimeBounds() {
  574. timeBounds = make([]int, 10000)
  575. timeBounds[0] = int(time.Now().Unix())
  576. for index := range timeBounds {
  577. if index == 0 {
  578. continue
  579. }
  580. timeBounds[index] = timeBounds[index-1] + speedUp*(int(3*maxTimePerRound.Seconds())+2)
  581. }
  582. }
  583. func getRandomTweet(clientNumber int) []byte {
  584. var tweet []byte
  585. r := mr.New(mr.NewSource(time.Now().UnixNano()))
  586. maxTopics := r.Intn(6)
  587. if maxTopics == 0 {
  588. maxTopics = 1
  589. }
  590. maxInt := 100
  591. topicNumbers := make([]int, maxTopics)
  592. //fills the array with unique random ascending values ranging from 0 to maxInt
  593. for i := 0; i < maxTopics; i++ {
  594. topicNumbers[i] = mr.Intn(maxInt)
  595. for j := 0; j < i; j++ {
  596. if topicNumbers[i] == topicNumbers[j] {
  597. i--
  598. break
  599. }
  600. }
  601. }
  602. sort.Ints(topicNumbers)
  603. //fmt.Println("topicNumbers", topicNumbers)
  604. var topics []byte
  605. topicIndex := 0
  606. for i := 0; i < len(topicNumbers)*2; i++ {
  607. if i%2 == 0 {
  608. topics = append(topics, byte(topicNumbers[topicIndex]))
  609. topicIndex++
  610. } else if i != (len(topicNumbers)*2)-1 {
  611. topics = append(topics, []byte(",")[0])
  612. }
  613. }
  614. topics = append(topics, []byte(";")[0])
  615. num := r.Intn(100)
  616. if num == 0 {
  617. num = 1
  618. }
  619. text := []byte(strconv.Itoa(num) + ";")
  620. tweet = append(tweet, topics...)
  621. tweet = append(tweet, text...)
  622. tweet = append(tweet, []byte(";")[0])
  623. //fmt.Println("writing", string(text))
  624. //fmt.Println(topicNumbers)
  625. if len(tweet) > 32 {
  626. fmt.Println("lenlen", len(tweet))
  627. }
  628. //adds padding
  629. length := dataLength - len(tweet)
  630. padding := make([]byte, length)
  631. rand.Read(padding)
  632. tweet = append(tweet, padding...)
  633. return tweet
  634. }
  635. //sends the array to the connection
  636. func writeTo(connection net.Conn, array []byte) {
  637. remainingLength := len(array)
  638. for remainingLength > 0 {
  639. if remainingLength >= mtu {
  640. _, err := connection.Write(array[:mtu])
  641. if err != nil {
  642. panic(err)
  643. }
  644. array = array[mtu:]
  645. remainingLength -= mtu
  646. } else {
  647. _, err := connection.Write(array)
  648. if err != nil {
  649. panic(err)
  650. }
  651. remainingLength = 0
  652. }
  653. }
  654. }
  655. //reads an array which is returned and of size "size" from the connection
  656. func readFrom(connection net.Conn, size int) []byte {
  657. var array []byte
  658. remainingSize := size
  659. for remainingSize > 0 {
  660. var err error
  661. toAppend := make([]byte, mtu)
  662. if remainingSize > mtu {
  663. _, err = connection.Read(toAppend)
  664. array = append(array, toAppend...)
  665. remainingSize -= mtu
  666. } else {
  667. _, err = connection.Read(toAppend[:remainingSize])
  668. array = append(array, toAppend[:remainingSize]...)
  669. remainingSize = 0
  670. }
  671. if err != nil {
  672. panic(err)
  673. }
  674. }
  675. return array
  676. }
  677. func intToByte(myInt int) (retBytes []byte) {
  678. retBytes = make([]byte, 4)
  679. retBytes[3] = byte((myInt >> 24) & 0xff)
  680. retBytes[2] = byte((myInt >> 16) & 0xff)
  681. retBytes[1] = byte((myInt >> 8) & 0xff)
  682. retBytes[0] = byte(myInt & 0xff)
  683. return
  684. }
  685. func byteToInt(myBytes []byte) (x int) {
  686. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  687. return
  688. }