pgsql_sock.erl 17 KB

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