pgsql_sock.erl 17 KB

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