forked from cfadmin-cn/mongo
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.lua
More file actions
Latest commit
670 lines (607 loc) · 25.6 KB
/
Copy pathprotocol.lua
File metadata and controls
670 lines (607 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
--[[
LICENSE: BSD
Author: CandyMi[https://github.com/candymi]
]]
localbson=require"mongo.bson"
localbson_encode=bson.encode
localbson_decode=bson.decode
localbson_encode_order=bson.bson_encode_order
localcrypt=require"crypt"
localmd5=crypt.md5
localsha1=crypt.sha1
localxor_str=crypt.xor_str
localhmac_sha1=crypt.hmac_sha1
localrandomkey=crypt.randomkey_ex
localbase64decode=crypt.base64decode
localbase64encode=crypt.base64encode
localsys=require"sys"
localnow=sys.now
localnew_tab=sys.new_tab
localnext=next
localtype=type
localpcall=pcall
localassert=assert
-- local find = string.find
localfmt=string.format
localstrpack=string.pack
localstrunpack=string.unpack
localconcat=table.concat
localunpack=table.unpack
localtoint=math.tointeger
localMAX_INT32= (1<<31) -1
localSTR_TO_OPCODE= {
OP_REPLY=1, -- Reply to a client request. responseTo is set.
OP_UPDATE=2001, -- receivedUpdate checkAuthForUpdate update.
OP_INSERT=2002, -- receivedInsert checkAuthForInsert createIndex/insert.
RESERVED=2003, -- Formerly used for OP_GET_BY_OID.
OP_QUERY=2004, -- receivedQuery checkAuthForQuery find.
OP_GET_MORE=2005, -- receivedGetMore checkAuthForGetMore listCollections/listIndexes/find.
OP_DELETE=2006, -- receivedDelete checkAuthForDelete remove
OP_KILL_CURSORS=2007, -- receivedKillCursors checkAuthForKillCursors killCursors
OP_MSG=2013, -- Send a message using the format introduced in MongoDB 3.6.
}
localOPCODE_TO_STR= {
[1] ="OP_REPLY",
[2001] ="OP_UPDATE",
[2002] ="OP_INSERT",
[2003] ="RESERVED",
[2004] ="OP_QUERY",
[2005] ="OP_GET_MORE",
[2006] ="OP_DELETE",
[2007] ="OP_KILL_CURSORS",
[2013] ="OP_MSG",
}
localfunctionsock_read(sock, bytes)
localbuffer=sock:recv(bytes)
ifnotbufferthen
return
end
if#buffer==bytesthen
returnbuffer
end
bytes=bytes-#buffer
localbuffers= {buffer}
localsock_recv=sock.recv
while1do
buffer=sock_recv(sock, bytes)
ifnotbufferthen
return
end
bytes=bytes-#buffer
buffers[#buffers+1] =buffer
ifbytes==0then
returnconcat(buffers)
end
end
end
localfunctiongetn_nonce_payload(username)
localnonce=base64encode(randomkey(16))
returnbase64encode(concat({"n,,n=" ..username, ",r=" ..nonce})), nonce
end
localfunctionsalt_password(key, salt, count)
salt=base64decode(salt) ..'\0\0\0\1'
localoutput=hmac_sha1(key, salt)
localinput=output
for_=1, count-1do
input=hmac_sha1(key, input)
output=xor_str(output, input)
end
returnoutput
end
---comment 读取公共头部
localfunctionread_header(sock)
-- print(1.1)
localdata=sock_read(sock, 16)
ifnotdatathen
returnfalse, "[MONGO ERROR]: Server closed this session when client read header byte from socket."
end
-- print(1.2)
localmsg_len, req_id, resp_id, opcode=strunpack("<i4i4i4i4", data)
return { msg_len=msg_len, req_id=req_id, resp_id=resp_id, opcode=opcode, opcode_str=OPCODE_TO_STR[opcode] }
end
---comment 读取MSG头部
localfunctionread_msg_header(sock)
localheader, err=read_header(sock)
ifnotheaderthen
returnfalse, err
end
localdata=sock_read(sock, 4)
ifnotdatathen
returnfalse, "[MONGO ERROR]: Server closed this session when client read header byte from socket."
end
localflag=strunpack("<i4", data)
header["flags"] = {
checksum=flag & 0x01==0x01andtrue,
morecome=flag & 0x02==0x02andtrue,
allowed=flag & 0x010000==0x010000andtrue,
}
returnheader
end
-- 读取OP_REPLY
localfunctionread_reply(self)
-- print(1)
localsock=self.sock
localheader, err=read_header(sock)
ifnotheaderthen
returnfalse, err
end
-- print(2, header.req_id, header.resp_id ~= self.reqid)
ifheader.req_idandheader.resp_id~=self.reqidthen
returnfalse, "[MONGO ERROR]: Unexpected response request ID."
end
-- print(3)
localbuf=sock_read(sock, 20)
ifnotbufthen
returnfalse, "[MONGO ERROR]: Server closed this session when client read reply byte from socket."
end
-- print(4)
header.flags, header.cuorsor, header.started, header.returned=strunpack("<i4i8i4i4", buf)
localdocument=sock_read(sock, header.msg_len-36)
ifnotdocumentthen
returnfalse, "[MONGO ERROR]: Server closed this session when client read document byte from socket."
end
-- print(5)
returnheader, bson_decode(document)
end
localfunctionread_msg_body(self)
-- print("开始读取")
localsock=self.sock
localheader, err=read_msg_header(sock)
ifnotheaderorheader.opcode~=STR_TO_OPCODE['OP_MSG'] then
self.connected=false
returnfalse, error"Invalid MSG TYPE."
end
ifheader.req_idandheader.resp_id~=self.reqidthen
returnfalse, "[MONGO ERROR]: Unexpected response request ID."
end
-- print("读取完毕")
-- var_dump(header)
ifheader.msg_len-20>1then
sock_read(sock, 1)
end
localdocument=sock_read(sock, header.msg_len-21)
ifnotdocumentthen
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client read reply."
end
self.reqid=self.reqid%MAX_INT32+1
localok, info=pcall(bson_decode, document)
ifnotokthen
returnfalse, info
end
returninfo
end
-- --------- QUERY --------- --
localfunctionsend_query(self, db, table, filter, option)
localquery= {{"find", table}, {"filter", filter}, {"limit", type(option) =='table' andtoint(option.limit) or0}, {"skip", type(option) =='table' andtoint(option.skip) or0}, {"$db", db}}
iftype(option) =='table' then
iftoint(option.cursor) andtoint(option.cursor) >4294967296then
query= {{"getMore", toint(option.cursor)}, {"collection", table}, {"$db", db}}
iftoint(option.size) then
query[#query+1] = {"batchSize", type(option) =='table' andtoint(option.size) or0}
end
else
-- 排序条件
iftype(option.sort) =='table' then
query[#query+1] = {"sort", option.sort}
end
-- 如果没有指定cursor但是指定了`size`, 数据如果超出`size`就会返回游标ID.
iftoint(option.size) andtoint(option.size) >0then
query[#query+1] = {"batchSize", type(option) =='table' andtoint(option.size) or0}
end
end
-- 限制返回字段
iftype(option.project) =='table' then
query[#query+1] = {"projection", option.project}
end
end
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionread_query(self)
returnread_msg_body(self)
end
-- --------- QUERY --------- --
-- --------- INSERT --------- --
localfunctionsend_insert(self, db, table, array, option)
localdocuments=new_tab(#array, 0)
forindex, tabinipairs(array) do
documents[index] =assert(bson_encode(tab))
end
localquery= {{"insert", table}, {"$db", db}}
ifoptionthen
ifoption.orderedthen
query[#query+1] = {"ordered", true}
end
ifself.have_transactionandoption.concernthen
query[#query+1] = {"writeConcern", option.concern}
end
end
localsection1=bson_encode_order(unpack(query))
localsection2=concat(documents)
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 10+4+#section2, "documents"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionread_insert(self)
returnread_msg_body(self)
end
-- --------- INSERT --------- --
-- --------- UPDATE --------- --
localfunctionsend_update(self, db, table, filter, update, option)
localsection1=bson_encode_order({"update", table}, {"$db", db}, {"ordered", true})
localsection2=bson_encode({q=filter, u=update, upsert=type(option) =='table' andoption.upsertandtrueorfalse, multi=type(option) =='table' andoption.multiandtrueorfalse} )
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 8+4+#section2, "updates"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionread_update(self)
returnread_msg_body(self)
end
-- --------- UPDATE --------- --
-- --------- DELETE --------- --
localfunctionsend_delete(self, db, table, filter, option)
localsection1=bson_encode_order({"delete", table}, {"$db", db}, {"ordered", true})
localsection2=bson_encode({q=filter, limit=type(option) =='table' andtoint(option.one) ==1and1or0 })
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 8+4+#section2, "deletes"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionread_delete(self)
returnread_msg_body(self)
end
-- --------- DELETE --------- --
-- --------- AGGREGATE --------- --
localfunctionsend_aggregate(self, db, table, pipeline, option)
localquery= {{"aggregate", table}, {"cursor", bson.empty_table()}, {"pipeline", pipeline}, {"$db", db}}
iftype(option) =='table' andtoint(option.cursor) andtoint(option.cursor) >4294967296then
query= {{"getMore", toint(option.cursor)}, {"collection", table}, {"$db", db}}
iftoint(option.size) andtoint(option.size) >0then
query[#query+1] = {"batchSize", toint(option.size)}
end
end
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionread_aggregate(self)
returnread_msg_body(self)
end
-- --------- AGGREGATE --------- --
-- --------- MapReduce --------- --
localfunctionsend_mapreduce(self, db, table, map, reduce, option)
option=type(option) =='table' andoptionor {}
localquery= {
{"mapReduce", table},
{"map", bson.dump(map)},
{"reduce", bson.dump(reduce)},
{"out", option.outor { inline=1.0 }},
}
ifoption.sortthen
query[#query+1] = {"sort", option.sort }
end
ifoption.limitthen
query[#query+1] = {"limit", option.limit }
end
query[#query+1] = {"query", type(option.out) =='table' andoption.outorbson.empty_table()}
query[#query+1] = {"$db", db}
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionread_mapreduce(self)
returnread_msg_body(self)
end
-- --------- MapReduce --------- --
-- --------- Indexed --------- --
localfunctionsend_createindex(self, db, table, indexes, option)
localindex_name= {}
localkeys= {}
forname, valueinpairs(indexes) do
index_name[#index_name+1] =name.."_" ..value
keys[name] =value
end
localindex_array= {
{
name=option.nameandoption.nameor ("_" ..concat(index_name, "_") .."_"),
key=keys,
unique=option.uniqueand1ornil,
sparse=option.sparseand1orfalse,
background=option.backgroundand1orfalse,
}
}
localquery= {{"createIndexes", table}, {"indexes", index_array}, {"$db", db}}
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionsend_getindexes(self, db, table)
localquery= {{"listIndexes", table}, {"cursor", bson.empty_table()}, {"$db", db}}
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionsend_dropindexes(self, db, table, indexname)
localquery= {{"dropIndexes", table}, {"index", indexname}, {"$db", db}}
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionread_index(self)
returnread_msg_body(self)
end
-- --------- Indexed --------- --
-- --------- GridFs --------- --
localfunctionsend_gridfs_files_list(self, db, table, filter, id)
localquery= {{"find", table..".files"}, {"filter", filter}, {"$db", db}}
iftoint(id) andtoint(id) >0then
query= {{"getMore", toint(id)}, {"collection", table..".files"}, {"$db", db}}
end
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionsend_gridfs_chunks_list(self, db, table, filter, id)
localquery= {{"find", table..".chunks"}, {"filter", filter}, {"$db", db}}
iftoint(id) andtoint(id) >0then
query= {{"getMore", toint(id)}, {"collection", table..".chunks"}, {"$db", db}}
end
localsections=bson_encode_order(unpack(query))
returnself.sock:send(strpack("<i4i4i4i4i4B", #sections+21, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0, 0)) andself.sock:send(sections)
end
localfunctionsend_gridfs_files_delete(self, db, table, filter, limit)
localsection1=bson_encode_order({"delete", table..".files"}, {"$db", db}, {"ordered", true})
localsection2=bson_encode_order({"q", filter}, {"limit", toint(limit) andtoint(limit) >0andtoint(limit) or0})
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 8+4+#section2, "deletes"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionsend_gridfs_chunks_delete(self, db, table, filter, limit)
localsection1=bson_encode_order({"delete", table..".chunks"}, {"$db", db}, {"ordered", true})
localsection2=bson_encode_order({"q", filter}, {"limit", toint(limit) andtoint(limit) >0andtoint(limit) or0})
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 10+4+#section2, "documents"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionsend_gridfs_files_upload(self, db, table, oid, filename, filelength, md5sum, meta)
localsection1=bson_encode_order({"insert", table..".files"}, {"ordered", true}, {"writeConcern", {w="majority"}}, {"$db", db})
localsection2=bson_encode_order({"_id", oid}, {"length", filelength}, {"chunkSize", 261120}, {"uploadDate", now() *1e3//1}, {"md5", md5sum}, {"filename", filename}, {"metadata", metaor {}})
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 10+4+#section2, "documents"), section2 }
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionsend_gridfs_chunks_upload(self, db, table, fid, file)
localsection1=bson_encode_order({"insert", table..".chunks"}, {"ordered", true}, {"writeConcern", {w="majority"}}, {"$db", db})
locallist=new_tab(128, 0)
locallen=#file
locals, e=1, 261120
whiletruedo
list[#list+1] = { file=file:sub(s, e)}
ife>=lenthen
break
end
s=e+1
e=s+261120
end
localsections2=new_tab(128, 0)
forindex, iteminipairs(list) do
sections2[#sections2+1] =bson_encode_order({"_id", bson.objectid()}, {"files_id", bson.objectid(fid)}, {"n", index-1}, {"data", bson.binary(item.file)})
end
localsection2=concat(sections2)
localsections=concat{strpack("<B", 0), section1, strpack("<Bi4z", 1, 10+4+#section2, "documents"), section2}
returnself.sock:send(strpack("<i4i4i4i4i4", 20+#sections, self.reqid, 0, STR_TO_OPCODE["OP_MSG"], 0)) andself.sock:send(sections)
end
localfunctionread_gridfs(self)
returnread_msg_body(self)
end
-- --------- Indexed --------- --
-- --------- HANDSHAKE --------- --
localfunctionsend_handshake(self)
localquery=assert(bson_encode_order(table.unpack({{ "isMaster", true }})))
returnself.sock:send(strpack("<i4i4i4i4i4zi4i4", #query+39, self.reqid, 0, STR_TO_OPCODE["OP_QUERY"], 0x04, 'admin.$cmd', 0, -1)) andself.sock:send(query)
end
-- --------- HANDSHAKE --------- --
-- --------- AUTH --------- --
localfunctionsend_auth(self)
localnonce, _--[[ non ]]=getn_nonce_payload(self.username)
localquery=assert(bson_encode_order({"saslStart", 1}, {"autoAuthorize", 1}, {"mechanism", self.auth_mode}, {"payload", nonce}))
local_=self.sock:send(strpack("<i4i4i4i4i4zi4i4", #query+29+#(self.db..'.$cmd'), self.reqid, 0, STR_TO_OPCODE["OP_QUERY"], 0x04, self.db..'.$cmd', 0, -1)) andself.sock:send(query)
localheader, response, err=read_reply(self)
ifnotheaderorresponse.ok~=1then
returnfalse, errorresponse.errmsgor"[MONGO ERROR]: Unknown Error."
end
ifnotresponse['conversationId'] then
returnfalse, "Invalid conversationId."
end
localpayload=response["payload"]
ifnotpayloadthen
returnfalse, "Invalid payload."
end
payload=base64decode(payload)
-- var_dump(header); var_dump(response);
localp= { r=nil, s=nil, i=nil }
forkey, valueinpayload:gmatch("([^,=]+)=([^,]+)") do
p[key] =value
end
-- 检查启动协议是否匹配.
-- if not find(p['r'] or "", '^' .. non) then
-- return false, "Invalid nonce when server return data."
-- end
localwithout_proof="c=biws,r=" ..p['r']
localsalted_password=salt_password(md5(fmt("%s:mongo:%s", self.username, self.password), true), p['s'], toint(p['i']))
localclient_key=hmac_sha1(salted_password, "Client Key")
localauth_msg=concat({base64decode(nonce):sub(4), payload, without_proof}, ",")
query=assert(bson_encode_order({"saslContinue", 1}, {"conversationId", response['conversationId']}, {"payload", base64encode(without_proof..',' .."p=" ..base64encode(xor_str(client_key, hmac_sha1(sha1(client_key), auth_msg))))}))
local_=self.sock:send(strpack("<i4i4i4i4i4zi4i4", #query+29+#(self.db..'.$cmd'), self.reqid, 0, STR_TO_OPCODE["OP_QUERY"], 0x04, self.db..'.$cmd', 0, -1)) andself.sock:send(query)
header, response, err=read_reply(self)
ifnotheaderorresponse.ok~=1then
returnfalse, errorresponse.errmsgor"[MONGO ERROR]: Unknown Error."
end
p= { v=nil}
response["payload"] =base64decode(response["payload"])
forkey, valueinstring.gmatch(response["payload"], "([^,=]+)=([^,]+)") do
p[key] =value
end
ifp['v'] ~=base64encode(hmac_sha1(hmac_sha1(salted_password, "Server Key"), auth_msg)) then
returnfalse, "Server returned an invalid signature."
end
ifnotresponse.donethen
query=assert(bson_encode_order({"saslContinue", 1}, {"conversationId", response['conversationId']}, {"payload", ""}))
local_=self.sock:send(strpack("<i4i4i4i4i4zi4i4", #query+29+#(self.db..'.$cmd'), self.reqid, 0, STR_TO_OPCODE["OP_QUERY"], 0x04, self.db..'.$cmd', 0, -1)) andself.sock:send(query)
header, response, err=read_reply(self)
ifnotheaderorresponse.ok~=1ornotresponse.donethen
returnfalse, errorresponse.errmsgor"[MONGO ERROR]: Authorization failed."
end
end
returntrue
end
-- --------- AUTH --------- --
localprotocol= { __Version__=0.1 }
---comment 发送授权认证
functionprotocol.request_auth(self)
iftype(self.username) =='string' andtype(self.password) =='string' then
localtab, err=send_auth(self)
ifnottabthen
returnfalse, err
end
end
returntrue
end
---comment 心跳与握手消息
functionprotocol.request_handshake(self)
localok=send_handshake(self)
ifnotokthen
returnfalse, "[MONGO ERROR]: Server closed this session when client send hello request."
end
localheader, response, err=read_reply(self)
ifnotheaderthen
returnfalse, "[MONGO ERROR]: Server connected refuse."
end
ifresponse.ok~=1orresponse.maxWireVersion<6then
-- 如果探测到MongoDB版本低于3.6则当做连接失败
returnfalse, errorresponse.errmsgor"[MONGO ERROR]: Version below 3.6 are not supported."
end
-- var_dump(header); var_dump(response);
self.have_transaction=response.maxWireVersion>=7-- 是否支持事务
returnresponse
end
---comment 查询语句
functionprotocol.request_query(self, db, table, filter, option)
ifnotsend_query(self, db, table, filter, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send query request."
end
returnread_query(self)
end
---comment 插入语句
functionprotocol.request_insert(self, db, table, array, option)
ifnotsend_insert(self, db, table, array, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send insert request."
end
returnread_insert(self)
end
---comment 更新语句
functionprotocol.request_update(self, db, table, filter, update, option)
ifnotsend_update(self, db, table, filter, update, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send update request."
end
returnread_update(self)
end
---comment 删除语句
functionprotocol.request_delete(self, db, table, array, option)
ifnotsend_delete(self, db, table, array, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send delete request."
end
returnread_delete(self)
end
---comment 统计查询
functionprotocol.request_count(self, db, table, filter, option)
ifnotsend_aggregate(self, db, table, { { ["$match"] =type(filter) =='table' andfilteror {} }, {["$group"] = { _id=bson.null(), n= {['$sum'] =1 } }} }, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send count request."
end
returnread_aggregate(self)
end
---comment 聚合查询
functionprotocol.request_aggregate(self, db, table, filter, option)
iftype(filter) ~='table' ornotnext(filter) then
filter=bson.empty_array()
elseif#filter<1then
filter= { filter }
end
ifnotsend_aggregate(self, db, table, filter, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send aggregate request."
end
returnread_aggregate(self)
end
---comment 分布式计算
functionprotocol.request_mapreduce(self, db, table, map, reduce, option)
ifnotsend_mapreduce(self, db, table, map, reduce, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send mapreduce request."
end
returnread_mapreduce(self)
end
---comment 创建索引
functionprotocol.request_createindex(self, db, table, indexs, option)
ifnotsend_createindex(self, db, table, indexs, option) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send createIndex request."
end
returnread_index(self)
end
---comment 获取索引
functionprotocol.request_getindexes(self, db, table)
ifnotsend_getindexes(self, db, table) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send getIndexes request."
end
returnread_index(self)
end
---comment 获取索引
functionprotocol.request_dropindexes(self, db, table, indexname)
ifnotsend_dropindexes(self, db, table, indexname) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send dropIndex request."
end
returnread_index(self)
end
---comment 获取GridFS Files
functionprotocol.request_gridfs_files_list(self, db, table, filter, id)
ifnotsend_gridfs_files_list(self, db, table, filter, id) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
---comment 获取GridFS Chunks
functionprotocol.request_gridfs_chunks_list(self, db, table, filter, id)
ifnotsend_gridfs_chunks_list(self, db, table, filter, id) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
---comment 删除GridFS Files
functionprotocol.request_gridfs_files_delete(self, db, table, filter, limit)
ifnotsend_gridfs_files_delete(self, db, table, filter, limit) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
---comment 删除GridFS Chunks
functionprotocol.request_gridfs_chunks_delete(self, db, table, filter, limit)
ifnotsend_gridfs_chunks_delete(self, db, table, filter, limit) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
functionprotocol.request_gridfs_files_upload(self, db, table, oid, filename, file, md5sum, meta)
ifnotsend_gridfs_files_upload(self, db, table, oid, filename, file, md5sum, meta) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
functionprotocol.request_gridfs_chunks_upload(self, db, table, fid, file)
ifnotsend_gridfs_chunks_upload(self, db, table, fid, file) then
self.connected=false
returnfalse, "[MONGO ERROR]: Server closed this session when client send GridFS request."
end
returnread_gridfs(self)
end
returnprotocol