1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Procedural macros to generate C callback functions for use in [milter]
//! implementation.
//!
//! The attribute macros in this crate facilitate the creation of FFI callback
//! functions that are required for the configuration of a [`Milter`]. The
//! attribute macros are used to annotate ordinary Rust functions as milter
//! callbacks. A C function is then generated that delegates to the Rust
//! callback, safely, and taking care of conversion between Rust/C types.
//!
//! Callback functions serve the purpose of *event handlers* (hence the
//! nomenclature `on_*`) for the various ‘events’ that happen during an SMTP
//! conversation. For each of the stages in the milter protocol there is a
//! corresponding attribute macro.
//!
//! # Usage
//!
//! This crate is a dependency of the [milter][crate] crate, which re-exports
//! all macros under its namespace. Thus you should not need to use this crate
//! directly.
//!
//! Note that with Rust 2018 there are two ways of importing procedural macros.
//! Nowadays, macros can be imported like other symbols:
//!
//! ```
//! use milter::{on_connect, on_close, Milter, Status};
//! ```
//!
//! That does require you to list all macros in the `use` statement, though.
//! The older syntax with `extern crate` lets you import all macros without
//! listing them explicitly:
//!
//! ```
//! #[macro_use] extern crate milter;
//!
//! use milter::{Milter, Status};
//! ```
//!
//! Both notations are acceptable.
//!
//! # Callback results
//!
//! The result type of a callback function may be wrapped in a
//! [`milter::Result`] where desired. This is a convenience: as most `Context`
//! methods return `milter::Result`s these can then be unwrapped  with the `?`
//! operator.
//!
//! For example, the end-of-message handler may return plain `Status`:
//!
//! ```
//! # #[macro_use] extern crate milter_callback;
//! # use milter::{ActionContext, Status};
//! #[on_eom(eom_callback)]
//! fn handle_eom(context: ActionContext<()>) -> Status {
//!     Status::Continue
//! }
//! ```
//!
//! Or it may return `milter::Result<Status>`. The example shows the use of the
//! `?` operator enabled by choosing this return type.
//!
//! ```
//! # #[macro_use] extern crate milter_callback;
//! # use milter::{ActionContext, Status};
//! #[on_eom(eom_callback)]
//! fn handle_eom(context: ActionContext<()>) -> milter::Result<Status> {
//!     if let Some(version) = context.macro_value("v")? {
//!         println!("{}", version);
//!     }
//!
//!     Ok(Status::Continue)
//! }
//! ```
//!
//! This feature is supported on all the callback functions.
//!
//! # Failure modes
//!
//! An `Err` result returned from a callback leads to a temporary failure
//! ([`Status::Tempfail`]) response being returned to the MTA. The milter
//! then continues to handle requests normally.
//!
//! Panicking, on the other hand, leads to immediate [shutdown] of the milter.
//! All stages switch to returning a failure response and no longer execute the
//! handler functions (however, currently executing callback handlers are
//! allowed to finish). The milter library worker processes are terminated and
//! the currently blocked invocation of `Milter::run` returns. Cleanup logic in
//! the `close` or other stages is not executed.
//!
//! The principle behind the panicking behaviour is, as elsewhere, exit as
//! quickly as possible, within the constraints posed by the milter library and
//! the FFI interface.
//!
//! The above failure modes are provided as a convenience. Use explicit error
//! handling if they don’t satisfy your requirements.
//!
//! [milter]: https://docs.rs/milter/0.1.3/milter
//! [`Milter`]: https://docs.rs/milter/0.1.3/milter/struct.Milter.html
//! [crate]: https://crates.io/crates/milter
//! [`milter::Result`]: https://docs.rs/milter/0.1.3/milter/type.Result.html
//! [`Status::Tempfail`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html#variant.Tempfail
//! [shutdown]: https://docs.rs/milter/0.1.3/milter/fn.shutdown.html

#![doc(html_root_url = "https://docs.rs/milter-callback/0.1.3")]

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Ident, ItemFn, ReturnType, Type};

mod convert;

use crate::convert::*;

/// Generates a callback function of type [`NegotiateCallback`] that delegates
/// to the annotated function.
///
/// As its sole argument `on_negotiate` takes an identifier to be used as the
/// name of the generated function.
///
/// The `on_negotiate` callback is called just before the `connect` stage, to
/// negotiate certain connection parameters. The function arguments indicate
/// what parameters are available. The milter can then return a subset of these
/// to signal desired options. The signature of the annotated function must be
/// as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * [`Actions`] – the available actions
/// * [`ProtocolOpts`] – the available milter protocol options
///
/// Return type:
///
/// * a tuple containing the fields
///   * [`Status`] – the response status. The special response status
///     [`Status::AllOpts`] enables all available actions and protocol options;
///     use [`Status::Continue`] to apply your own set of actions and protocol
///     options.
///   * [`Actions`] – the desired actions
///   * [`ProtocolOpts`] – the desired protocol options
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Actions, Context, ProtocolOpts, Status};
/// # struct MyData;
///
/// #[on_negotiate(negotiate_callback)]
/// fn handle_negotiate(
///     context: Context<MyData>,
///     actions: Actions,
///     protocol_opts: ProtocolOpts,
/// ) -> (Status, Actions, ProtocolOpts) {
///     (Status::AllOpts, Default::default(), Default::default())
/// }
/// ```
///
/// [`NegotiateCallback`]: https://docs.rs/milter/0.1.3/milter/type.NegotiateCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Actions`]: https://docs.rs/milter/0.1.3/milter/struct.Actions.html
/// [`ProtocolOpts`]: https://docs.rs/milter/0.1.3/milter/struct.ProtocolOpts.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
/// [`Status::AllOpts`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html#variant.AllOpts
/// [`Status::Continue`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html#variant.Continue
#[proc_macro_attribute]
pub fn on_negotiate(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! {
        #fn_name(
            ::milter::Context::new(ctx),
            ::milter::Actions::from_bits_truncate(f0),
            ::milter::ProtocolOpts::from_bits_truncate(f1),
        )
    };
    let ok_arms = quote! {
        ::std::result::Result::Ok((::milter::Status::AllOpts, _, _)) => ::milter::Status::AllOpts as ::milter::sfsistat,
        ::std::result::Result::Ok((status, actions, protocol_opts)) => {
            *pf0 = actions.bits();
            *pf1 = protocol_opts.bits();
            *pf2 = 0;
            *pf3 = 0;
            status as ::milter::sfsistat
        }
    };
    let invoke_handler = invoke_handler_expr_ext(handler, result_ret, ok_arms);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            ctx: *mut ::milter::SMFICTX,
            f0: ::libc::c_ulong,
            f1: ::libc::c_ulong,
            f2: ::libc::c_ulong,
            f3: ::libc::c_ulong,
            pf0: *mut ::libc::c_ulong,
            pf1: *mut ::libc::c_ulong,
            pf2: *mut ::libc::c_ulong,
            pf3: *mut ::libc::c_ulong,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`ConnectCallback`] that delegates to
/// the annotated function.
///
/// As its sole argument `on_connect` takes an identifier to be used as the name
/// of the generated function.
///
/// The `on_connect` callback is called at the beginning of an SMTP connection.
/// The signature of the annotated function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>&amp;[str]</code> – the client’s hostname
/// * <code>[Option]&lt;[SocketAddr]&gt;</code> – the client’s internet socket
///   address, if any
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// use std::net::SocketAddr;
/// # struct MyData;
///
/// #[on_connect(connect_callback)]
/// fn handle_connect(
///     context: Context<MyData>,
///     hostname: &str,
///     socket_address: Option<SocketAddr>,
/// ) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`ConnectCallback`]: https://docs.rs/milter/0.1.3/milter/type.ConnectCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [Option]: https://doc.rust-lang.org/std/option/enum.Option.html
/// [SocketAddr]: https://doc.rust-lang.org/std/net/enum.SocketAddr.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_connect(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (hostname_ident, hostname) = to_str_expr("hostname", result_ret);
    let (hostaddr_ident, hostaddr) = to_socket_addr_expr("hostaddr");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #hostname, #hostaddr) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #hostname_ident: *mut ::libc::c_char,
            #hostaddr_ident: *mut ::libc::sockaddr,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`HeloCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_helo` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_helo` callback is called when a `HELO` or `EHLO` SMTP command is
/// received. The signature of the annotated function must be as specified
/// below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>&amp;[str]</code> – the client’s hostname as stated in the
///   `HELO`/`EHLO` command
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_helo(helo_callback)]
/// fn handle_helo(context: Context<MyData>, helo_host: &str) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`HeloCallback`]: https://docs.rs/milter/0.1.3/milter/type.HeloCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_helo(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (helohost_ident, helohost) = to_str_expr("helohost", result_ret);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #helohost) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #helohost_ident: *mut ::libc::c_char,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`MailCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_mail` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_mail` callback handles processing of an envelope sender (`MAIL FROM`
/// SMTP command). The signature of the annotated function must be as specified
/// below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>[Vec]&lt;&amp;[str]&gt;</code> – the SMTP command arguments (the
///   first element is the sender address)
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_mail(mail_callback)]
/// fn handle_mail(context: Context<MyData>, smtp_args: Vec<&str>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`MailCallback`]: https://docs.rs/milter/0.1.3/milter/type.MailCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_mail(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (argv_ident, argv) = to_strs_expr("argv", result_ret);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #argv) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #argv_ident: *mut *mut ::libc::c_char,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`RcptCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_rcpt` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_rcpt` callback handles processing of an envelope recipient (`RCPT
/// TO` SMTP command). It can be called multiple times for a single message. The
/// signature of the annotated function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>[Vec]&lt;&amp;[str]&gt;</code> – the SMTP command arguments (the
///   first element is the recipient address)
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_rcpt(rcpt_callback)]
/// fn handle_rcpt(context: Context<MyData>, smtp_args: Vec<&str>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`RcptCallback`]: https://docs.rs/milter/0.1.3/milter/type.RcptCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [Vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_rcpt(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (argv_ident, argv) = to_strs_expr("argv", result_ret);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #argv) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #argv_ident: *mut *mut ::libc::c_char,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`DataCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_data` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_data` callback is called at the start of the message content (before
/// header and body). The signature of the annotated function must be as
/// specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_data(data_callback)]
/// fn handle_data(context: Context<MyData>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`DataCallback`]: https://docs.rs/milter/0.1.3/milter/type.DataCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_data(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`HeaderCallback`] that delegates to
/// the annotated function.
///
/// As its sole argument `on_header` takes an identifier to be used as the name
/// of the generated function.
///
/// The `on_header` callback handles processing of a message header. It can be
/// called multiple times for a single message. If the value spans multiple
/// lines, line breaks are represented as `\n` (a single newline), not `\r\n`.
/// The signature of the annotated function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>&amp;[str]</code> – the header name
/// * <code>&amp;[str]</code> – the header value
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_header(header_callback)]
/// fn handle_header(context: Context<MyData>, name: &str, value: &str) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`HeaderCallback`]: https://docs.rs/milter/0.1.3/milter/type.HeaderCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_header(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (headerf_ident, headerf) = to_str_expr("headerf", result_ret);
    let (headerv_ident, headerv) = to_str_expr("headerv", result_ret);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #headerf, #headerv) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #headerf_ident: *mut ::libc::c_char,
            #headerv_ident: *mut ::libc::c_char,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`EohCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_eoh` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_eoh` callback is called when the end of the message header is
/// reached. The signature of the annotated function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_eoh(eoh_callback)]
/// fn handle_eoh(context: Context<MyData>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`EohCallback`]: https://docs.rs/milter/0.1.3/milter/type.EohCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_eoh(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`BodyCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_body` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_body` callback handles processing of message body content. It can be
/// called multiple times for a single message. The signature of the annotated
/// function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>[&amp;&lsqb;](https://doc.rust-lang.org/std/primitive.slice.html)[u8](https://doc.rust-lang.org/std/primitive.u8.html)[&rsqb;](https://doc.rust-lang.org/std/primitive.slice.html)</code>
///   – a content chunk of the message body, whole or in part
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_body(body_callback)]
/// fn handle_body(context: Context<MyData>, content_chunk: &[u8]) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`BodyCallback`]: https://docs.rs/milter/0.1.3/milter/type.BodyCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_body(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! {
        #fn_name(#ctx, ::std::slice::from_raw_parts(bodyp as *const u8, len))
    };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            bodyp: *mut ::libc::c_uchar,
            len: ::libc::size_t,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`EomCallback`] that delegates to the
/// annotated function.
///
/// As its sole argument `on_eom` takes an identifier to be used as the name of
/// the generated function.
///
/// The `on_eom` callback is called when the end of the message body is reached,
/// that is the end of the SMTP `DATA` command. This is the only stage where
/// message-modifying [actions] can be taken. The signature of the annotated
/// function must be as specified below.
///
/// Arguments:
///
/// * <code>[ActionContext]&lt;T&gt;</code> – the callback context
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{ActionContext, Status};
/// # struct MyData;
///
/// #[on_eom(eom_callback)]
/// fn handle_eom(context: ActionContext<MyData>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`EomCallback`]: https://docs.rs/milter/0.1.3/milter/type.EomCallback.html
/// [actions]: https://docs.rs/milter/0.1.3/milter/struct.Actions.html
/// [ActionContext]: https://docs.rs/milter/0.1.3/milter/struct.ActionContext.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_eom(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(::milter::ActionContext::new(ctx)) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            ctx: *mut ::milter::SMFICTX,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`AbortCallback`] that delegates to
/// the annotated function.
///
/// As its sole argument `on_abort` takes an identifier to be used as the name
/// of the generated function.
///
/// The `on_abort` callback is called when processing of the current *message*
/// is aborted by the MTA. The signature of the annotated function must be as
/// specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_abort(abort_callback)]
/// fn handle_abort(context: Context<MyData>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`AbortCallback`]: https://docs.rs/milter/0.1.3/milter/type.AbortCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_abort(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`CloseCallback`] that delegates to
/// the annotated function.
///
/// As its sole argument `on_close` takes an identifier to be used as the name
/// of the generated function.
///
/// The `on_close` callback is called when an SMTP connection is closed. It is
/// always closed at the end of a connection, also when messages were aborted.
/// It may even be called as the first and only callback (without
/// `on_connect`!), for example when the MTA decides not to go ahead with this
/// connection. The signature of the annotated function must be as specified
/// below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_close(close_callback)]
/// fn handle_close(context: Context<MyData>) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`CloseCallback`]: https://docs.rs/milter/0.1.3/milter/type.CloseCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_close(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

/// Generates a callback function of type [`UnknownCallback`] that delegates to
/// the annotated function.
///
/// As its sole argument `on_unknown` takes an identifier to be used as the name
/// of the generated function.
///
/// The `on_unknown` callback is called for unknown SMTP commands. The signature
/// of the annotated function must be as specified below.
///
/// Arguments:
///
/// * <code>[Context]&lt;T&gt;</code> – the callback context
/// * <code>&amp;[str]</code> – the SMTP command
///
/// Return type:
///
/// * [`Status`] – the response status
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate milter_callback;
/// use milter::{Context, Status};
/// # struct MyData;
///
/// #[on_unknown(unknown_callback)]
/// fn handle_unknown(context: Context<MyData>, smtp_cmd: &str) -> Status {
///     Status::Continue
/// }
/// ```
///
/// [`UnknownCallback`]: https://docs.rs/milter/0.1.3/milter/type.UnknownCallback.html
/// [Context]: https://docs.rs/milter/0.1.3/milter/struct.Context.html
/// [str]: https://doc.rust-lang.org/std/primitive.str.html
/// [`Status`]: https://docs.rs/milter/0.1.3/milter/enum.Status.html
#[proc_macro_attribute]
pub fn on_unknown(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ident = parse_macro_input!(attr as Ident);
    let handler_fn = parse_macro_input!(item as ItemFn);

    let result_ret = is_result(&handler_fn.sig.output);
    let (ctx_ident, ctx) = to_context_expr("ctx");
    let (arg_ident, arg) = to_str_expr("arg", result_ret);

    let fn_name = &handler_fn.sig.ident;
    let handler = quote! { #fn_name(#ctx, #arg) };
    let invoke_handler = invoke_handler_expr(handler, result_ret);

    (quote! {
        #handler_fn

        #[doc(hidden)]
        pub unsafe extern "C" fn #ident(
            #ctx_ident: *mut ::milter::SMFICTX,
            #arg_ident: *const ::libc::c_char,
        ) -> ::milter::sfsistat {
            #invoke_handler
        }
    }).into()
}

fn is_result(return_type: &ReturnType) -> bool {
    match return_type {
        ReturnType::Type(_, t) => match t.as_ref() {
            Type::Path(p) => p.path.segments.last().unwrap().ident == "Result",
            _ => false,
        },
        _ => false,
    }
}