pgsql_sock.erl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. %%% Copyright (C) 2009 - Will Glozer. All rights reserved.
  2. %%% Copyright (C) 2011 - Anton Lebedevich. All rights reserved.
  3. -module(pgsql_sock).
  4. -behavior(gen_server).
  5. -export([start_link/0,
  6. close/1,
  7. get_parameter/2,
  8. cancel/1]).
  9. -export([handle_call/3, handle_cast/2, handle_info/2]).
  10. -export([init/1, code_change/3, terminate/2]).
  11. %% state callbacks
  12. -export([auth/2, initializing/2, on_message/2]).
  13. -include("pgsql.hrl").
  14. -include("pgsql_binary.hrl").
  15. -record(state, {mod,
  16. sock,
  17. data = <<>>,
  18. backend,
  19. handler,
  20. queue = queue:new(),
  21. async,
  22. parameters = [],
  23. types = [],
  24. columns = [],
  25. rows = [],
  26. results = [],
  27. sync_required,
  28. txstatus}).
  29. %% -- client interface --
  30. start_link() ->
  31. gen_server:start_link(?MODULE, [], []).
  32. close(C) when is_pid(C) ->
  33. catch gen_server:cast(C, stop),
  34. ok.
  35. get_parameter(C, Name) ->
  36. gen_server:call(C, {get_parameter, to_binary(Name)}, infinity).
  37. cancel(S) ->
  38. gen_server:cast(S, cancel).
  39. %% -- gen_server implementation --
  40. init([]) ->
  41. {ok, #state{}}.
  42. handle_call({get_parameter, Name}, _From, State) ->
  43. case lists:keysearch(Name, 1, State#state.parameters) of
  44. {value, {Name, Value}} -> Value;
  45. false -> Value = undefined
  46. end,
  47. {reply, {ok, Value}, State};
  48. handle_call(Command, From, State) ->
  49. #state{queue = Q} = State,
  50. Req = {{call, From}, Command},
  51. command(Command, State#state{queue = queue:in(Req, Q)}).
  52. handle_cast({{Method, From, Ref}, Command} = Req, State)
  53. when ((Method == cast) or (Method == incremental)),
  54. is_pid(From),
  55. is_reference(Ref) ->
  56. #state{queue = Q} = State,
  57. command(Command, State#state{queue = queue:in(Req, Q)});
  58. handle_cast(stop, State) ->
  59. {stop, normal, flush_queue(State, {error, closed})};
  60. handle_cast(cancel, State = #state{backend = {Pid, Key}}) ->
  61. {ok, {Addr, Port}} = inet:peername(State#state.sock),
  62. SockOpts = [{active, false}, {packet, raw}, binary],
  63. %% TODO timeout
  64. {ok, Sock} = gen_tcp:connect(Addr, Port, SockOpts),
  65. Msg = <<16:?int32, 80877102:?int32, Pid:?int32, Key:?int32>>,
  66. ok = gen_tcp:send(Sock, Msg),
  67. gen_tcp:close(Sock),
  68. {noreply, State}.
  69. handle_info({Closed, Sock}, #state{sock = Sock} = State)
  70. when Closed == tcp_closed; Closed == ssl_closed ->
  71. {stop, sock_closed, flush_queue(State, {error, sock_closed})};
  72. handle_info({Error, Sock, Reason}, #state{sock = Sock} = State)
  73. when Error == tcp_error; Error == ssl_error ->
  74. Why = {sock_error, Reason},
  75. {stop, Why, flush_queue(State, {error, Why})};
  76. handle_info({_, Sock, Data2}, #state{data = Data, sock = Sock} = State) ->
  77. loop(State#state{data = <<Data/binary, Data2/binary>>}).
  78. terminate(_Reason, _State) ->
  79. %% TODO send termination msg, close socket ??
  80. ok.
  81. code_change(_OldVsn, State, _Extra) ->
  82. {ok, State}.
  83. %% -- internal functions --
  84. command(Command, State = #state{sync_required = true})
  85. when Command /= sync ->
  86. {noreply, finish(State, {error, sync_required})};
  87. command({connect, Host, Username, Password, Opts}, State) ->
  88. Timeout = proplists:get_value(timeout, Opts, 5000),
  89. Port = proplists:get_value(port, Opts, 5432),
  90. SockOpts = [{active, false}, {packet, raw}, binary, {nodelay, true}],
  91. {ok, Sock} = gen_tcp:connect(Host, Port, SockOpts, Timeout),
  92. State2 = case proplists:get_value(ssl, Opts) of
  93. T when T == true; T == required ->
  94. start_ssl(Sock, T, Opts, State);
  95. _ ->
  96. State#state{mod = gen_tcp, sock = Sock}
  97. end,
  98. Opts2 = ["user", 0, Username, 0],
  99. case proplists:get_value(database, Opts, undefined) of
  100. undefined -> Opts3 = Opts2;
  101. Database -> Opts3 = [Opts2 | ["database", 0, Database, 0]]
  102. end,
  103. send(State2, [<<196608:?int32>>, Opts3, 0]),
  104. Async = proplists:get_value(async, Opts, undefined),
  105. setopts(State2, [{active, true}]),
  106. put(username, Username),
  107. put(password, Password),
  108. {noreply,
  109. State2#state{handler = auth,
  110. async = Async}};
  111. command({squery, Sql}, State) ->
  112. send(State, $Q, [Sql, 0]),
  113. {noreply, State};
  114. %% TODO add fast_equery command that doesn't need parsed statement,
  115. %% uses default (text) column format,
  116. %% sends Describe after Bind to get RowDescription
  117. command({equery, Statement, Parameters}, State) ->
  118. #statement{name = StatementName, columns = Columns} = Statement,
  119. Bin1 = pgsql_wire:encode_parameters(Parameters),
  120. Bin2 = pgsql_wire:encode_formats(Columns),
  121. send(State, $B, ["", 0, StatementName, 0, Bin1, Bin2]),
  122. send(State, $E, ["", 0, <<0:?int32>>]),
  123. send(State, $C, [$S, "", 0]),
  124. send(State, $S, []),
  125. {noreply, State};
  126. command({parse, Name, Sql, Types}, State) ->
  127. Bin = pgsql_wire:encode_types(Types),
  128. send(State, $P, [Name, 0, Sql, 0, Bin]),
  129. send(State, $D, [$S, Name, 0]),
  130. send(State, $H, []),
  131. {noreply, State};
  132. command({bind, Statement, PortalName, Parameters}, State) ->
  133. #statement{name = StatementName, columns = Columns, types = Types} = Statement,
  134. Typed_Parameters = lists:zip(Types, Parameters),
  135. Bin1 = pgsql_wire:encode_parameters(Typed_Parameters),
  136. Bin2 = pgsql_wire:encode_formats(Columns),
  137. send(State, $B, [PortalName, 0, StatementName, 0, Bin1, Bin2]),
  138. send(State, $H, []),
  139. {noreply, State};
  140. command({execute, _Statement, PortalName, MaxRows}, State) ->
  141. send(State, $E, [PortalName, 0, <<MaxRows:?int32>>]),
  142. send(State, $H, []),
  143. {noreply, State};
  144. command({describe_statement, Name}, State) ->
  145. send(State, $D, [$S, Name, 0]),
  146. send(State, $H, []),
  147. {noreply, State};
  148. command({describe_portal, Name}, State) ->
  149. send(State, $D, [$P, Name, 0]),
  150. send(State, $H, []),
  151. {noreply, State};
  152. command({close, Type, Name}, State) ->
  153. case Type of
  154. statement -> Type2 = $S;
  155. portal -> Type2 = $P
  156. end,
  157. send(State, $C, [Type2, Name, 0]),
  158. send(State, $H, []),
  159. {noreply, State};
  160. command(sync, State) ->
  161. send(State, $S, []),
  162. {noreply, State#state{sync_required = false}}.
  163. start_ssl(S, Flag, Opts, State) ->
  164. ok = gen_tcp:send(S, <<8:?int32, 80877103:?int32>>),
  165. Timeout = proplists:get_value(timeout, Opts, 5000),
  166. {ok, <<Code>>} = gen_tcp:recv(S, 1, Timeout),
  167. case Code of
  168. $S ->
  169. case ssl:connect(S, Opts, Timeout) of
  170. {ok, S2} -> State#state{mod = ssl, sock = S2};
  171. {error, Reason} -> exit({ssl_negotiation_failed, Reason})
  172. end;
  173. $N ->
  174. case Flag of
  175. true -> State;
  176. required -> exit(ssl_not_available)
  177. end
  178. end.
  179. setopts(#state{mod = Mod, sock = Sock}, Opts) ->
  180. case Mod of
  181. gen_tcp -> inet:setopts(Sock, Opts);
  182. ssl -> ssl:setopts(Sock, Opts)
  183. end.
  184. send(#state{mod = Mod, sock = Sock}, Data) ->
  185. Mod:send(Sock, pgsql_wire:encode(Data)).
  186. send(#state{mod = Mod, sock = Sock}, Type, Data) ->
  187. Mod:send(Sock, pgsql_wire:encode(Type, Data)).
  188. loop(#state{data = Data, handler = Handler} = State) ->
  189. case pgsql_wire:decode_message(Data) of
  190. {Message, Tail} ->
  191. case ?MODULE:Handler(Message, State#state{data = Tail}) of
  192. {noreply, State2} ->
  193. loop(State2);
  194. R = {stop, _Reason2, _State2} ->
  195. R
  196. end;
  197. _ ->
  198. {noreply, State}
  199. end.
  200. finish(State, Result) ->
  201. finish(State, Result, Result).
  202. finish(State = #state{queue = Q}, Notice, Result) ->
  203. case queue:get(Q) of
  204. {{cast, From, Ref}, _} ->
  205. From ! {self(), Ref, Result};
  206. {{incremental, From, Ref}, _} ->
  207. From ! {self(), Ref, Notice};
  208. {{call, From}, _} ->
  209. gen_server:reply(From, Result)
  210. end,
  211. State#state{queue = queue:drop(Q),
  212. types = [],
  213. columns = [],
  214. rows = [],
  215. results = []}.
  216. add_result(State = #state{queue = Q, results = Results}, Notice, Result) ->
  217. Results2 = case queue:get(Q) of
  218. {{incremental, From, Ref}, _} ->
  219. From ! {self(), Ref, Notice},
  220. Results;
  221. _ ->
  222. [Result | Results]
  223. end,
  224. State#state{types = [],
  225. columns = [],
  226. rows = [],
  227. results = Results2}.
  228. add_row(State = #state{queue = Q, rows = Rows}, Data) ->
  229. Rows2 = case queue:get(Q) of
  230. {{incremental, From, Ref}, _} ->
  231. From ! {self(), Ref, {data, Data}},
  232. Rows;
  233. _ ->
  234. [Data | Rows]
  235. end,
  236. State#state{rows = Rows2}.
  237. notify(State = #state{queue = Q}, Notice) ->
  238. case queue:get(Q) of
  239. {{incremental, From, Ref}, _} ->
  240. From ! {self(), Ref, Notice};
  241. _ ->
  242. ignore
  243. end,
  244. State.
  245. notify_async(State = #state{async = Pid}, Msg) ->
  246. case is_pid(Pid) of
  247. true -> Pid ! {pgsql, self(), Msg};
  248. false -> false
  249. end,
  250. State.
  251. command_tag(#state{queue = Q}) ->
  252. {_, Req} = queue:get(Q),
  253. if is_tuple(Req) ->
  254. element(1, Req);
  255. is_atom(Req) ->
  256. Req
  257. end.
  258. get_columns(State) ->
  259. #state{queue = Q, columns = Columns} = State,
  260. case queue:get(Q) of
  261. {_, {equery, #statement{columns = C}, _}} ->
  262. C;
  263. {_, {execute, #statement{columns = C}, _, _}} ->
  264. C;
  265. {_, {squery, _}} ->
  266. Columns
  267. end.
  268. make_statement(State) ->
  269. #state{queue = Q, types = Types, columns = Columns} = State,
  270. Name = case queue:get(Q) of
  271. {_, {parse, N, _, _}} -> N;
  272. {_, {describe_statement, N}} -> N
  273. end,
  274. #statement{name = Name, types = Types, columns = Columns}.
  275. sync_required(#state{queue = Q} = State) ->
  276. case queue:is_empty(Q) of
  277. false ->
  278. case command_tag(State) of
  279. sync ->
  280. State;
  281. _ ->
  282. sync_required(finish(State, {error, sync_required}))
  283. end;
  284. true ->
  285. State#state{sync_required = true}
  286. end.
  287. flush_queue(#state{queue = Q} = State, Error) ->
  288. case queue:is_empty(Q) of
  289. false ->
  290. flush_queue(finish(State, Error), Error);
  291. true -> State
  292. end.
  293. to_binary(B) when is_binary(B) -> B;
  294. to_binary(L) when is_list(L) -> list_to_binary(L).
  295. hex(Bin) ->
  296. HChar = fun(N) when N < 10 -> $0 + N;
  297. (N) when N < 16 -> $W + N
  298. end,
  299. <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
  300. %% -- backend message handling --
  301. %% AuthenticationOk
  302. auth({$R, <<0:?int32>>}, State) ->
  303. {noreply, State#state{handler = initializing}};
  304. %% AuthenticationCleartextPassword
  305. auth({$R, <<3:?int32>>}, State) ->
  306. send(State, $p, [get(password), 0]),
  307. {noreply, State};
  308. %% AuthenticationMD5Password
  309. auth({$R, <<5:?int32, Salt:4/binary>>}, State) ->
  310. Digest1 = hex(erlang:md5([get(password), get(username)])),
  311. Str = ["md5", hex(erlang:md5([Digest1, Salt])), 0],
  312. send(State, $p, Str),
  313. {noreply, State};
  314. auth({$R, <<M:?int32, _/binary>>}, State) ->
  315. case M of
  316. 2 -> Method = kerberosV5;
  317. 4 -> Method = crypt;
  318. 6 -> Method = scm;
  319. 7 -> Method = gss;
  320. 8 -> Method = sspi;
  321. _ -> Method = unknown
  322. end,
  323. State2 = finish(State, {error, {unsupported_auth_method, Method}}),
  324. {stop, normal, State2};
  325. %% ErrorResponse
  326. auth({error, E}, State) ->
  327. case E#error.code of
  328. <<"28000">> -> Why = invalid_authorization_specification;
  329. <<"28P01">> -> Why = invalid_password;
  330. Any -> Why = Any
  331. end,
  332. {stop, normal, finish(State, {error, Why})};
  333. auth(Other, State) ->
  334. on_message(Other, State).
  335. %% BackendKeyData
  336. initializing({$K, <<Pid:?int32, Key:?int32>>}, State) ->
  337. {noreply, State#state{backend = {Pid, Key}}};
  338. %% ReadyForQuery
  339. initializing({$Z, <<Status:8>>}, State) ->
  340. #state{parameters = Parameters} = State,
  341. erase(username),
  342. erase(password),
  343. %% TODO decode dates to now() format
  344. case lists:keysearch(<<"integer_datetimes">>, 1, Parameters) of
  345. {value, {_, <<"on">>}} -> put(datetime_mod, pgsql_idatetime);
  346. {value, {_, <<"off">>}} -> put(datetime_mod, pgsql_fdatetime)
  347. end,
  348. State2 = finish(State#state{handler = on_message,
  349. txstatus = Status},
  350. connected),
  351. {noreply, State2};
  352. initializing({error, _} = Error, State) ->
  353. {stop, normal, finish(State, Error)};
  354. initializing(Other, State) ->
  355. on_message(Other, State).
  356. %% ParseComplete
  357. on_message({$1, <<>>}, State) ->
  358. {noreply, State};
  359. %% ParameterDescription
  360. on_message({$t, <<_Count:?int16, Bin/binary>>}, State) ->
  361. Types = [pgsql_types:oid2type(Oid) || <<Oid:?int32>> <= Bin],
  362. State2 = notify(State#state{types = Types}, {types, Types}),
  363. {noreply, State2};
  364. %% RowDescription
  365. on_message({$T, <<Count:?int16, Bin/binary>>}, State) ->
  366. Columns = pgsql_wire:decode_columns(Count, Bin),
  367. Columns2 =
  368. case command_tag(State) of
  369. C when C == describe_portal; C == squery ->
  370. Columns;
  371. C when C == parse; C == describe_statement ->
  372. [Col#column{format = pgsql_wire:format(Col#column.type)}
  373. || Col <- Columns]
  374. end,
  375. State2 = State#state{columns = Columns2},
  376. Message = {columns, Columns2},
  377. State3 = case command_tag(State2) of
  378. squery ->
  379. notify(State2, Message);
  380. T when T == parse; T == describe_statement ->
  381. finish(State2, Message, {ok, make_statement(State2)});
  382. describe_portal ->
  383. finish(State2, Message, {ok, Columns})
  384. end,
  385. {noreply, State3};
  386. %% NoData
  387. on_message({$n, <<>>}, State) ->
  388. State2 = case command_tag(State) of
  389. C when C == parse; C == describe_statement ->
  390. finish(State, no_data, {ok, make_statement(State)});
  391. describe_portal ->
  392. finish(State, no_data, {ok, []})
  393. end,
  394. {noreply, State2};
  395. %% BindComplete
  396. on_message({$2, <<>>}, State) ->
  397. State2 = case command_tag(State) of
  398. equery ->
  399. State;
  400. bind ->
  401. finish(State, ok)
  402. end,
  403. {noreply, State2};
  404. %% CloseComplete
  405. on_message({$3, <<>>}, State) ->
  406. State2 = case command_tag(State) of
  407. equery ->
  408. State;
  409. close ->
  410. finish(State, ok)
  411. end,
  412. {noreply, State2};
  413. %% DataRow
  414. on_message({$D, <<_Count:?int16, Bin/binary>>}, State) ->
  415. Data = pgsql_wire:decode_data(get_columns(State), Bin),
  416. {noreply, add_row(State, Data)};
  417. %% PortalSuspended
  418. on_message({$s, <<>>}, State) ->
  419. State2 = finish(State,
  420. suspended,
  421. {partial, lists:reverse(State#state.rows)}),
  422. {noreply, State2};
  423. %% CommandComplete
  424. on_message({$C, Bin}, State) ->
  425. Complete = pgsql_wire:decode_complete(Bin),
  426. Command = command_tag(State),
  427. Notice = {complete, Complete},
  428. Rows = lists:reverse(State#state.rows),
  429. State2 = case {Command, Complete, Rows} of
  430. {execute, {_, Count}, []} ->
  431. finish(State, Notice, {ok, Count});
  432. {execute, {_, Count}, _} ->
  433. finish(State, Notice, {ok, Count, Rows});
  434. {execute, _, _} ->
  435. finish(State, Notice, {ok, Rows});
  436. {C, {_, Count}, []} when C == squery; C == equery ->
  437. add_result(State, Notice, {ok, Count});
  438. {C, {_, Count}, _} when C == squery; C == equery ->
  439. add_result(State, Notice, {ok, Count, get_columns(State), Rows});
  440. {C, _, _} when C == squery; C == equery ->
  441. add_result(State, Notice, {ok, get_columns(State), Rows})
  442. end,
  443. {noreply, State2};
  444. %% EmptyQueryResponse
  445. on_message({$I, _Bin}, State) ->
  446. Notice = {complete, empty},
  447. State2 = case command_tag(State) of
  448. execute ->
  449. finish(State, Notice, {ok, [], []});
  450. C when C == squery; C == equery ->
  451. add_result(State, Notice, {ok, [], []})
  452. end,
  453. {noreply, State2};
  454. %% ReadyForQuery
  455. on_message({$Z, <<Status:8>>}, State) ->
  456. State2 = case command_tag(State) of
  457. squery ->
  458. case State#state.results of
  459. [Result] ->
  460. finish(State, done, Result);
  461. Results ->
  462. finish(State, done, lists:reverse(Results))
  463. end;
  464. equery ->
  465. case State#state.results of
  466. [Result] ->
  467. finish(State, done, Result);
  468. [] ->
  469. finish(State, done)
  470. end;
  471. sync ->
  472. finish(State, ok)
  473. end,
  474. {noreply, State2#state{txstatus = Status}};
  475. on_message(Error = {error, _}, State) ->
  476. State2 = case command_tag(State) of
  477. C when C == squery; C == equery ->
  478. add_result(State, Error, Error);
  479. _ ->
  480. sync_required(finish(State, Error))
  481. end,
  482. {noreply, State2};
  483. %% NoticeResponse
  484. on_message({$N, Data}, State) ->
  485. State2 = notify_async(State, {notice, pgsql_wire:decode_error(Data)}),
  486. {noreply, State2};
  487. %% ParameterStatus
  488. on_message({$S, Data}, State) ->
  489. [Name, Value] = pgsql_wire:decode_strings(Data),
  490. Parameters2 = lists:keystore(Name, 1, State#state.parameters,
  491. {Name, Value}),
  492. {noreply, State#state{parameters = Parameters2}};
  493. %% NotificationResponse
  494. on_message({$A, <<Pid:?int32, Strings/binary>>}, State) ->
  495. case pgsql_wire:decode_strings(Strings) of
  496. [Channel, Payload] -> ok;
  497. [Channel] -> Payload = <<>>
  498. end,
  499. State2 = notify_async(State, {notification, Channel, Pid, Payload}),
  500. {noreply, State2}.