├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── apns └── mod.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | # Compiled files 3 | *.o 4 | *.so 5 | *.rlib 6 | *.dll 7 | 8 | # Executables 9 | *.exe 10 | 11 | # Generated by Cargo 12 | /target/ 13 | Cargo.lock 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "apns" 4 | version = "0.2.0" 5 | authors = ["Mach "] 6 | description = "Library for Apple Push Notification Service." 7 | homepage = "https://github.com/back2mach/apns" 8 | repository = "https://github.com/back2mach/apns" 9 | readme = "README.md" 10 | keywords = ["apns", "apple", "push", "notification"] 11 | license = "Apache-2.0" 12 | 13 | [lib] 14 | 15 | name = "apns" 16 | 17 | [dependencies] 18 | 19 | num = "~0.1" 20 | openssl = "~0.9" 21 | byteorder = "~0.4" 22 | rustc-serialize = "~0.3" 23 | rand = "~0.3" 24 | quick-error = "^0.1" 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # apns 2 | APNS(Apple Push Notification Service) implemented in Rust 3 | 4 | [![Build Status](https://travis-ci.org/back2mach/apns.svg?branch=master)](https://travis-ci.org/back2mach/apns) 5 | 6 | ### Config 7 | 8 | ```rust 9 | let cert_file = Path::new("ck.pem"); 10 | let private_key_file = Path::new("no_pwd.pem"); 11 | let ca_file = Path::new("ca.pem"); 12 | let sandbox_environment = false; 13 | let apns = apns::APNS::new(sandbox_environment, cert_file, private_key_file, ca_file); 14 | ``` 15 | 16 | ### Payload Alert(Plain Format) 17 | 18 | ```rust 19 | let alert = apns::PayloadAPSAlert::Plain("Hello world"); 20 | ``` 21 | 22 | ### Payload Alert(Localized Format) 23 | 24 | ```rust 25 | let alert = apns::PayloadAPSAlert::Localized(loc_key, loc_args); 26 | ``` 27 | 28 | ### Send Payload 29 | 30 | ```rust 31 | let aps = apns::PayloadAPS{alert: alert, badge: Some(1), sound: Some(sound), content_available: None}; 32 | 33 | // Custom data 34 | let mut map = HashMap::new(); 35 | map.insert("source_id", "from"); 36 | map.insert("target_id", "to"); 37 | map.insert("message_type", "msg"); 38 | let payload = apns::Payload{aps: aps, info: Some(map)}; 39 | 40 | apns.send_payload(payload, device_token); 41 | ``` 42 | 43 | ### Feedback Service 44 | 45 | ```rust 46 | apns.get_feedback(); 47 | ``` 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/apns/mod.rs: -------------------------------------------------------------------------------- 1 | use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; 2 | 3 | use rustc_serialize::Encodable; 4 | use rustc_serialize::Encoder; 5 | use rustc_serialize::json; 6 | 7 | use openssl; 8 | use openssl::ssl; 9 | use openssl::ssl::SslStream; 10 | 11 | use std::ops::{Range, Index}; 12 | use std::net::TcpStream; 13 | use std::io::{Cursor}; 14 | use std::path::Path; 15 | use std::vec::Vec; 16 | use std::collections::HashMap; 17 | use std::time; 18 | 19 | use num::pow; 20 | use rand::{self, Rng}; 21 | 22 | 23 | #[derive(Debug)] 24 | pub struct Payload<'a> { 25 | pub aps: PayloadAPS<'a>, 26 | pub info: Option> 27 | } 28 | 29 | #[derive(Debug)] 30 | pub struct PayloadAPS<'a> { 31 | pub alert: PayloadAPSAlert<'a>, 32 | pub badge: Option, 33 | pub sound: Option<&'a str>, 34 | pub content_available: Option, 35 | pub category: Option<&'a str> 36 | } 37 | 38 | #[derive(Debug)] 39 | pub struct PayloadAPSAlertDictionary<'a> { 40 | pub title: Option<&'a str>, 41 | pub body: Option<&'a str>, 42 | pub title_loc_key: Option<&'a str>, 43 | pub title_loc_args: Option>, 44 | pub action_loc_key: Option<&'a str>, 45 | pub loc_key: Option<&'a str>, 46 | pub loc_args: Option>, 47 | pub launch_image: Option<&'a str> 48 | } 49 | 50 | #[derive(Debug)] 51 | pub enum PayloadAPSAlert<'a> { 52 | Plain(&'a str), 53 | Localized(&'a str, Vec<&'a str>), 54 | Dictionary(PayloadAPSAlertDictionary<'a>) 55 | } 56 | 57 | impl<'a> Encodable for Payload<'a> { 58 | fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 59 | match *self { 60 | Payload{ref aps, ref info} => { 61 | if let Some(ref map) = *info { 62 | encoder.emit_struct("Payload", 1 + map.len(), |encoder| { 63 | try!(encoder.emit_struct_field( "aps", 0usize, |encoder| aps.encode(encoder))); 64 | let mut index = 1usize; 65 | for (key, val) in map.iter() { 66 | try!(encoder.emit_struct_field(key, index, |encoder| val.encode(encoder))); 67 | index = index + 1; 68 | } 69 | Ok(()) 70 | }) 71 | } 72 | else { 73 | encoder.emit_struct("Payload", 1, |encoder| { 74 | try!(encoder.emit_struct_field( "aps", 0usize, |encoder| aps.encode(encoder))); 75 | Ok(()) 76 | }) 77 | } 78 | } 79 | } 80 | } 81 | } 82 | 83 | impl<'a> Encodable for PayloadAPS<'a> { 84 | fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 85 | match *self { 86 | PayloadAPS{ref alert, ref badge, ref sound, ref content_available, ref category} => { 87 | let mut count = 1; 88 | if badge.is_some() { count = count + 1; } 89 | if sound.is_some() { count = count + 1; } 90 | if content_available.is_some() { count = count + 1; } 91 | if category.is_some() { count = count + 1; } 92 | 93 | let mut index = 0usize; 94 | encoder.emit_struct("PayloadAPS", count, |encoder| { 95 | try!(encoder.emit_struct_field( "alert", index, |encoder| alert.encode(encoder))); 96 | index = index + 1; 97 | if badge.is_some() { 98 | try!(encoder.emit_struct_field( "badge", index, |encoder| badge.unwrap().encode(encoder))); 99 | index = index + 1; 100 | } 101 | if sound.is_some() { 102 | try!(encoder.emit_struct_field( "sound", index, |encoder| sound.unwrap().encode(encoder))); 103 | index = index + 1; 104 | } 105 | if content_available.is_some() { 106 | try!(encoder.emit_struct_field( "content-available", index, |encoder| content_available.unwrap().encode(encoder))); 107 | index = index + 1; 108 | } 109 | if category.is_some() { 110 | try!(encoder.emit_struct_field( "category", index, |encoder| category.unwrap().encode(encoder))); 111 | index = index + 1; 112 | } 113 | Ok(()) 114 | }) 115 | } 116 | } 117 | } 118 | } 119 | 120 | impl<'a> Encodable for PayloadAPSAlert<'a> { 121 | fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 122 | match *self { 123 | PayloadAPSAlert::Plain(ref str) => { 124 | encoder.emit_str(str) 125 | }, 126 | PayloadAPSAlert::Localized(ref key, ref args) => { 127 | encoder.emit_struct("PayloadAPSAlert", 2, |encoder| { 128 | try!(encoder.emit_struct_field( "loc-key", 0usize, |encoder| key.encode(encoder))); 129 | try!(encoder.emit_struct_field( "loc-args", 1usize, |encoder| args.encode(encoder))); 130 | Ok(()) 131 | }) 132 | }, 133 | PayloadAPSAlert::Dictionary(ref dictionary) => { 134 | try!(dictionary.encode(encoder)); 135 | Ok(()) 136 | } 137 | } 138 | } 139 | } 140 | 141 | impl<'a> Encodable for PayloadAPSAlertDictionary<'a> { 142 | fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 143 | match *self { 144 | PayloadAPSAlertDictionary{ref title, ref body, ref title_loc_key, ref title_loc_args, ref action_loc_key, ref loc_key, ref loc_args, ref launch_image} => { 145 | let mut count = 0; 146 | if title.is_some() { count = count + 1; } 147 | if body.is_some() { count = count + 1; } 148 | if title_loc_key.is_some() { count = count + 1; } 149 | if title_loc_args.is_some() { count = count + 1; } 150 | if action_loc_key.is_some() { count = count + 1; } 151 | if loc_key.is_some() { count = count + 1; } 152 | if loc_args.is_some() { count = count + 1; } 153 | if launch_image.is_some() { count = count + 1; } 154 | 155 | let mut index = 0usize; 156 | encoder.emit_struct("PayloadAPSAlertDictionary", count, |encoder| { 157 | if title.is_some() { 158 | try!(encoder.emit_struct_field( "title", index, |encoder| title.unwrap().encode(encoder))); 159 | index = index + 1; 160 | } 161 | if body.is_some() { 162 | try!(encoder.emit_struct_field( "body", index, |encoder| body.unwrap().encode(encoder))); 163 | index = index + 1; 164 | } 165 | if title_loc_key.is_some() { 166 | try!(encoder.emit_struct_field( "title-loc-key", index, |encoder| title_loc_key.unwrap().encode(encoder))); 167 | index = index + 1; 168 | } 169 | if let Some(ref title_loc_args_) = *title_loc_args { 170 | try!(encoder.emit_struct_field( "title-loc-args", index, |encoder| title_loc_args_.encode(encoder))); 171 | index = index + 1; 172 | } 173 | if action_loc_key.is_some() { 174 | try!(encoder.emit_struct_field( "action-loc-key", index, |encoder| action_loc_key.unwrap().encode(encoder))); 175 | index = index + 1; 176 | } 177 | if loc_key.is_some() { 178 | try!(encoder.emit_struct_field( "loc-key", index, |encoder| loc_key.unwrap().encode(encoder))); 179 | index = index + 1; 180 | } 181 | if let Some(ref loc_args_) = *loc_args { 182 | try!(encoder.emit_struct_field( "title-loc-args", index, |encoder| loc_args_.encode(encoder))); 183 | index = index + 1; 184 | } 185 | if launch_image.is_some() { 186 | try!(encoder.emit_struct_field( "launch-image", index, |encoder| launch_image.unwrap().encode(encoder))); 187 | index = index + 1; 188 | } 189 | Ok(()) 190 | }) 191 | } 192 | } 193 | } 194 | } 195 | 196 | #[allow(dead_code)] 197 | fn hex_to_int(hex: &str) -> u32 { 198 | let mut total = 0u32; 199 | let mut n = hex.to_string().len(); 200 | 201 | for c in hex.chars() { 202 | n = n - 1; 203 | match c { 204 | '0'...'9' => { 205 | total += pow(16, n) * ((c as u32) - ('0' as u32)); 206 | }, 207 | 'a'...'f' => { 208 | total += pow(16, n) * ((c as u32) - ('a' as u32) + 10); 209 | }, 210 | _ => { 211 | 212 | } 213 | } 214 | } 215 | 216 | return total; 217 | } 218 | 219 | #[allow(dead_code)] 220 | fn convert_to_binary(device_token: &str) -> Vec { 221 | let mut device_token_bytes: Vec = Vec::new(); 222 | for i in 0..8 { 223 | let string = device_token.to_string(); 224 | let range = Range{start:i*8, end:i*8+8}; 225 | let sub_str = string.index(range); 226 | 227 | let sub_str_num = hex_to_int(sub_str); 228 | let mut sub_str_bytes = vec![]; 229 | let _ = sub_str_bytes.write_u32::(sub_str_num); 230 | 231 | for s in sub_str_bytes.iter() { 232 | device_token_bytes.push(*s); 233 | } 234 | } 235 | 236 | return device_token_bytes; 237 | } 238 | 239 | #[allow(dead_code)] 240 | pub fn convert_to_token(binary: &[u8]) -> String { 241 | let mut token = "".to_string(); 242 | for i in 0..8 { 243 | let range = Range{start:i*4, end:i*4+4}; 244 | let sub_slice = binary.index(range); 245 | 246 | let mut rdr = Cursor::new(sub_slice.to_vec()); 247 | let num = rdr.read_u32::().unwrap(); 248 | 249 | token = format!("{}{:x}", token, num); 250 | } 251 | return token; 252 | } 253 | 254 | #[allow(dead_code)] 255 | pub fn convert_to_timestamp(binary: &[u8]) -> u32 { 256 | let mut rdr = Cursor::new(binary.to_vec()); 257 | let num = rdr.read_u32::().unwrap(); 258 | 259 | return num; 260 | } 261 | 262 | pub struct APNS<'a> { 263 | pub sandbox: bool, 264 | pub certificate: &'a Path, 265 | pub private_key: &'a Path, 266 | pub ca_certificate: &'a Path, 267 | } 268 | 269 | impl<'a> APNS<'a> { 270 | pub fn new(sandbox: bool, cert_file: &'a Path, private_key_file: &'a Path, ca_file: &'a Path) -> APNS<'a> { 271 | APNS{sandbox: sandbox, certificate: cert_file, private_key: private_key_file, ca_certificate: ca_file} 272 | } 273 | 274 | #[allow(dead_code)] 275 | pub fn get_feedback(&self) -> Result, Error> { 276 | let apns_feedback_production = "feedback.push.apple.com:2196"; 277 | let apns_feedback_development = "feedback.sandbox.push.apple.com:2196"; 278 | 279 | let apns_feedback_url = if self.sandbox { apns_feedback_development } else { apns_feedback_production }; 280 | let mut stream = try!(get_ssl_stream(apns_feedback_url, self.certificate, self.private_key, self.ca_certificate)); 281 | 282 | let mut tokens: Vec<(u32, String)> = Vec::new(); 283 | let mut read_buffer = [0u8; 38]; 284 | loop { 285 | match stream.ssl_read(&mut read_buffer) { 286 | Ok(size) => { 287 | if size != 38 { 288 | break; 289 | } 290 | }, 291 | Err(..) => { 292 | /* return Result::Err(SslError::StreamError(error));*/ 293 | break; 294 | } 295 | } 296 | let time_range = Range{start:0, end:4}; 297 | let time_slice = read_buffer.index(time_range); 298 | let time = convert_to_timestamp(time_slice); 299 | 300 | let token_range = Range{start:6, end:38}; 301 | let token_slice = read_buffer.index(token_range); 302 | 303 | let token = convert_to_token(token_slice); 304 | tokens.push((time, token)); 305 | } 306 | 307 | return Result::Ok(tokens); 308 | } 309 | 310 | #[allow(dead_code)] 311 | pub fn send_payload(&self, payload: Payload, device_token: &str) { 312 | let notification_bytes = get_notification_bytes(payload, device_token); 313 | 314 | let apns_url_production = "gateway.push.apple.com:2195"; 315 | let apns_url_development = "gateway.sandbox.push.apple.com:2195"; 316 | 317 | let apns_url = if self.sandbox { apns_url_development } else { apns_url_production }; 318 | 319 | let ssl_result = get_ssl_stream(apns_url, self.certificate, self.private_key, self.ca_certificate); 320 | match ssl_result { 321 | Ok(mut ssls) => { 322 | if let Err(error) = ssls.ssl_write(¬ification_bytes) { 323 | println!("ssl_stream write error {:?}", error); 324 | } 325 | 326 | // Read possible error code response 327 | if ssls.ssl().pending() == 6 { 328 | let mut read_buffer = [0u8; 6]; 329 | match ssls.ssl_read(&mut read_buffer) { 330 | Ok(size) => { 331 | for c in read_buffer.iter() { 332 | print!("{}", c); 333 | } 334 | println!("ssl_stream read size {:?}", size); 335 | } 336 | Err(error) => { 337 | println!("ssl_stream read error {:?}", error); 338 | } 339 | } 340 | } 341 | }, 342 | Err(error) => { 343 | println!("failed to get_ssl_stream error {:?}", error); 344 | } 345 | }; 346 | } 347 | } 348 | 349 | fn get_notification_bytes(payload: Payload, device_token: &str) -> Vec { 350 | let payload_str = match json::encode(&payload) { 351 | Ok(json_str) => { json_str.to_string() } 352 | Err(error) => { 353 | println!("json encode error {:?}", error); 354 | return vec![]; 355 | } 356 | }; 357 | 358 | let payload_bytes = payload_str.into_bytes(); 359 | let device_token_bytes: Vec = convert_to_binary(device_token); 360 | 361 | let mut notification_buffer: Vec = vec![]; 362 | let mut message_buffer: Vec = vec![]; 363 | 364 | // Device token 365 | let mut device_token_length = vec![]; 366 | let _ = device_token_length.write_u16::(device_token_bytes.len() as u16); 367 | 368 | message_buffer.push(1u8); 369 | for s in device_token_length.iter() { 370 | message_buffer.push(*s); 371 | } 372 | for s in device_token_bytes.iter() { 373 | message_buffer.push(*s); 374 | } 375 | 376 | // Payload 377 | let mut payload_length = vec![]; 378 | let _ = payload_length.write_u16::(payload_bytes.len() as u16); 379 | 380 | message_buffer.push(2u8); 381 | for s in payload_length.iter() { 382 | message_buffer.push(*s); 383 | } 384 | for s in payload_bytes.iter() { 385 | message_buffer.push(*s); 386 | } 387 | 388 | // Notification identifier 389 | let payload_id = rand::thread_rng().gen(); 390 | let mut payload_id_be = vec![]; 391 | let _ = payload_id_be.write_u32::(payload_id); 392 | 393 | let mut payload_id_length = vec![]; 394 | let _ = payload_id_length.write_u16::(payload_id_be.len() as u16); 395 | 396 | message_buffer.push(3u8); 397 | for s in payload_id_length.iter() { 398 | message_buffer.push(*s); 399 | } 400 | for s in payload_id_be.iter() { 401 | message_buffer.push(*s); 402 | } 403 | 404 | // Expiration date 405 | let time = match time::SystemTime::now().duration_since(time::UNIX_EPOCH) { 406 | Ok(dur) => dur, 407 | Err(err) => err.duration(), 408 | }.as_secs() + 86400; // expired after one day 409 | let mut exp_date_be = vec![]; 410 | let _ = exp_date_be.write_u32::(time as u32); 411 | 412 | let mut exp_date_length = vec![]; 413 | let _ = exp_date_length.write_u16::(exp_date_be.len() as u16); 414 | 415 | message_buffer.push(4u8); 416 | for s in exp_date_length.iter() { 417 | message_buffer.push(*s); 418 | } 419 | for s in exp_date_be.iter() { 420 | message_buffer.push(*s); 421 | } 422 | 423 | // Priority 424 | let mut priority_length = vec![]; 425 | let _ = priority_length.write_u16::(1u16); 426 | 427 | message_buffer.push(5u8); 428 | for s in priority_length.iter() { 429 | message_buffer.push(*s); 430 | } 431 | message_buffer.push(10u8); 432 | 433 | let mut message_buffer_length = vec![]; 434 | let _ = message_buffer_length.write_u32::(message_buffer.len() as u32); 435 | 436 | let command = 2u8; 437 | notification_buffer.push(command); 438 | for s in message_buffer_length.iter() { 439 | notification_buffer.push(*s); 440 | } 441 | for s in message_buffer.iter() { 442 | notification_buffer.push(*s); 443 | } 444 | 445 | return notification_buffer; 446 | } 447 | 448 | fn get_ssl_stream(url: &str, cert_file: &Path, private_key_file: &Path, ca_file: &Path) -> Result, Error> { 449 | let mut connector_builder = try!(ssl::SslConnectorBuilder::new(ssl::SslMethod::tls()).map_err(|e|Error::SslContext(e))); 450 | { 451 | let context = connector_builder.builder_mut(); 452 | if let Err(error) = context.set_ca_file(ca_file) { 453 | println!("set_CA_file error {:?}", error); 454 | return Err(Error::SslContext(error)); 455 | } 456 | if let Err(error) = context.set_certificate_file(cert_file, openssl::x509::X509_FILETYPE_PEM) { 457 | println!("set_certificate_file error {:?}", error); 458 | return Err(Error::SslContext(error)); 459 | } 460 | if let Err(error) = context.set_private_key_file(private_key_file, openssl::x509::X509_FILETYPE_PEM) { 461 | println!("set_private_key_file error {:?}", error); 462 | return Err(Error::SslContext(error)); 463 | } 464 | } 465 | let tcp_conn = match TcpStream::connect(url) { 466 | Ok(conn) => { 467 | conn 468 | }, 469 | Err(error) => { 470 | return Err(Error::TcpStream(error)); 471 | } 472 | }; 473 | let connector = connector_builder.build(); 474 | return connector.connect(url,tcp_conn).map_err(|e|Error::Handshake(e)); 475 | } 476 | 477 | /* ERRORS */ 478 | quick_error! { 479 | #[derive(Debug)] 480 | pub enum Error { 481 | Handshake(err: openssl::ssl::HandshakeError) {from() cause(err)} 482 | TcpStream(err: ::std::io::Error) { from() cause(err) } 483 | SslContext(err: openssl::error::ErrorStack) { from() cause(err) } 484 | } 485 | } 486 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate num; 2 | extern crate rand; 3 | extern crate openssl; 4 | extern crate byteorder; 5 | extern crate rustc_serialize; 6 | #[macro_use] extern crate quick_error; 7 | 8 | pub mod apns; 9 | 10 | pub use apns::APNS; 11 | pub use apns::Payload; 12 | pub use apns::PayloadAPS; 13 | pub use apns::PayloadAPSAlert; 14 | pub use apns::PayloadAPSAlertDictionary; 15 | --------------------------------------------------------------------------------