ProtoCommon.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /**
  2. * Copyright (C) 2008 Happy Fish / YuQing
  3. *
  4. * FastDFS Java Client may be copied only under the terms of the GNU Lesser
  5. * General Public License (LGPL).
  6. * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
  7. **/
  8. package org.csource.fastdfs;
  9. import org.csource.common.MyException;
  10. import org.csource.common.NameValuePair;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.io.UnsupportedEncodingException;
  14. import java.net.Socket;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.util.Arrays;
  17. /**
  18. * protocol common functions
  19. * @author Happy Fish / YuQing
  20. * @version Version 1.18
  21. */
  22. public class ProtoCommon
  23. {
  24. /**
  25. * receive package info
  26. */
  27. public static class RecvPackageInfo
  28. {
  29. public byte errno;
  30. public byte[] body;
  31. public RecvPackageInfo(byte errno, byte[] body)
  32. {
  33. this.errno = errno;
  34. this.body = body;
  35. }
  36. }
  37. /**
  38. * receive header info
  39. */
  40. public static class RecvHeaderInfo
  41. {
  42. public byte errno;
  43. public long body_len;
  44. public RecvHeaderInfo(byte errno, long body_len)
  45. {
  46. this.errno = errno;
  47. this.body_len = body_len;
  48. }
  49. }
  50. public static final byte FDFS_PROTO_CMD_QUIT = 82;
  51. public static final byte TRACKER_PROTO_CMD_SERVER_LIST_GROUP = 91;
  52. public static final byte TRACKER_PROTO_CMD_SERVER_LIST_STORAGE = 92;
  53. public static final byte TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE = 93;
  54. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITHOUT_GROUP_ONE = 101;
  55. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ONE = 102;
  56. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_UPDATE = 103;
  57. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITH_GROUP_ONE = 104;
  58. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ALL = 105;
  59. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITHOUT_GROUP_ALL = 106;
  60. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITH_GROUP_ALL = 107;
  61. public static final byte TRACKER_PROTO_CMD_RESP = 100;
  62. public static final byte FDFS_PROTO_CMD_ACTIVE_TEST = 111;
  63. public static final byte STORAGE_PROTO_CMD_UPLOAD_FILE = 11;
  64. public static final byte STORAGE_PROTO_CMD_DELETE_FILE = 12;
  65. public static final byte STORAGE_PROTO_CMD_SET_METADATA = 13;
  66. public static final byte STORAGE_PROTO_CMD_DOWNLOAD_FILE = 14;
  67. public static final byte STORAGE_PROTO_CMD_GET_METADATA = 15;
  68. public static final byte STORAGE_PROTO_CMD_UPLOAD_SLAVE_FILE = 21;
  69. public static final byte STORAGE_PROTO_CMD_QUERY_FILE_INFO = 22;
  70. public static final byte STORAGE_PROTO_CMD_UPLOAD_APPENDER_FILE= 23; //create appender file
  71. public static final byte STORAGE_PROTO_CMD_APPEND_FILE = 24; //append file
  72. public static final byte STORAGE_PROTO_CMD_MODIFY_FILE = 34; //modify appender file
  73. public static final byte STORAGE_PROTO_CMD_TRUNCATE_FILE = 36; //truncate appender file
  74. public static final byte STORAGE_PROTO_CMD_RESP = TRACKER_PROTO_CMD_RESP;
  75. public static final byte FDFS_STORAGE_STATUS_INIT = 0;
  76. public static final byte FDFS_STORAGE_STATUS_WAIT_SYNC = 1;
  77. public static final byte FDFS_STORAGE_STATUS_SYNCING = 2;
  78. public static final byte FDFS_STORAGE_STATUS_IP_CHANGED = 3;
  79. public static final byte FDFS_STORAGE_STATUS_DELETED = 4;
  80. public static final byte FDFS_STORAGE_STATUS_OFFLINE = 5;
  81. public static final byte FDFS_STORAGE_STATUS_ONLINE = 6;
  82. public static final byte FDFS_STORAGE_STATUS_ACTIVE = 7;
  83. public static final byte FDFS_STORAGE_STATUS_NONE = 99;
  84. /**
  85. * for overwrite all old metadata
  86. */
  87. public static final byte STORAGE_SET_METADATA_FLAG_OVERWRITE = 'O';
  88. /**
  89. * for replace, insert when the meta item not exist, otherwise update it
  90. */
  91. public static final byte STORAGE_SET_METADATA_FLAG_MERGE = 'M';
  92. public static final int FDFS_PROTO_PKG_LEN_SIZE = 8;
  93. public static final int FDFS_PROTO_CMD_SIZE = 1;
  94. public static final int FDFS_GROUP_NAME_MAX_LEN = 16;
  95. public static final int FDFS_IPADDR_SIZE = 16;
  96. public static final int FDFS_DOMAIN_NAME_MAX_SIZE = 128;
  97. public static final int FDFS_VERSION_SIZE = 6;
  98. public static final int FDFS_STORAGE_ID_MAX_SIZE = 16;
  99. public static final String FDFS_RECORD_SEPERATOR = "\u0001";
  100. public static final String FDFS_FIELD_SEPERATOR = "\u0002";
  101. public static final int TRACKER_QUERY_STORAGE_FETCH_BODY_LEN = FDFS_GROUP_NAME_MAX_LEN
  102. + FDFS_IPADDR_SIZE - 1 + FDFS_PROTO_PKG_LEN_SIZE;
  103. public static final int TRACKER_QUERY_STORAGE_STORE_BODY_LEN = FDFS_GROUP_NAME_MAX_LEN
  104. + FDFS_IPADDR_SIZE + FDFS_PROTO_PKG_LEN_SIZE;
  105. protected static final int PROTO_HEADER_CMD_INDEX = FDFS_PROTO_PKG_LEN_SIZE;
  106. protected static final int PROTO_HEADER_STATUS_INDEX = FDFS_PROTO_PKG_LEN_SIZE+1;
  107. public static final byte FDFS_FILE_EXT_NAME_MAX_LEN = 6;
  108. public static final byte FDFS_FILE_PREFIX_MAX_LEN = 16;
  109. public static final byte FDFS_FILE_PATH_LEN = 10;
  110. public static final byte FDFS_FILENAME_BASE64_LENGTH = 27;
  111. public static final byte FDFS_TRUNK_FILE_INFO_LEN = 16;
  112. public static final byte ERR_NO_ENOENT = 2;
  113. public static final byte ERR_NO_EIO = 5;
  114. public static final byte ERR_NO_EBUSY = 16;
  115. public static final byte ERR_NO_EINVAL = 22;
  116. public static final byte ERR_NO_ENOSPC = 28;
  117. public static final byte ECONNREFUSED = 61;
  118. public static final byte ERR_NO_EALREADY = 114;
  119. public static final long INFINITE_FILE_SIZE = 256 * 1024L * 1024 * 1024 * 1024 * 1024L;
  120. public static final long APPENDER_FILE_SIZE = INFINITE_FILE_SIZE;
  121. public static final long TRUNK_FILE_MARK_SIZE = 512 * 1024L * 1024 * 1024 * 1024 * 1024L;
  122. public static final long NORMAL_LOGIC_FILENAME_LENGTH = FDFS_FILE_PATH_LEN + FDFS_FILENAME_BASE64_LENGTH + FDFS_FILE_EXT_NAME_MAX_LEN + 1;
  123. public static final long TRUNK_LOGIC_FILENAME_LENGTH = NORMAL_LOGIC_FILENAME_LENGTH + FDFS_TRUNK_FILE_INFO_LEN;
  124. private ProtoCommon()
  125. {
  126. }
  127. public static String getStorageStatusCaption(byte status)
  128. {
  129. switch(status)
  130. {
  131. case FDFS_STORAGE_STATUS_INIT:
  132. return "INIT";
  133. case FDFS_STORAGE_STATUS_WAIT_SYNC:
  134. return "WAIT_SYNC";
  135. case FDFS_STORAGE_STATUS_SYNCING:
  136. return "SYNCING";
  137. case FDFS_STORAGE_STATUS_IP_CHANGED:
  138. return "IP_CHANGED";
  139. case FDFS_STORAGE_STATUS_DELETED:
  140. return "DELETED";
  141. case FDFS_STORAGE_STATUS_OFFLINE:
  142. return "OFFLINE";
  143. case FDFS_STORAGE_STATUS_ONLINE:
  144. return "ONLINE";
  145. case FDFS_STORAGE_STATUS_ACTIVE:
  146. return "ACTIVE";
  147. case FDFS_STORAGE_STATUS_NONE:
  148. return "NONE";
  149. default:
  150. return "UNKOWN";
  151. }
  152. }
  153. /**
  154. * pack header by FastDFS transfer protocol
  155. * @param cmd which command to send
  156. * @param pkg_len package body length
  157. * @param errno status code, should be (byte)0
  158. * @return packed byte buffer
  159. */
  160. public static byte[] packHeader(byte cmd, long pkg_len, byte errno) throws UnsupportedEncodingException
  161. {
  162. byte[] header;
  163. byte[] hex_len;
  164. header = new byte[FDFS_PROTO_PKG_LEN_SIZE + 2];
  165. Arrays.fill(header, (byte)0);
  166. hex_len = ProtoCommon.long2buff(pkg_len);
  167. System.arraycopy(hex_len, 0, header, 0, hex_len.length);
  168. header[PROTO_HEADER_CMD_INDEX] = cmd;
  169. header[PROTO_HEADER_STATUS_INDEX] = errno;
  170. return header;
  171. }
  172. /**
  173. * receive pack header
  174. * @param in input stream
  175. * @param expect_cmd expect response command
  176. * @param expect_body_len expect response package body length
  177. * @return RecvHeaderInfo: errno and pkg body length
  178. */
  179. public static RecvHeaderInfo recvHeader(InputStream in, byte expect_cmd, long expect_body_len) throws IOException
  180. {
  181. byte[] header;
  182. int bytes;
  183. long pkg_len;
  184. header = new byte[FDFS_PROTO_PKG_LEN_SIZE + 2];
  185. if ((bytes=in.read(header)) != header.length)
  186. {
  187. throw new IOException("recv package size " + bytes + " != " + header.length);
  188. }
  189. if (header[PROTO_HEADER_CMD_INDEX] != expect_cmd)
  190. {
  191. throw new IOException("recv cmd: " + header[PROTO_HEADER_CMD_INDEX] + " is not correct, expect cmd: " + expect_cmd);
  192. }
  193. if (header[PROTO_HEADER_STATUS_INDEX] != 0)
  194. {
  195. return new RecvHeaderInfo(header[PROTO_HEADER_STATUS_INDEX], 0);
  196. }
  197. pkg_len = ProtoCommon.buff2long(header, 0);
  198. if (pkg_len < 0)
  199. {
  200. throw new IOException("recv body length: " + pkg_len + " < 0!");
  201. }
  202. if (expect_body_len >= 0 && pkg_len != expect_body_len)
  203. {
  204. throw new IOException("recv body length: " + pkg_len + " is not correct, expect length: " + expect_body_len);
  205. }
  206. return new RecvHeaderInfo((byte)0, pkg_len);
  207. }
  208. /**
  209. * receive whole pack
  210. * @param in input stream
  211. * @param expect_cmd expect response command
  212. * @param expect_body_len expect response package body length
  213. * @return RecvPackageInfo: errno and reponse body(byte buff)
  214. */
  215. public static RecvPackageInfo recvPackage(InputStream in, byte expect_cmd, long expect_body_len) throws IOException
  216. {
  217. RecvHeaderInfo header = recvHeader(in, expect_cmd, expect_body_len);
  218. if (header.errno != 0)
  219. {
  220. return new RecvPackageInfo(header.errno, null);
  221. }
  222. byte[] body = new byte[(int)header.body_len];
  223. int totalBytes = 0;
  224. int remainBytes = (int)header.body_len;
  225. int bytes;
  226. while (totalBytes < header.body_len)
  227. {
  228. if ((bytes=in.read(body, totalBytes, remainBytes)) < 0)
  229. {
  230. break;
  231. }
  232. totalBytes += bytes;
  233. remainBytes -= bytes;
  234. }
  235. if (totalBytes != header.body_len)
  236. {
  237. throw new IOException("recv package size " + totalBytes + " != " + header.body_len);
  238. }
  239. return new RecvPackageInfo((byte)0, body);
  240. }
  241. /**
  242. * split metadata to name value pair array
  243. * @param meta_buff metadata
  244. * @return name value pair array
  245. */
  246. public static NameValuePair[] split_metadata(String meta_buff)
  247. {
  248. return split_metadata(meta_buff, FDFS_RECORD_SEPERATOR, FDFS_FIELD_SEPERATOR);
  249. }
  250. /**
  251. * split metadata to name value pair array
  252. * @param meta_buff metadata
  253. * @param recordSeperator record/row seperator
  254. * @param filedSeperator field/column seperator
  255. * @return name value pair array
  256. */
  257. public static NameValuePair[] split_metadata(String meta_buff,
  258. String recordSeperator, String filedSeperator)
  259. {
  260. String[] rows;
  261. String[] cols;
  262. NameValuePair[] meta_list;
  263. rows = meta_buff.split(recordSeperator);
  264. meta_list = new NameValuePair[rows.length];
  265. for (int i=0; i<rows.length; i++)
  266. {
  267. cols = rows[i].split(filedSeperator, 2);
  268. meta_list[i] = new NameValuePair(cols[0]);
  269. if (cols.length == 2)
  270. {
  271. meta_list[i].setValue(cols[1]);
  272. }
  273. }
  274. return meta_list;
  275. }
  276. /**
  277. * pack metadata array to string
  278. * @param meta_list metadata array
  279. * @return packed metadata
  280. */
  281. public static String pack_metadata(NameValuePair[] meta_list)
  282. {
  283. if (meta_list.length == 0)
  284. {
  285. return "";
  286. }
  287. StringBuffer sb = new StringBuffer(32 * meta_list.length);
  288. sb.append(meta_list[0].getName()).append(FDFS_FIELD_SEPERATOR).append(meta_list[0].getValue());
  289. for (int i=1; i<meta_list.length; i++)
  290. {
  291. sb.append(FDFS_RECORD_SEPERATOR);
  292. sb.append(meta_list[i].getName()).append(FDFS_FIELD_SEPERATOR).append(meta_list[i].getValue());
  293. }
  294. return sb.toString();
  295. }
  296. /**
  297. * send quit command to server and close socket
  298. * @param sock the Socket object
  299. */
  300. public static void closeSocket(Socket sock) throws IOException
  301. {
  302. byte[] header;
  303. header = packHeader(FDFS_PROTO_CMD_QUIT, 0, (byte)0);
  304. sock.getOutputStream().write(header);
  305. sock.close();
  306. }
  307. /**
  308. * send ACTIVE_TEST command to server, test if network is ok and the server is alive
  309. * @param sock the Socket object
  310. */
  311. public static boolean activeTest(Socket sock) throws IOException
  312. {
  313. byte[] header;
  314. header = packHeader(FDFS_PROTO_CMD_ACTIVE_TEST, 0, (byte)0);
  315. sock.getOutputStream().write(header);
  316. RecvHeaderInfo headerInfo = recvHeader(sock.getInputStream(), TRACKER_PROTO_CMD_RESP, 0);
  317. return headerInfo.errno == 0 ? true : false;
  318. }
  319. /**
  320. * long convert to buff (big-endian)
  321. * @param n long number
  322. * @return 8 bytes buff
  323. */
  324. public static byte[] long2buff(long n)
  325. {
  326. byte[] bs;
  327. bs = new byte[8];
  328. bs[0] = (byte)((n >> 56) & 0xFF);
  329. bs[1] = (byte)((n >> 48) & 0xFF);
  330. bs[2] = (byte)((n >> 40) & 0xFF);
  331. bs[3] = (byte)((n >> 32) & 0xFF);
  332. bs[4] = (byte)((n >> 24) & 0xFF);
  333. bs[5] = (byte)((n >> 16) & 0xFF);
  334. bs[6] = (byte)((n >> 8) & 0xFF);
  335. bs[7] = (byte)(n & 0xFF);
  336. return bs;
  337. }
  338. /**
  339. * buff convert to long
  340. * @param bs the buffer (big-endian)
  341. * @param offset the start position based 0
  342. * @return long number
  343. */
  344. public static long buff2long(byte[] bs, int offset)
  345. {
  346. return (((long)(bs[offset] >= 0 ? bs[offset] : 256+bs[offset])) << 56) |
  347. (((long)(bs[offset+1] >= 0 ? bs[offset+1] : 256+bs[offset+1])) << 48) |
  348. (((long)(bs[offset+2] >= 0 ? bs[offset+2] : 256+bs[offset+2])) << 40) |
  349. (((long)(bs[offset+3] >= 0 ? bs[offset+3] : 256+bs[offset+3])) << 32) |
  350. (((long)(bs[offset+4] >= 0 ? bs[offset+4] : 256+bs[offset+4])) << 24) |
  351. (((long)(bs[offset+5] >= 0 ? bs[offset+5] : 256+bs[offset+5])) << 16) |
  352. (((long)(bs[offset+6] >= 0 ? bs[offset+6] : 256+bs[offset+6])) << 8) |
  353. ((long)(bs[offset+7] >= 0 ? bs[offset+7] : 256+bs[offset+7]));
  354. }
  355. /**
  356. * buff convert to int
  357. * @param bs the buffer (big-endian)
  358. * @param offset the start position based 0
  359. * @return int number
  360. */
  361. public static int buff2int(byte[] bs, int offset)
  362. {
  363. return (((int)(bs[offset] >= 0 ? bs[offset] : 256+bs[offset])) << 24) |
  364. (((int)(bs[offset+1] >= 0 ? bs[offset+1] : 256+bs[offset+1])) << 16) |
  365. (((int)(bs[offset+2] >= 0 ? bs[offset+2] : 256+bs[offset+2])) << 8) |
  366. ((int)(bs[offset+3] >= 0 ? bs[offset+3] : 256+bs[offset+3]));
  367. }
  368. /**
  369. * buff convert to ip address
  370. * @param bs the buffer (big-endian)
  371. * @param offset the start position based 0
  372. * @return ip address
  373. */
  374. public static String getIpAddress(byte[] bs, int offset)
  375. {
  376. if (bs[0] == 0 || bs[3] == 0) //storage server ID
  377. {
  378. return "";
  379. }
  380. int n;
  381. StringBuilder sbResult = new StringBuilder(16);
  382. for (int i=offset; i<offset+4; i++)
  383. {
  384. n = (bs[i] >= 0) ? bs[i] : 256 + bs[i];
  385. if (sbResult.length() > 0)
  386. {
  387. sbResult.append(".");
  388. }
  389. sbResult.append(String.valueOf(n));
  390. }
  391. return sbResult.toString();
  392. }
  393. /**
  394. * md5 function
  395. * @param source the input buffer
  396. * @return md5 string
  397. */
  398. public static String md5(byte[] source) throws NoSuchAlgorithmException
  399. {
  400. char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  401. java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
  402. md.update(source);
  403. byte tmp[] = md.digest();
  404. char str[] = new char[32];
  405. int k = 0;
  406. for (int i = 0; i < 16; i++)
  407. {
  408. str[k++] = hexDigits[tmp[i] >>> 4 & 0xf];
  409. str[k++] = hexDigits[tmp[i] & 0xf];
  410. }
  411. return new String(str);
  412. }
  413. /**
  414. * get token for file URL
  415. * @param remote_filename the filename return by FastDFS server
  416. * @param ts unix timestamp, unit: second
  417. * @param secret_key the secret key
  418. * @return token string
  419. */
  420. public static String getToken(String remote_filename, int ts, String secret_key) throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException
  421. {
  422. byte[] bsFilename = remote_filename.getBytes(ClientGlobal.g_charset);
  423. byte[] bsKey = secret_key.getBytes(ClientGlobal.g_charset);
  424. byte[] bsTimestamp = (new Integer(ts)).toString().getBytes(ClientGlobal.g_charset);
  425. byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
  426. System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
  427. System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
  428. System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
  429. return md5(buff);
  430. }
  431. /**
  432. * generate slave filename
  433. * @param master_filename the master filename to generate the slave filename
  434. * @param prefix_name the prefix name to generate the slave filename
  435. * @param ext_name the extension name of slave filename, null for same as the master extension name
  436. * @return slave filename string
  437. */
  438. public static String genSlaveFilename(String master_filename,
  439. String prefix_name, String ext_name) throws MyException
  440. {
  441. String true_ext_name;
  442. int dotIndex;
  443. if (master_filename.length() < 28 + FDFS_FILE_EXT_NAME_MAX_LEN)
  444. {
  445. throw new MyException("master filename \"" + master_filename + "\" is invalid");
  446. }
  447. dotIndex = master_filename.indexOf('.', master_filename.length() - (FDFS_FILE_EXT_NAME_MAX_LEN + 1));
  448. if (ext_name != null)
  449. {
  450. if (ext_name.length() == 0)
  451. {
  452. true_ext_name = "";
  453. }
  454. else if (ext_name.charAt(0) == '.')
  455. {
  456. true_ext_name = ext_name;
  457. }
  458. else
  459. {
  460. true_ext_name = "." + ext_name;
  461. }
  462. }
  463. else
  464. {
  465. if (dotIndex < 0)
  466. {
  467. true_ext_name = "";
  468. }
  469. else
  470. {
  471. true_ext_name = master_filename.substring(dotIndex);
  472. }
  473. }
  474. if (true_ext_name.length() == 0 && prefix_name.equals("-m"))
  475. {
  476. throw new MyException("prefix_name \"" + prefix_name + "\" is invalid");
  477. }
  478. if (dotIndex < 0)
  479. {
  480. return master_filename + prefix_name + true_ext_name;
  481. }
  482. else
  483. {
  484. return master_filename.substring(0, dotIndex) + prefix_name + true_ext_name;
  485. }
  486. }
  487. }