repo
string
commit
string
message
string
diff
string
disbeliever/disbeliever-overlay
634e396c72dd72fe13f274a2731557ab7dfc9f9f
fixed app-dicts/tagainijisho-1.0.1
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest index 8be8f38..82127d2 100644 --- a/app-dicts/tagainijisho/Manifest +++ b/app-dicts/tagainijisho/Manifest @@ -1,6 +1,6 @@ DIST tagainijisho-0.8.85.tar.gz 16824374 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff SHA512 5f205aa83b4c69fb26c80fd23902352b27af6d2b482caad8fc0803e91ad9a903d24daf8f0141a4d08140f6963dbe346f76315f037b75fc3f54269fd151f36d5f WHIRLPOOL 2dc41c381172772cb1a62db808caf2c6a46fcf68d127e110336f5c6a4d6b5f6aad1c70cde80fa8ea2bed72c98850d20e2b0a3eca1434d55f994aae047a69705d DIST tagainijisho-0.9.4.tar.gz 19044179 SHA256 61b840d1252c459d1130c24dfa7883b50ced513e076cf31388c88ab5eca4f0e0 SHA512 6322efe7af6d527fbe958458601c470c88e298ef30c179fdbe91b6a9a668d264521959ddc0bdfed3e2aeb44cfd93bcedb854ef4cc8471b2d5d802fc1c42baff1 WHIRLPOOL caa1b4a24e4fe8c35e7f0f279595555146fe0c76a3365840299e541a6b1a5e9d815ec6a5cfec474ad7607e65e0b7449527ae3380d4990c706345dde4edb00422 DIST tagainijisho-1.0.1.tar.gz 21201810 SHA256 76f893107cfd804752e0ea78d52ceee70c51f1ea08e65d5c61d7bb5801dc9c9b SHA512 c7e3b778ba2c32f9100aad7d5131e646eac11e7e9c56c2a3378b20a1ac5cc32d460a5d573a4e8414504df47198e1f32f36ecf05d21a18dc0d6eabc0acfab499a WHIRLPOOL 3acf2736da90ea03e77beb0c720d94239c89d4a89f4d18131531f17f3483717d9463de7fc394efcdd7743857ff48777eff24795e4ff438fa87663d38efa7c71d EBUILD tagainijisho-0.8.85.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac EBUILD tagainijisho-0.9.4.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac -EBUILD tagainijisho-1.0.1.ebuild 393 SHA256 e37e3dc789dd0eb67f6e4c6bb4d86f8de0c37865770fd641992b243324ede404 SHA512 87a30b056b3a3abbfde788f75dbc77a0c8d58bcb393a01ec64d1e7e1036579445e99ddf6dc8175cd9abbab4d6fc15f99bae792f28d4ef38e4085d04491b6670c WHIRLPOOL 9fdbf2af4152af96fb0ff4e2d67e4b012b4d27daa1f2b4528c168f9d1c3b49f2506b7d5255c52f04253522a99978a575c23fe2a68fbf40743a8b8bc5ce94c32b +EBUILD tagainijisho-1.0.1.ebuild 390 SHA256 3476e32c1ec6da66f812b42d7206febb25fa8944d4ff8cd991aafc989ace0bf0 SHA512 4b5078b06e9b1d861d15f760278af77f28261d029f9b3db4b8d0be9d193292c4260899d15c2e03ee13e51c4288c18c98661e63227d6340661ed42292111238ce WHIRLPOOL 1f491d42ba4c6543787d83d50e7e380725a289e20c77feb3d68043e6dbd12260a411116b4efa89438f038c12925be9a3ee62638a09d291878b9713c101e0ea20
disbeliever/disbeliever-overlay
fde91a3e00f0e80c5fd285252243c2882be79339
+app-dicts/tagainijisho-1.0.1
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest index c295418..8be8f38 100644 --- a/app-dicts/tagainijisho/Manifest +++ b/app-dicts/tagainijisho/Manifest @@ -1,4 +1,6 @@ DIST tagainijisho-0.8.85.tar.gz 16824374 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff SHA512 5f205aa83b4c69fb26c80fd23902352b27af6d2b482caad8fc0803e91ad9a903d24daf8f0141a4d08140f6963dbe346f76315f037b75fc3f54269fd151f36d5f WHIRLPOOL 2dc41c381172772cb1a62db808caf2c6a46fcf68d127e110336f5c6a4d6b5f6aad1c70cde80fa8ea2bed72c98850d20e2b0a3eca1434d55f994aae047a69705d DIST tagainijisho-0.9.4.tar.gz 19044179 SHA256 61b840d1252c459d1130c24dfa7883b50ced513e076cf31388c88ab5eca4f0e0 SHA512 6322efe7af6d527fbe958458601c470c88e298ef30c179fdbe91b6a9a668d264521959ddc0bdfed3e2aeb44cfd93bcedb854ef4cc8471b2d5d802fc1c42baff1 WHIRLPOOL caa1b4a24e4fe8c35e7f0f279595555146fe0c76a3365840299e541a6b1a5e9d815ec6a5cfec474ad7607e65e0b7449527ae3380d4990c706345dde4edb00422 +DIST tagainijisho-1.0.1.tar.gz 21201810 SHA256 76f893107cfd804752e0ea78d52ceee70c51f1ea08e65d5c61d7bb5801dc9c9b SHA512 c7e3b778ba2c32f9100aad7d5131e646eac11e7e9c56c2a3378b20a1ac5cc32d460a5d573a4e8414504df47198e1f32f36ecf05d21a18dc0d6eabc0acfab499a WHIRLPOOL 3acf2736da90ea03e77beb0c720d94239c89d4a89f4d18131531f17f3483717d9463de7fc394efcdd7743857ff48777eff24795e4ff438fa87663d38efa7c71d EBUILD tagainijisho-0.8.85.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac EBUILD tagainijisho-0.9.4.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac +EBUILD tagainijisho-1.0.1.ebuild 393 SHA256 e37e3dc789dd0eb67f6e4c6bb4d86f8de0c37865770fd641992b243324ede404 SHA512 87a30b056b3a3abbfde788f75dbc77a0c8d58bcb393a01ec64d1e7e1036579445e99ddf6dc8175cd9abbab4d6fc15f99bae792f28d4ef38e4085d04491b6670c WHIRLPOOL 9fdbf2af4152af96fb0ff4e2d67e4b012b4d27daa1f2b4528c168f9d1c3b49f2506b7d5255c52f04253522a99978a575c23fe2a68fbf40743a8b8bc5ce94c32b
disbeliever/disbeliever-overlay
b89054d854505460c1c9a3f36de25e3357dd3bbc
add app-dicts/tagainijisho-0.9.4, remove tagainijisho-0.9.2
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest index e590128..c295418 100644 --- a/app-dicts/tagainijisho/Manifest +++ b/app-dicts/tagainijisho/Manifest @@ -1,4 +1,4 @@ -DIST tagainijisho-0.8.85.tar.gz 16824374 RMD160 1fe9726af089175b3bb918b7221699073f31ee4b SHA1 eb5cf5785c26de36b75cd2dd4605f6dcf09a2fc2 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff -DIST tagainijisho-0.9.2.tar.gz 18519329 RMD160 9e4919ec055e1532a72f236302bca6b3dade80b8 SHA1 91e3bc1c1aacc487a4832a799edf3a2bd7937c70 SHA256 fbdcbdf3674eb3ce04cd85679b20a65ba767942dcdaa0565024b5e93723bc92d -EBUILD tagainijisho-0.8.85.ebuild 389 RMD160 952bbb8c6562d510162bff08efbae964075ed617 SHA1 c42b61f95b94b5c5507a07771360d4af039aea5e SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 -EBUILD tagainijisho-0.9.2.ebuild 389 RMD160 952bbb8c6562d510162bff08efbae964075ed617 SHA1 c42b61f95b94b5c5507a07771360d4af039aea5e SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 +DIST tagainijisho-0.8.85.tar.gz 16824374 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff SHA512 5f205aa83b4c69fb26c80fd23902352b27af6d2b482caad8fc0803e91ad9a903d24daf8f0141a4d08140f6963dbe346f76315f037b75fc3f54269fd151f36d5f WHIRLPOOL 2dc41c381172772cb1a62db808caf2c6a46fcf68d127e110336f5c6a4d6b5f6aad1c70cde80fa8ea2bed72c98850d20e2b0a3eca1434d55f994aae047a69705d +DIST tagainijisho-0.9.4.tar.gz 19044179 SHA256 61b840d1252c459d1130c24dfa7883b50ced513e076cf31388c88ab5eca4f0e0 SHA512 6322efe7af6d527fbe958458601c470c88e298ef30c179fdbe91b6a9a668d264521959ddc0bdfed3e2aeb44cfd93bcedb854ef4cc8471b2d5d802fc1c42baff1 WHIRLPOOL caa1b4a24e4fe8c35e7f0f279595555146fe0c76a3365840299e541a6b1a5e9d815ec6a5cfec474ad7607e65e0b7449527ae3380d4990c706345dde4edb00422 +EBUILD tagainijisho-0.8.85.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac +EBUILD tagainijisho-0.9.4.ebuild 389 SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 SHA512 0681d471535d45637ce0075356008e4eed775951db7ae72bad328d8bd900324a4470180e1a03372ad347390c1f28e6da39413176ce192586b3e4a409cf85fed5 WHIRLPOOL 022f0618ec43879936f6487ceb6d33818b8fa03b77c3a11e94c9161db211a4772876edbba3664bc219c81e9529c66d8401572548bba1c5f0cc4a5d529c69bfac diff --git a/app-dicts/tagainijisho/tagainijisho-0.9.2.ebuild b/app-dicts/tagainijisho/tagainijisho-0.9.4.ebuild similarity index 100% rename from app-dicts/tagainijisho/tagainijisho-0.9.2.ebuild rename to app-dicts/tagainijisho/tagainijisho-0.9.4.ebuild
disbeliever/disbeliever-overlay
794765cc057a964162e37d26632628c1051fde59
add media-sound/deadbeef-0.5.6, remove media-sound/deadbeef-0.5.1-r3
diff --git a/media-sound/deadbeef/Manifest b/media-sound/deadbeef/Manifest index 22dfdc6..85beaf7 100644 --- a/media-sound/deadbeef/Manifest +++ b/media-sound/deadbeef/Manifest @@ -1,5 +1,6 @@ -DIST deadbeef-0.5.1.tar.bz2 2317508 RMD160 3d46d05b0d07fc8c3a515fcbd0c7d8525b199588 SHA1 82cbdeb3cdd5303c75d668d3d238e68b442c6db1 SHA256 449e2933634c8f06dfdac65cd1afbe87a7f97fcd8e541694d6e65fe1941ac18f -DIST deadbeef-0.5.5.tar.bz2 3219511 RMD160 af9969f10fbcc8c7e1c938a6a5c30445dc50f0a2 SHA1 cf738fdb96be152a14769e4e29aa8e45722ff332 SHA256 d9d01276f07e90155da37fb257c744af4accb4da17da048ce5604cb1174750b7 -EBUILD deadbeef-0.5.1-r1.ebuild 2796 RMD160 de57c6800c52d0675d7e78f27508f4da2cba595e SHA1 623b8f8e5a51f74fdeb337b6340a07670d038a16 SHA256 4646b3bae2ab58686951a35f6daff96610e62cc9f86e5da62d707534101c83a4 -EBUILD deadbeef-0.5.1-r3.ebuild 2793 RMD160 4b4edaadf3283fb53ada996739e7296107d252ab SHA1 df528e35f9a71560509ed51e08f4d63d4cb7a733 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c -EBUILD deadbeef-0.5.5.ebuild 2793 RMD160 4b4edaadf3283fb53ada996739e7296107d252ab SHA1 df528e35f9a71560509ed51e08f4d63d4cb7a733 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c +DIST deadbeef-0.5.1.tar.bz2 2317508 SHA256 449e2933634c8f06dfdac65cd1afbe87a7f97fcd8e541694d6e65fe1941ac18f SHA512 49c06b6a208d69ebc5e252289da998c64fdf441f2c52457884ede446b0e2346cd1b5163cf065f5fd85565c563b1b673462d8ded855b60deeb51d1d0b8b8d8327 WHIRLPOOL e215a587e422a22965913df44f023b2aa1717d103a8d935e2505b26de2dcd39757e3820ae3acfa2c5244b53bb9c5b606b5ed49915447ffe94158ef4b7f21b11a +DIST deadbeef-0.5.5.tar.bz2 3219511 SHA256 d9d01276f07e90155da37fb257c744af4accb4da17da048ce5604cb1174750b7 SHA512 18ff9d10f3e31bfde5ae193c8d738d973299b5f96ac4137cd805b6aca843fc60ee81c7371faaad0e5dde6a1a8683231afa85dbd1fa9cd4798d261ba5ae7fcc76 WHIRLPOOL 0f1b98b08bbe6c7b9d3086c711760d585dde0330ae8b8bf83c924a24b879c638771c2b75ac5ea86ead561f6dec9aa97913e972835d653773a52ff0f0033cc001 +DIST deadbeef-0.5.6.tar.bz2 3279899 SHA256 17c123eb50e33c89403d8d3035b9132463a227a6905fd42bcbb2a3a5616cea5b SHA512 20d8d58e2df90078af2dd6583c7ae9d7b3b6f7d73cef1d823910614278779614c1544e839a886ab7ab972ad235220829d8e07dc1c959e98c94fc1e47299e5b4a WHIRLPOOL 9b7349c4664be4e98a935fb97393195cc4911d28e011a83c8f3d621b004ccb70f3e5e06129138eb3edf64b17c533b0b214a29e2fb71b96e7b6638b92d2a69947 +EBUILD deadbeef-0.5.1-r3.ebuild 2793 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c SHA512 2a47f0746e4a0440ff1d876a2092dc2b7a83b0a36ea041df48955040cb2d027580d215411988a0385a118b9f6980a61787e59d11bb9881cbd1ad11054c69a5cd WHIRLPOOL ffd3d9d08907c5786d2f6830533c04d2a965a7c88c89f0eb997f682c3a681c049086a0589ad2e2e3005e749663bbc4a69af21ed0a002ef6e386a99d23a298429 +EBUILD deadbeef-0.5.5.ebuild 2793 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c SHA512 2a47f0746e4a0440ff1d876a2092dc2b7a83b0a36ea041df48955040cb2d027580d215411988a0385a118b9f6980a61787e59d11bb9881cbd1ad11054c69a5cd WHIRLPOOL ffd3d9d08907c5786d2f6830533c04d2a965a7c88c89f0eb997f682c3a681c049086a0589ad2e2e3005e749663bbc4a69af21ed0a002ef6e386a99d23a298429 +EBUILD deadbeef-0.5.6.ebuild 2793 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c SHA512 2a47f0746e4a0440ff1d876a2092dc2b7a83b0a36ea041df48955040cb2d027580d215411988a0385a118b9f6980a61787e59d11bb9881cbd1ad11054c69a5cd WHIRLPOOL ffd3d9d08907c5786d2f6830533c04d2a965a7c88c89f0eb997f682c3a681c049086a0589ad2e2e3005e749663bbc4a69af21ed0a002ef6e386a99d23a298429 diff --git a/media-sound/deadbeef/deadbeef-0.5.1-r3.ebuild b/media-sound/deadbeef/deadbeef-0.5.6.ebuild similarity index 100% rename from media-sound/deadbeef/deadbeef-0.5.1-r3.ebuild rename to media-sound/deadbeef/deadbeef-0.5.6.ebuild
disbeliever/disbeliever-overlay
793867f0227fcdcb28f2c39a779808da19787869
Add profiles/repo_name
diff --git a/profiles/repo_name b/profiles/repo_name new file mode 100644 index 0000000..563ca48 --- /dev/null +++ b/profiles/repo_name @@ -0,0 +1 @@ +disbeliever-overlay
disbeliever/disbeliever-overlay
fb0897353bf37a1e5a2cfa0b2ab41547775118e3
remove deadbeef-0.5.1-r1 (really)
diff --git a/media-sound/deadbeef/Manifest b/media-sound/deadbeef/Manifest index 4f68fa3..22dfdc6 100644 --- a/media-sound/deadbeef/Manifest +++ b/media-sound/deadbeef/Manifest @@ -1,3 +1,5 @@ DIST deadbeef-0.5.1.tar.bz2 2317508 RMD160 3d46d05b0d07fc8c3a515fcbd0c7d8525b199588 SHA1 82cbdeb3cdd5303c75d668d3d238e68b442c6db1 SHA256 449e2933634c8f06dfdac65cd1afbe87a7f97fcd8e541694d6e65fe1941ac18f +DIST deadbeef-0.5.5.tar.bz2 3219511 RMD160 af9969f10fbcc8c7e1c938a6a5c30445dc50f0a2 SHA1 cf738fdb96be152a14769e4e29aa8e45722ff332 SHA256 d9d01276f07e90155da37fb257c744af4accb4da17da048ce5604cb1174750b7 EBUILD deadbeef-0.5.1-r1.ebuild 2796 RMD160 de57c6800c52d0675d7e78f27508f4da2cba595e SHA1 623b8f8e5a51f74fdeb337b6340a07670d038a16 SHA256 4646b3bae2ab58686951a35f6daff96610e62cc9f86e5da62d707534101c83a4 EBUILD deadbeef-0.5.1-r3.ebuild 2793 RMD160 4b4edaadf3283fb53ada996739e7296107d252ab SHA1 df528e35f9a71560509ed51e08f4d63d4cb7a733 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c +EBUILD deadbeef-0.5.5.ebuild 2793 RMD160 4b4edaadf3283fb53ada996739e7296107d252ab SHA1 df528e35f9a71560509ed51e08f4d63d4cb7a733 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c diff --git a/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild b/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild deleted file mode 100644 index d58117f..0000000 --- a/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright 1999-2011 Gentoo Foundation -# Distributed under the terms of the GNU General Public License v2 -# $Header: $ - -EAPI="4" - -inherit fdo-mime - -DESCRIPTION="foobar2000-like music player." -HOMEPAGE="http://deadbeef.sourceforge.net/" -SRC_URI="mirror://sourceforge/${PN}/${P}.tar.bz2" -LICENSE="GPL-2 ZLIB" - -SLOT="0" -KEYWORDS="~x86 ~amd64" -IUSE="aac adplug alsa cdda cover curl dts encode ffmpeg flac gme +gtk - hotkeys imlib lastfm libnotify libsamplerate m3u mac midi mms mp3 - musepack nls null oss pulseaudio shellexec sid sndfile supereq threads - tta vorbis vtx wavpack zip" - -REQUIRED_USE="encode? ( gtk ) - cover? ( curl ) - lastfm? ( curl )" - -RDEPEND=" - aac? ( media-libs/faad2 ) - alsa? ( media-libs/alsa-lib ) - cdda? ( dev-libs/libcdio media-libs/libcddb ) - cover? ( - imlib? ( media-libs/imlib2 ) - !imlib? ( virtual/jpeg media-libs/libpng ) - ) - curl? ( net-misc/curl ) - ffmpeg? ( media-video/ffmpeg ) - flac? ( media-libs/flac ) - gtk? ( x11-libs/gtk+:2 ) - hotkeys? ( x11-libs/libX11 ) - libnotify? ( sys-apps/dbus ) - libsamplerate? ( media-libs/libsamplerate ) - midi? ( media-sound/timidity-freepats ) - mp3? ( media-libs/libmad ) - pulseaudio? ( media-sound/pulseaudio ) - sndfile? ( media-libs/libsndfile ) - vorbis? ( media-libs/libvorbis ) - wavpack? ( media-sound/wavpack ) - zip? ( sys-libs/zlib ) - " -DEPEND="${RDEPEND} - nls? ( virtual/libintl dev-util/intltool ) - " - -src_prepare() { - if use midi; then - # set default gentoo path - sed -e 's;/etc/timidity++/timidity-freepats.cfg;/usr/share/timidity/freepats/timidity.cfg;g' \ - -i "${S}/plugins/wildmidi/wildmidiplug.c" - fi -} - -src_configure() { - my_config="$(use_enable nls) - $(use_enable threads) - $(use_enable null nullout) - $(use_enable alsa) - $(use_enable oss) - $(use_enable gtk gtkui) - $(use_enable aac) - $(use_enable adplug) - $(use_enable cdda) - $(use_enable cover artwork) - $(use_enable curl vfs-curl) - $(use_enable dts dca) - $(use_enable encode converter) - $(use_enable ffmpeg) - $(use_enable flac) - $(use_enable gme) - $(use_enable hotkeys) - $(use_enable imlib artwork-imlib2) - $(use_enable lastfm lfm) - $(use_enable libnotify notify) - $(use_enable libsamplerate src) - $(use_enable m3u) - $(use_enable mac ffap) - $(use_enable midi wildmidi) - $(use_enable mms) - $(use_enable mp3 mad) - $(use_enable musepack) - $(use_enable pulseaudio pulse) - $(use_enable shellexec) - $(use_enable sid) - $(use_enable sndfile) - $(use_enable supereq) - $(use_enable tta) - $(use_enable vorbis) - $(use_enable vtx) - $(use_enable wavpack) - $(use_enable zip vfs-zip) - --docdir=/usr/share/doc/${PF}" - - econf ${my_config} -} - -src_install() { - # Do not compress docs as we need it for deadbeef's help function. - PORTAGE_DOCOMPRESS_SKIP+=( "/usr/share/doc/${PF}" ) - - emake DESTDIR="${D}" install || die "emake install failed" -}
disbeliever/disbeliever-overlay
cd53dd40a91b3e172e9489d4791d615ba4cbb39f
add deadbeef-0.5.5, remove deadbeef-0.5.1-r1
diff --git a/media-sound/deadbeef/deadbeef-0.5.5.ebuild b/media-sound/deadbeef/deadbeef-0.5.5.ebuild new file mode 100644 index 0000000..69306bd --- /dev/null +++ b/media-sound/deadbeef/deadbeef-0.5.5.ebuild @@ -0,0 +1,109 @@ +# Copyright 1999-2011 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +EAPI="4" + +inherit fdo-mime gnome2 + +DESCRIPTION="foobar2000-like music player." +HOMEPAGE="http://deadbeef.sourceforge.net/" +SRC_URI="mirror://sourceforge/${PN}/${P}.tar.bz2" +LICENSE="GPL-2 ZLIB" + +SLOT="0" +KEYWORDS="~x86 ~amd64" +IUSE="aac adplug alsa cdda cover curl dts encode ffmpeg flac gme +gtk + hotkeys imlib lastfm libnotify libsamplerate m3u mac midi mms mp3 + musepack nls null oss pulseaudio shellexec sid sndfile supereq threads + tta vorbis vtx wavpack zip" + +REQUIRED_USE="encode? ( gtk ) + cover? ( curl ) + lastfm? ( curl )" + +RDEPEND=" + aac? ( media-libs/faad2 ) + alsa? ( media-libs/alsa-lib ) + cdda? ( dev-libs/libcdio media-libs/libcddb ) + cover? ( + imlib? ( media-libs/imlib2 ) + !imlib? ( virtual/jpeg media-libs/libpng ) + ) + curl? ( net-misc/curl ) + ffmpeg? ( media-video/ffmpeg ) + flac? ( media-libs/flac ) + gtk? ( x11-libs/gtk+:2 ) + hotkeys? ( x11-libs/libX11 ) + libnotify? ( sys-apps/dbus ) + libsamplerate? ( media-libs/libsamplerate ) + midi? ( media-sound/timidity-freepats ) + mp3? ( media-libs/libmad ) + pulseaudio? ( media-sound/pulseaudio ) + sndfile? ( media-libs/libsndfile ) + vorbis? ( media-libs/libvorbis ) + wavpack? ( media-sound/wavpack ) + zip? ( sys-libs/zlib ) + " +DEPEND="${RDEPEND} + dev-util/pkgconfig + nls? ( virtual/libintl dev-util/intltool ) + " + +src_prepare() { + if use midi; then + # set default gentoo path + sed -e 's;/etc/timidity++/timidity-freepats.cfg;/usr/share/timidity/freepats/timidity.cfg;g' \ + -i "${S}/plugins/wildmidi/wildmidiplug.c" + fi +} + +src_configure() { + my_config="$(use_enable nls) + $(use_enable threads) + $(use_enable null nullout) + $(use_enable alsa) + $(use_enable oss) + $(use_enable gtk gtkui) + $(use_enable aac) + $(use_enable adplug) + $(use_enable cdda) + $(use_enable cover artwork) + $(use_enable curl vfs-curl) + $(use_enable dts dca) + $(use_enable encode converter) + $(use_enable ffmpeg) + $(use_enable flac) + $(use_enable gme) + $(use_enable hotkeys) + $(use_enable imlib artwork-imlib2) + $(use_enable lastfm lfm) + $(use_enable libnotify notify) + $(use_enable libsamplerate src) + $(use_enable m3u) + $(use_enable mac ffap) + $(use_enable midi wildmidi) + $(use_enable mms) + $(use_enable mp3 mad) + $(use_enable musepack) + $(use_enable pulseaudio pulse) + $(use_enable shellexec) + $(use_enable sid) + $(use_enable sndfile) + $(use_enable supereq) + $(use_enable tta) + $(use_enable vorbis) + $(use_enable vtx) + $(use_enable wavpack) + $(use_enable zip vfs-zip) + --docdir=/usr/share/doc/${PF}" + + econf ${my_config} +} + +src_install() { + # Do not compress docs as we need it for deadbeef's help function. + PORTAGE_DOCOMPRESS_SKIP+=( "/usr/share/doc/${PF}" ) + + emake DESTDIR="${D}" install +}
disbeliever/disbeliever-overlay
95eadd0e9a1c8b262a267f3df69857f452bffe70
+media-sound/deadbeef
diff --git a/media-sound/deadbeef/Manifest b/media-sound/deadbeef/Manifest new file mode 100644 index 0000000..4f68fa3 --- /dev/null +++ b/media-sound/deadbeef/Manifest @@ -0,0 +1,3 @@ +DIST deadbeef-0.5.1.tar.bz2 2317508 RMD160 3d46d05b0d07fc8c3a515fcbd0c7d8525b199588 SHA1 82cbdeb3cdd5303c75d668d3d238e68b442c6db1 SHA256 449e2933634c8f06dfdac65cd1afbe87a7f97fcd8e541694d6e65fe1941ac18f +EBUILD deadbeef-0.5.1-r1.ebuild 2796 RMD160 de57c6800c52d0675d7e78f27508f4da2cba595e SHA1 623b8f8e5a51f74fdeb337b6340a07670d038a16 SHA256 4646b3bae2ab58686951a35f6daff96610e62cc9f86e5da62d707534101c83a4 +EBUILD deadbeef-0.5.1-r3.ebuild 2793 RMD160 4b4edaadf3283fb53ada996739e7296107d252ab SHA1 df528e35f9a71560509ed51e08f4d63d4cb7a733 SHA256 fee2942ca7fe2210ca1fb2930f5d0d568f1be7eaceef061f645a6ee232bc6b1c diff --git a/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild b/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild new file mode 100644 index 0000000..d58117f --- /dev/null +++ b/media-sound/deadbeef/deadbeef-0.5.1-r1.ebuild @@ -0,0 +1,108 @@ +# Copyright 1999-2011 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +EAPI="4" + +inherit fdo-mime + +DESCRIPTION="foobar2000-like music player." +HOMEPAGE="http://deadbeef.sourceforge.net/" +SRC_URI="mirror://sourceforge/${PN}/${P}.tar.bz2" +LICENSE="GPL-2 ZLIB" + +SLOT="0" +KEYWORDS="~x86 ~amd64" +IUSE="aac adplug alsa cdda cover curl dts encode ffmpeg flac gme +gtk + hotkeys imlib lastfm libnotify libsamplerate m3u mac midi mms mp3 + musepack nls null oss pulseaudio shellexec sid sndfile supereq threads + tta vorbis vtx wavpack zip" + +REQUIRED_USE="encode? ( gtk ) + cover? ( curl ) + lastfm? ( curl )" + +RDEPEND=" + aac? ( media-libs/faad2 ) + alsa? ( media-libs/alsa-lib ) + cdda? ( dev-libs/libcdio media-libs/libcddb ) + cover? ( + imlib? ( media-libs/imlib2 ) + !imlib? ( virtual/jpeg media-libs/libpng ) + ) + curl? ( net-misc/curl ) + ffmpeg? ( media-video/ffmpeg ) + flac? ( media-libs/flac ) + gtk? ( x11-libs/gtk+:2 ) + hotkeys? ( x11-libs/libX11 ) + libnotify? ( sys-apps/dbus ) + libsamplerate? ( media-libs/libsamplerate ) + midi? ( media-sound/timidity-freepats ) + mp3? ( media-libs/libmad ) + pulseaudio? ( media-sound/pulseaudio ) + sndfile? ( media-libs/libsndfile ) + vorbis? ( media-libs/libvorbis ) + wavpack? ( media-sound/wavpack ) + zip? ( sys-libs/zlib ) + " +DEPEND="${RDEPEND} + nls? ( virtual/libintl dev-util/intltool ) + " + +src_prepare() { + if use midi; then + # set default gentoo path + sed -e 's;/etc/timidity++/timidity-freepats.cfg;/usr/share/timidity/freepats/timidity.cfg;g' \ + -i "${S}/plugins/wildmidi/wildmidiplug.c" + fi +} + +src_configure() { + my_config="$(use_enable nls) + $(use_enable threads) + $(use_enable null nullout) + $(use_enable alsa) + $(use_enable oss) + $(use_enable gtk gtkui) + $(use_enable aac) + $(use_enable adplug) + $(use_enable cdda) + $(use_enable cover artwork) + $(use_enable curl vfs-curl) + $(use_enable dts dca) + $(use_enable encode converter) + $(use_enable ffmpeg) + $(use_enable flac) + $(use_enable gme) + $(use_enable hotkeys) + $(use_enable imlib artwork-imlib2) + $(use_enable lastfm lfm) + $(use_enable libnotify notify) + $(use_enable libsamplerate src) + $(use_enable m3u) + $(use_enable mac ffap) + $(use_enable midi wildmidi) + $(use_enable mms) + $(use_enable mp3 mad) + $(use_enable musepack) + $(use_enable pulseaudio pulse) + $(use_enable shellexec) + $(use_enable sid) + $(use_enable sndfile) + $(use_enable supereq) + $(use_enable tta) + $(use_enable vorbis) + $(use_enable vtx) + $(use_enable wavpack) + $(use_enable zip vfs-zip) + --docdir=/usr/share/doc/${PF}" + + econf ${my_config} +} + +src_install() { + # Do not compress docs as we need it for deadbeef's help function. + PORTAGE_DOCOMPRESS_SKIP+=( "/usr/share/doc/${PF}" ) + + emake DESTDIR="${D}" install || die "emake install failed" +} diff --git a/media-sound/deadbeef/deadbeef-0.5.1-r3.ebuild b/media-sound/deadbeef/deadbeef-0.5.1-r3.ebuild new file mode 100644 index 0000000..69306bd --- /dev/null +++ b/media-sound/deadbeef/deadbeef-0.5.1-r3.ebuild @@ -0,0 +1,109 @@ +# Copyright 1999-2011 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +EAPI="4" + +inherit fdo-mime gnome2 + +DESCRIPTION="foobar2000-like music player." +HOMEPAGE="http://deadbeef.sourceforge.net/" +SRC_URI="mirror://sourceforge/${PN}/${P}.tar.bz2" +LICENSE="GPL-2 ZLIB" + +SLOT="0" +KEYWORDS="~x86 ~amd64" +IUSE="aac adplug alsa cdda cover curl dts encode ffmpeg flac gme +gtk + hotkeys imlib lastfm libnotify libsamplerate m3u mac midi mms mp3 + musepack nls null oss pulseaudio shellexec sid sndfile supereq threads + tta vorbis vtx wavpack zip" + +REQUIRED_USE="encode? ( gtk ) + cover? ( curl ) + lastfm? ( curl )" + +RDEPEND=" + aac? ( media-libs/faad2 ) + alsa? ( media-libs/alsa-lib ) + cdda? ( dev-libs/libcdio media-libs/libcddb ) + cover? ( + imlib? ( media-libs/imlib2 ) + !imlib? ( virtual/jpeg media-libs/libpng ) + ) + curl? ( net-misc/curl ) + ffmpeg? ( media-video/ffmpeg ) + flac? ( media-libs/flac ) + gtk? ( x11-libs/gtk+:2 ) + hotkeys? ( x11-libs/libX11 ) + libnotify? ( sys-apps/dbus ) + libsamplerate? ( media-libs/libsamplerate ) + midi? ( media-sound/timidity-freepats ) + mp3? ( media-libs/libmad ) + pulseaudio? ( media-sound/pulseaudio ) + sndfile? ( media-libs/libsndfile ) + vorbis? ( media-libs/libvorbis ) + wavpack? ( media-sound/wavpack ) + zip? ( sys-libs/zlib ) + " +DEPEND="${RDEPEND} + dev-util/pkgconfig + nls? ( virtual/libintl dev-util/intltool ) + " + +src_prepare() { + if use midi; then + # set default gentoo path + sed -e 's;/etc/timidity++/timidity-freepats.cfg;/usr/share/timidity/freepats/timidity.cfg;g' \ + -i "${S}/plugins/wildmidi/wildmidiplug.c" + fi +} + +src_configure() { + my_config="$(use_enable nls) + $(use_enable threads) + $(use_enable null nullout) + $(use_enable alsa) + $(use_enable oss) + $(use_enable gtk gtkui) + $(use_enable aac) + $(use_enable adplug) + $(use_enable cdda) + $(use_enable cover artwork) + $(use_enable curl vfs-curl) + $(use_enable dts dca) + $(use_enable encode converter) + $(use_enable ffmpeg) + $(use_enable flac) + $(use_enable gme) + $(use_enable hotkeys) + $(use_enable imlib artwork-imlib2) + $(use_enable lastfm lfm) + $(use_enable libnotify notify) + $(use_enable libsamplerate src) + $(use_enable m3u) + $(use_enable mac ffap) + $(use_enable midi wildmidi) + $(use_enable mms) + $(use_enable mp3 mad) + $(use_enable musepack) + $(use_enable pulseaudio pulse) + $(use_enable shellexec) + $(use_enable sid) + $(use_enable sndfile) + $(use_enable supereq) + $(use_enable tta) + $(use_enable vorbis) + $(use_enable vtx) + $(use_enable wavpack) + $(use_enable zip vfs-zip) + --docdir=/usr/share/doc/${PF}" + + econf ${my_config} +} + +src_install() { + # Do not compress docs as we need it for deadbeef's help function. + PORTAGE_DOCOMPRESS_SKIP+=( "/usr/share/doc/${PF}" ) + + emake DESTDIR="${D}" install +}
disbeliever/disbeliever-overlay
4e8554b9f27f044ebd45557d82b56a774bfd66bb
+tagainijisho-0.9.2.ebuild
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest index 250e739..e590128 100644 --- a/app-dicts/tagainijisho/Manifest +++ b/app-dicts/tagainijisho/Manifest @@ -1,2 +1,4 @@ DIST tagainijisho-0.8.85.tar.gz 16824374 RMD160 1fe9726af089175b3bb918b7221699073f31ee4b SHA1 eb5cf5785c26de36b75cd2dd4605f6dcf09a2fc2 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff +DIST tagainijisho-0.9.2.tar.gz 18519329 RMD160 9e4919ec055e1532a72f236302bca6b3dade80b8 SHA1 91e3bc1c1aacc487a4832a799edf3a2bd7937c70 SHA256 fbdcbdf3674eb3ce04cd85679b20a65ba767942dcdaa0565024b5e93723bc92d EBUILD tagainijisho-0.8.85.ebuild 389 RMD160 952bbb8c6562d510162bff08efbae964075ed617 SHA1 c42b61f95b94b5c5507a07771360d4af039aea5e SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 +EBUILD tagainijisho-0.9.2.ebuild 389 RMD160 952bbb8c6562d510162bff08efbae964075ed617 SHA1 c42b61f95b94b5c5507a07771360d4af039aea5e SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 diff --git a/app-dicts/tagainijisho/tagainijisho-0.9.2.ebuild b/app-dicts/tagainijisho/tagainijisho-0.9.2.ebuild new file mode 100644 index 0000000..eecd0dc --- /dev/null +++ b/app-dicts/tagainijisho/tagainijisho-0.9.2.ebuild @@ -0,0 +1,16 @@ +EAPI=2 + +inherit cmake-utils + +DESCRIPTION="Tagaini Jisho is a free, open-source Japanese dictionary and kanji lookup tool" +HOMEPAGE="http://www.tagaini.net/" +SRC_URI="http://launchpad.net/tagaini-jisho/devel/0.9.0b2/+download/${P}.tar.gz" +RESTRICT="mirror" +LICENSE="GPL-3" +SLOT="0" +KEYWORDS="~x86 ~amd64" +IUSE="" + +DEPEND=">=dev-util/cmake-2.8.1 +>=x11-libs/qt-gui-4.5:4" +RDEPEND="${DEPEND}"
disbeliever/disbeliever-overlay
7f626df99150cc4d45a6b0260eb442dfbf1feea3
add dependencies to app-dicts/tagainijisho
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest index c57d969..250e739 100644 --- a/app-dicts/tagainijisho/Manifest +++ b/app-dicts/tagainijisho/Manifest @@ -1,2 +1,2 @@ DIST tagainijisho-0.8.85.tar.gz 16824374 RMD160 1fe9726af089175b3bb918b7221699073f31ee4b SHA1 eb5cf5785c26de36b75cd2dd4605f6dcf09a2fc2 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff -EBUILD tagainijisho-0.8.85.ebuild 313 RMD160 967a663d6ed9753035763d8735bbeb3c1c6bde80 SHA1 1e760b64a4fb4efa22c14811e089803ade141d0b SHA256 55348873e6f6743378b0403985ee1b2c4a38188e154db4d71f70e90f84a9d031 +EBUILD tagainijisho-0.8.85.ebuild 389 RMD160 952bbb8c6562d510162bff08efbae964075ed617 SHA1 c42b61f95b94b5c5507a07771360d4af039aea5e SHA256 e2b97031a50919055c4253a434136faa2eb39dc01be9d4468514e825fcaf7fd5 diff --git a/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild b/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild index 2494661..eecd0dc 100644 --- a/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild +++ b/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild @@ -1,13 +1,16 @@ EAPI=2 inherit cmake-utils DESCRIPTION="Tagaini Jisho is a free, open-source Japanese dictionary and kanji lookup tool" HOMEPAGE="http://www.tagaini.net/" SRC_URI="http://launchpad.net/tagaini-jisho/devel/0.9.0b2/+download/${P}.tar.gz" RESTRICT="mirror" LICENSE="GPL-3" SLOT="0" KEYWORDS="~x86 ~amd64" IUSE="" +DEPEND=">=dev-util/cmake-2.8.1 +>=x11-libs/qt-gui-4.5:4" +RDEPEND="${DEPEND}"
disbeliever/disbeliever-overlay
c7328039769463af0a22729845907e5558676559
add app-dicts/tagainijisho, del x11-misc/zim
diff --git a/app-dicts/tagainijisho/Manifest b/app-dicts/tagainijisho/Manifest new file mode 100644 index 0000000..c57d969 --- /dev/null +++ b/app-dicts/tagainijisho/Manifest @@ -0,0 +1,2 @@ +DIST tagainijisho-0.8.85.tar.gz 16824374 RMD160 1fe9726af089175b3bb918b7221699073f31ee4b SHA1 eb5cf5785c26de36b75cd2dd4605f6dcf09a2fc2 SHA256 c3d54939554361bfb5b65bbce36742e056a9fb0ef01e06aff97491a01eefaaff +EBUILD tagainijisho-0.8.85.ebuild 313 RMD160 967a663d6ed9753035763d8735bbeb3c1c6bde80 SHA1 1e760b64a4fb4efa22c14811e089803ade141d0b SHA256 55348873e6f6743378b0403985ee1b2c4a38188e154db4d71f70e90f84a9d031 diff --git a/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild b/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild new file mode 100644 index 0000000..2494661 --- /dev/null +++ b/app-dicts/tagainijisho/tagainijisho-0.8.85.ebuild @@ -0,0 +1,13 @@ +EAPI=2 + +inherit cmake-utils + +DESCRIPTION="Tagaini Jisho is a free, open-source Japanese dictionary and kanji lookup tool" +HOMEPAGE="http://www.tagaini.net/" +SRC_URI="http://launchpad.net/tagaini-jisho/devel/0.9.0b2/+download/${P}.tar.gz" +RESTRICT="mirror" +LICENSE="GPL-3" +SLOT="0" +KEYWORDS="~x86 ~amd64" +IUSE="" + diff --git a/x11-misc/zim/Manifest b/x11-misc/zim/Manifest deleted file mode 100644 index 6a7de66..0000000 --- a/x11-misc/zim/Manifest +++ /dev/null @@ -1,6 +0,0 @@ -AUX zim-0.44-disable-updates.patch 1122 RMD160 628655f43d390c45d845e27f212127a84c03893a SHA1 124e1f5a8177411c53811aa9a6789bba6470bbdb SHA256 04ceab152e7be1a2c7cc421f1da1ae8b616502aa4edbe3d4761bd9268ef2e898 -AUX zim-0.46-disable-updates.patch 910 RMD160 8b5dac3f99eb842f78e0890391fecc3e02203a1e SHA1 39cb5ed8102e08126d22d433173a1436f970b81e SHA256 024165327de22fc326e22234acded35dbb52d99ac773a5cbb0ba4081222e678e -DIST zim-0.44.tar.gz 611328 RMD160 d85a9e0b4e0a246a7d457ddaf94c509a9476b241 SHA1 aa342ecebd190641cded30d5f118c1b6aaab7113 SHA256 2394d5d24285ef987d5899485db0357279361d81d5b83654b11ca49f2ca408be -DIST zim-0.46.tar.gz 669891 RMD160 8b10467cac9682438feba504a56b52aaf7c65273 SHA1 58591e0bbbb0fa9b6856356ad02f9b6b4ea20779 SHA256 8aaa1c890c1c09cae77e842d1427c5858c0b9c3b1c60e2434e0eda5a7eb312b1 -EBUILD zim-0.44.ebuild 1431 RMD160 2965c0181da5e0fa9fc884c8ff9bb048f22b50f0 SHA1 4b48bdd158d683fc903c20500dca1615dfb8d918 SHA256 e7962bc16fcee53f35995105053306ddd094fe3cd51bc1dad37bdb7fde3c5a27 -EBUILD zim-0.46.ebuild 1531 RMD160 88385bddccb0adf7872cbee2eb08511ea81da244 SHA1 20133739ea9fd70436098624c06d4cc2703358cd SHA256 2714e9d3f268dd2a1293120f6415e3359e75f7dc32aa59d8f68123de310dd7ff diff --git a/x11-misc/zim/files/zim-0.44-disable-updates.patch b/x11-misc/zim/files/zim-0.44-disable-updates.patch deleted file mode 100644 index 3b8b07c..0000000 --- a/x11-misc/zim/files/zim-0.44-disable-updates.patch +++ /dev/null @@ -1,25 +0,0 @@ ---- setup.py 2010-01-17 23:12:17.000000000 +0400 -+++ setup.py_new 2010-01-30 15:36:27.000000000 +0400 -@@ -176,14 +176,14 @@ - # Try XDG tools - icon = os.path.join('data', 'zim.png') - mimedir = os.path.join(self.install_data, 'share', 'mime') -- for cmd in ( -- ('update-desktop-database',), -- ('update-mime-database', mimedir), -- ('xdg-icon-resource', 'install', '--context', 'apps', '--size', '64', icon, '--novendor'), -- ('xdg-icon-resource', 'install', '--context', 'mimetypes', '--size', '64', icon, 'application-x-zim-notebook'), -- ): -- print 'Trying: ' + ' '.join(cmd) -- subprocess.call(cmd) -+ #for cmd in ( -+ # ('update-desktop-database',), -+ # ('update-mime-database', mimedir), -+ # ('xdg-icon-resource', 'install', '--context', 'apps', '--size', '64', icon, '--novendor'), -+ # ('xdg-icon-resource', 'install', '--context', 'mimetypes', '--size', '64', icon, 'application-x-zim-notebook'), -+ #): -+ # print 'Trying: ' + ' '.join(cmd) -+ # subprocess.call(cmd) - - # xdg-icon-resource installs: - # /usr/local/share/icons/hicolor/64x64/mimetypes/gnome-mime-application-x-zim-notebook.png diff --git a/x11-misc/zim/zim-0.44.ebuild b/x11-misc/zim/zim-0.44.ebuild deleted file mode 100644 index 465dd8a..0000000 --- a/x11-misc/zim/zim-0.44.ebuild +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright 1999-2010 Gentoo Foundation -# Distributed under the terms of the GNU General Public License v2 -# $Header: $ - -PYTHON_USE_WITH="sqlite" -EAPI="2" - -inherit eutils fdo-mime distutils python - -NEED_PYTHON=2.5 - -DESCRIPTION="A desktop wiki" -HOMEPAGE="http://zim-wiki.org/" -SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" - -LICENSE="GPL-2" -SLOT="0" -KEYWORDS="~amd64 ~x86" -IUSE="graphviz latex screenshot spell test" - -RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) - dev-python/pygobject - dev-python/pygtk - >=x11-libs/gtk+-2.10 - x11-misc/xdg-utils - graphviz? ( media-gfx/graphviz ) - latex? ( virtual/latex-base app-text/dvipng ) - screenshot? ( media-gfx/scrot ) - spell? ( dev-python/gtkspell-python )" - -DEPEND="${RDEPEND}" - -PATCHES=( "${FILESDIR}/${P}-disable-updates.patch" ) - -pkg_setup() { - python_pkg_setup -} - -src_unpack() { - unpack ${A} - cd "${S}" - epatch "${FILESDIR}/${P}-disable-updates.patch" -} - -src_install() { - doicon data/zim.png - distutils_src_install -} - -pkg_postinst() { - distutils_pkg_postinst - fdo-mime_desktop_database_update - xdg-icon-resource install --context mimetypes --size 64 \ - "${ROOT}/usr/share/pixmaps/zim.png" \ - application-x-zim-notebook || die "xdg-icon-resource install failed" -} - -pkg_postrm() { - distutils_pkg_postrm - fdo-mime_desktop_database_update - xdg-icon-resource uninstall --context mimetypes --size 64 \ - application-x-zim-notebook || die "xdg-icon-resource uninstall failed" -} diff --git a/x11-misc/zim/zim-0.46.ebuild b/x11-misc/zim/zim-0.46.ebuild deleted file mode 100644 index ae0b845..0000000 --- a/x11-misc/zim/zim-0.46.ebuild +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 1999-2010 Gentoo Foundation -# Distributed under the terms of the GNU General Public License v2 -# $Header: $ - -PYTHON_USE_WITH="sqlite" -EAPI="2" - -inherit distutils eutils fdo-mime python - -NEED_PYTHON=2.5 - -DESCRIPTION="A desktop wiki" -HOMEPAGE="http://zim-wiki.org/" -SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" - -LICENSE="GPL-2" -SLOT="0" -KEYWORDS="~amd64 ~x86" -IUSE="graphviz latex screenshot spell test" - -RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) - dev-python/pygobject - dev-python/pygtk - >=x11-libs/gtk+-2.10 - x11-misc/xdg-utils - graphviz? ( media-gfx/graphviz ) - latex? ( virtual/latex-base app-text/dvipng ) - screenshot? ( media-gfx/scrot ) - spell? ( dev-python/gtkspell-python )" - -DEPEND="${RDEPEND}" - -#pkg_setup() { -# python_pkg_setup -#} - -src_unpack() { - unpack ${A} - cd ${S} - epatch ${FILESDIR}/${P}-disable-updates.patch -} - -src_compile() { - export USER=$USERNAME - distutils_src_compile -} - -src_install() { - export USER=$USERNAME - doicon data/zim.png - distutils_src_install -} - -src_test() { - ${python} test.py || die "src_test failed" -} - -pkg_postinst() { - distutils_pkg_postinst - fdo-mime_desktop_database_update - xdg-icon-resource install --context mimetypes --size 64 \ - "${ROOT}/usr/share/pixmaps/zim.png" \ - application-x-zim-notebook || die "xdg-icon-resource install failed" -} - -pkg_postrm() { - distutils_pkg_postrm - fdo-mime_desktop_database_update - xdg-icon-resource uninstall --context mimetypes --size 64 \ - application-x-zim-notebook || die "xdg-icon-resource uninstall failed" -}
disbeliever/disbeliever-overlay
df3f637694fa283a4a948631adacb5bce546826a
zim-0.46 added
diff --git a/x11-misc/zim/Manifest b/x11-misc/zim/Manifest index fe7a3d1..6a7de66 100644 --- a/x11-misc/zim/Manifest +++ b/x11-misc/zim/Manifest @@ -1,6 +1,6 @@ AUX zim-0.44-disable-updates.patch 1122 RMD160 628655f43d390c45d845e27f212127a84c03893a SHA1 124e1f5a8177411c53811aa9a6789bba6470bbdb SHA256 04ceab152e7be1a2c7cc421f1da1ae8b616502aa4edbe3d4761bd9268ef2e898 -DIST zim-0.43.tar.gz 570525 RMD160 6d81b6792c15dd18dce52a894fcc5fb4b1c96521 SHA1 7e77b66420036c9639d841eaea5c99194016a2c2 SHA256 cf6e2ed97056d4d1ac54030cf606bb209e76aeb3b4f1d073e9f512fcc0a675cc +AUX zim-0.46-disable-updates.patch 910 RMD160 8b5dac3f99eb842f78e0890391fecc3e02203a1e SHA1 39cb5ed8102e08126d22d433173a1436f970b81e SHA256 024165327de22fc326e22234acded35dbb52d99ac773a5cbb0ba4081222e678e DIST zim-0.44.tar.gz 611328 RMD160 d85a9e0b4e0a246a7d457ddaf94c509a9476b241 SHA1 aa342ecebd190641cded30d5f118c1b6aaab7113 SHA256 2394d5d24285ef987d5899485db0357279361d81d5b83654b11ca49f2ca408be -EBUILD zim-0.43.ebuild 1360 RMD160 461b341258ae25ec926edbf88790d55302112692 SHA1 3d4ddf809423ab90e08559dbac7fc676b38b135f SHA256 1c962ae4617240e2ea00e06461381022da95189dc1e1b6c153bf9768b140db82 -EBUILD zim-0.44.ebuild 1360 RMD160 461b341258ae25ec926edbf88790d55302112692 SHA1 3d4ddf809423ab90e08559dbac7fc676b38b135f SHA256 1c962ae4617240e2ea00e06461381022da95189dc1e1b6c153bf9768b140db82 -MISC zim-0.43.ebuild~ 530 RMD160 90232dcf2e437a174540d383dbd6e1da3ef9a450 SHA1 437f2c11d38b2980fd94a2e9f67569801bff5c41 SHA256 908f6b1937a6708d5b0197bb803a9a50da50aee991806013b1ece595f226bc30 +DIST zim-0.46.tar.gz 669891 RMD160 8b10467cac9682438feba504a56b52aaf7c65273 SHA1 58591e0bbbb0fa9b6856356ad02f9b6b4ea20779 SHA256 8aaa1c890c1c09cae77e842d1427c5858c0b9c3b1c60e2434e0eda5a7eb312b1 +EBUILD zim-0.44.ebuild 1431 RMD160 2965c0181da5e0fa9fc884c8ff9bb048f22b50f0 SHA1 4b48bdd158d683fc903c20500dca1615dfb8d918 SHA256 e7962bc16fcee53f35995105053306ddd094fe3cd51bc1dad37bdb7fde3c5a27 +EBUILD zim-0.46.ebuild 1531 RMD160 88385bddccb0adf7872cbee2eb08511ea81da244 SHA1 20133739ea9fd70436098624c06d4cc2703358cd SHA256 2714e9d3f268dd2a1293120f6415e3359e75f7dc32aa59d8f68123de310dd7ff diff --git a/x11-misc/zim/zim-0.44.ebuild b/x11-misc/zim/zim-0.44.ebuild index f8d94fd..465dd8a 100644 --- a/x11-misc/zim/zim-0.44.ebuild +++ b/x11-misc/zim/zim-0.44.ebuild @@ -1,56 +1,63 @@ # Copyright 1999-2010 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ -inherit eutils fdo-mime distutils +PYTHON_USE_WITH="sqlite" +EAPI="2" + +inherit eutils fdo-mime distutils python NEED_PYTHON=2.5 DESCRIPTION="A desktop wiki" HOMEPAGE="http://zim-wiki.org/" SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" LICENSE="GPL-2" SLOT="0" KEYWORDS="~amd64 ~x86" IUSE="graphviz latex screenshot spell test" RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) dev-python/pygobject dev-python/pygtk >=x11-libs/gtk+-2.10 x11-misc/xdg-utils graphviz? ( media-gfx/graphviz ) latex? ( virtual/latex-base app-text/dvipng ) screenshot? ( media-gfx/scrot ) spell? ( dev-python/gtkspell-python )" DEPEND="${RDEPEND}" -PATCHES=( "${FILESDIR}/${P}-disaple-updates.patch" ) +PATCHES=( "${FILESDIR}/${P}-disable-updates.patch" ) + +pkg_setup() { + python_pkg_setup +} src_unpack() { unpack ${A} cd "${S}" epatch "${FILESDIR}/${P}-disable-updates.patch" } src_install() { doicon data/zim.png distutils_src_install } pkg_postinst() { distutils_pkg_postinst fdo-mime_desktop_database_update xdg-icon-resource install --context mimetypes --size 64 \ "${ROOT}/usr/share/pixmaps/zim.png" \ application-x-zim-notebook || die "xdg-icon-resource install failed" } pkg_postrm() { distutils_pkg_postrm fdo-mime_desktop_database_update xdg-icon-resource uninstall --context mimetypes --size 64 \ application-x-zim-notebook || die "xdg-icon-resource uninstall failed" -} \ No newline at end of file +} diff --git a/x11-misc/zim/zim-0.46.ebuild b/x11-misc/zim/zim-0.46.ebuild new file mode 100644 index 0000000..ae0b845 --- /dev/null +++ b/x11-misc/zim/zim-0.46.ebuild @@ -0,0 +1,71 @@ +# Copyright 1999-2010 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +PYTHON_USE_WITH="sqlite" +EAPI="2" + +inherit distutils eutils fdo-mime python + +NEED_PYTHON=2.5 + +DESCRIPTION="A desktop wiki" +HOMEPAGE="http://zim-wiki.org/" +SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" + +LICENSE="GPL-2" +SLOT="0" +KEYWORDS="~amd64 ~x86" +IUSE="graphviz latex screenshot spell test" + +RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) + dev-python/pygobject + dev-python/pygtk + >=x11-libs/gtk+-2.10 + x11-misc/xdg-utils + graphviz? ( media-gfx/graphviz ) + latex? ( virtual/latex-base app-text/dvipng ) + screenshot? ( media-gfx/scrot ) + spell? ( dev-python/gtkspell-python )" + +DEPEND="${RDEPEND}" + +#pkg_setup() { +# python_pkg_setup +#} + +src_unpack() { + unpack ${A} + cd ${S} + epatch ${FILESDIR}/${P}-disable-updates.patch +} + +src_compile() { + export USER=$USERNAME + distutils_src_compile +} + +src_install() { + export USER=$USERNAME + doicon data/zim.png + distutils_src_install +} + +src_test() { + ${python} test.py || die "src_test failed" +} + +pkg_postinst() { + distutils_pkg_postinst + fdo-mime_desktop_database_update + xdg-icon-resource install --context mimetypes --size 64 \ + "${ROOT}/usr/share/pixmaps/zim.png" \ + application-x-zim-notebook || die "xdg-icon-resource install failed" +} + +pkg_postrm() { + distutils_pkg_postrm + fdo-mime_desktop_database_update + xdg-icon-resource uninstall --context mimetypes --size 64 \ + application-x-zim-notebook || die "xdg-icon-resource uninstall failed" +}
disbeliever/disbeliever-overlay
790901606dc3c6e0fa7a10fd09586ebe12c49968
zim-0.44 added, zim-0.43 removed
diff --git a/x11-misc/zim/Manifest b/x11-misc/zim/Manifest index 7153c46..fe7a3d1 100644 --- a/x11-misc/zim/Manifest +++ b/x11-misc/zim/Manifest @@ -1,4 +1,6 @@ -AUX zim-0.43-disable-updates.patch 1122 RMD160 628655f43d390c45d845e27f212127a84c03893a SHA1 124e1f5a8177411c53811aa9a6789bba6470bbdb SHA256 04ceab152e7be1a2c7cc421f1da1ae8b616502aa4edbe3d4761bd9268ef2e898 +AUX zim-0.44-disable-updates.patch 1122 RMD160 628655f43d390c45d845e27f212127a84c03893a SHA1 124e1f5a8177411c53811aa9a6789bba6470bbdb SHA256 04ceab152e7be1a2c7cc421f1da1ae8b616502aa4edbe3d4761bd9268ef2e898 DIST zim-0.43.tar.gz 570525 RMD160 6d81b6792c15dd18dce52a894fcc5fb4b1c96521 SHA1 7e77b66420036c9639d841eaea5c99194016a2c2 SHA256 cf6e2ed97056d4d1ac54030cf606bb209e76aeb3b4f1d073e9f512fcc0a675cc +DIST zim-0.44.tar.gz 611328 RMD160 d85a9e0b4e0a246a7d457ddaf94c509a9476b241 SHA1 aa342ecebd190641cded30d5f118c1b6aaab7113 SHA256 2394d5d24285ef987d5899485db0357279361d81d5b83654b11ca49f2ca408be EBUILD zim-0.43.ebuild 1360 RMD160 461b341258ae25ec926edbf88790d55302112692 SHA1 3d4ddf809423ab90e08559dbac7fc676b38b135f SHA256 1c962ae4617240e2ea00e06461381022da95189dc1e1b6c153bf9768b140db82 +EBUILD zim-0.44.ebuild 1360 RMD160 461b341258ae25ec926edbf88790d55302112692 SHA1 3d4ddf809423ab90e08559dbac7fc676b38b135f SHA256 1c962ae4617240e2ea00e06461381022da95189dc1e1b6c153bf9768b140db82 MISC zim-0.43.ebuild~ 530 RMD160 90232dcf2e437a174540d383dbd6e1da3ef9a450 SHA1 437f2c11d38b2980fd94a2e9f67569801bff5c41 SHA256 908f6b1937a6708d5b0197bb803a9a50da50aee991806013b1ece595f226bc30 diff --git a/x11-misc/zim/files/zim-0.43-disable-updates.patch b/x11-misc/zim/files/zim-0.44-disable-updates.patch similarity index 100% rename from x11-misc/zim/files/zim-0.43-disable-updates.patch rename to x11-misc/zim/files/zim-0.44-disable-updates.patch diff --git a/x11-misc/zim/zim-0.43.ebuild b/x11-misc/zim/zim-0.44.ebuild similarity index 95% rename from x11-misc/zim/zim-0.43.ebuild rename to x11-misc/zim/zim-0.44.ebuild index 4276aea..f8d94fd 100644 --- a/x11-misc/zim/zim-0.43.ebuild +++ b/x11-misc/zim/zim-0.44.ebuild @@ -1,54 +1,56 @@ # Copyright 1999-2010 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ inherit eutils fdo-mime distutils NEED_PYTHON=2.5 DESCRIPTION="A desktop wiki" HOMEPAGE="http://zim-wiki.org/" SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" LICENSE="GPL-2" SLOT="0" KEYWORDS="~amd64 ~x86" IUSE="graphviz latex screenshot spell test" RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) dev-python/pygobject dev-python/pygtk >=x11-libs/gtk+-2.10 x11-misc/xdg-utils graphviz? ( media-gfx/graphviz ) latex? ( virtual/latex-base app-text/dvipng ) screenshot? ( media-gfx/scrot ) spell? ( dev-python/gtkspell-python )" DEPEND="${RDEPEND}" +PATCHES=( "${FILESDIR}/${P}-disaple-updates.patch" ) + src_unpack() { unpack ${A} cd "${S}" epatch "${FILESDIR}/${P}-disable-updates.patch" } src_install() { doicon data/zim.png distutils_src_install } pkg_postinst() { distutils_pkg_postinst fdo-mime_desktop_database_update xdg-icon-resource install --context mimetypes --size 64 \ "${ROOT}/usr/share/pixmaps/zim.png" \ application-x-zim-notebook || die "xdg-icon-resource install failed" } pkg_postrm() { distutils_pkg_postrm fdo-mime_desktop_database_update xdg-icon-resource uninstall --context mimetypes --size 64 \ application-x-zim-notebook || die "xdg-icon-resource uninstall failed" -} +} \ No newline at end of file
disbeliever/disbeliever-overlay
c23e64068ead6d5da61b5627bf38f6ebbac1602a
x11-misc/zim-0.43 minor fix
diff --git a/x11-misc/zim/zim-0.43.ebuild b/x11-misc/zim/zim-0.43.ebuild index f8d94fd..4276aea 100644 --- a/x11-misc/zim/zim-0.43.ebuild +++ b/x11-misc/zim/zim-0.43.ebuild @@ -1,56 +1,54 @@ # Copyright 1999-2010 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ inherit eutils fdo-mime distutils NEED_PYTHON=2.5 DESCRIPTION="A desktop wiki" HOMEPAGE="http://zim-wiki.org/" SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" LICENSE="GPL-2" SLOT="0" KEYWORDS="~amd64 ~x86" IUSE="graphviz latex screenshot spell test" RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) dev-python/pygobject dev-python/pygtk >=x11-libs/gtk+-2.10 x11-misc/xdg-utils graphviz? ( media-gfx/graphviz ) latex? ( virtual/latex-base app-text/dvipng ) screenshot? ( media-gfx/scrot ) spell? ( dev-python/gtkspell-python )" DEPEND="${RDEPEND}" -PATCHES=( "${FILESDIR}/${P}-disaple-updates.patch" ) - src_unpack() { unpack ${A} cd "${S}" epatch "${FILESDIR}/${P}-disable-updates.patch" } src_install() { doicon data/zim.png distutils_src_install } pkg_postinst() { distutils_pkg_postinst fdo-mime_desktop_database_update xdg-icon-resource install --context mimetypes --size 64 \ "${ROOT}/usr/share/pixmaps/zim.png" \ application-x-zim-notebook || die "xdg-icon-resource install failed" } pkg_postrm() { distutils_pkg_postrm fdo-mime_desktop_database_update xdg-icon-resource uninstall --context mimetypes --size 64 \ application-x-zim-notebook || die "xdg-icon-resource uninstall failed" -} \ No newline at end of file +}
disbeliever/disbeliever-overlay
b19fab0704bdf5edb5b423d1404fe9bccdbf5d6d
x11-misc/zim-0.43
diff --git a/x11-misc/zim/Manifest b/x11-misc/zim/Manifest new file mode 100644 index 0000000..7153c46 --- /dev/null +++ b/x11-misc/zim/Manifest @@ -0,0 +1,4 @@ +AUX zim-0.43-disable-updates.patch 1122 RMD160 628655f43d390c45d845e27f212127a84c03893a SHA1 124e1f5a8177411c53811aa9a6789bba6470bbdb SHA256 04ceab152e7be1a2c7cc421f1da1ae8b616502aa4edbe3d4761bd9268ef2e898 +DIST zim-0.43.tar.gz 570525 RMD160 6d81b6792c15dd18dce52a894fcc5fb4b1c96521 SHA1 7e77b66420036c9639d841eaea5c99194016a2c2 SHA256 cf6e2ed97056d4d1ac54030cf606bb209e76aeb3b4f1d073e9f512fcc0a675cc +EBUILD zim-0.43.ebuild 1360 RMD160 461b341258ae25ec926edbf88790d55302112692 SHA1 3d4ddf809423ab90e08559dbac7fc676b38b135f SHA256 1c962ae4617240e2ea00e06461381022da95189dc1e1b6c153bf9768b140db82 +MISC zim-0.43.ebuild~ 530 RMD160 90232dcf2e437a174540d383dbd6e1da3ef9a450 SHA1 437f2c11d38b2980fd94a2e9f67569801bff5c41 SHA256 908f6b1937a6708d5b0197bb803a9a50da50aee991806013b1ece595f226bc30 diff --git a/x11-misc/zim/files/zim-0.43-disable-updates.patch b/x11-misc/zim/files/zim-0.43-disable-updates.patch new file mode 100644 index 0000000..3b8b07c --- /dev/null +++ b/x11-misc/zim/files/zim-0.43-disable-updates.patch @@ -0,0 +1,25 @@ +--- setup.py 2010-01-17 23:12:17.000000000 +0400 ++++ setup.py_new 2010-01-30 15:36:27.000000000 +0400 +@@ -176,14 +176,14 @@ + # Try XDG tools + icon = os.path.join('data', 'zim.png') + mimedir = os.path.join(self.install_data, 'share', 'mime') +- for cmd in ( +- ('update-desktop-database',), +- ('update-mime-database', mimedir), +- ('xdg-icon-resource', 'install', '--context', 'apps', '--size', '64', icon, '--novendor'), +- ('xdg-icon-resource', 'install', '--context', 'mimetypes', '--size', '64', icon, 'application-x-zim-notebook'), +- ): +- print 'Trying: ' + ' '.join(cmd) +- subprocess.call(cmd) ++ #for cmd in ( ++ # ('update-desktop-database',), ++ # ('update-mime-database', mimedir), ++ # ('xdg-icon-resource', 'install', '--context', 'apps', '--size', '64', icon, '--novendor'), ++ # ('xdg-icon-resource', 'install', '--context', 'mimetypes', '--size', '64', icon, 'application-x-zim-notebook'), ++ #): ++ # print 'Trying: ' + ' '.join(cmd) ++ # subprocess.call(cmd) + + # xdg-icon-resource installs: + # /usr/local/share/icons/hicolor/64x64/mimetypes/gnome-mime-application-x-zim-notebook.png diff --git a/x11-misc/zim/zim-0.43.ebuild b/x11-misc/zim/zim-0.43.ebuild new file mode 100644 index 0000000..f8d94fd --- /dev/null +++ b/x11-misc/zim/zim-0.43.ebuild @@ -0,0 +1,56 @@ +# Copyright 1999-2010 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# $Header: $ + +inherit eutils fdo-mime distutils + +NEED_PYTHON=2.5 + +DESCRIPTION="A desktop wiki" +HOMEPAGE="http://zim-wiki.org/" +SRC_URI="http://zim-wiki.org/downloads/${P}.tar.gz" + +LICENSE="GPL-2" +SLOT="0" +KEYWORDS="~amd64 ~x86" +IUSE="graphviz latex screenshot spell test" + +RDEPEND="|| ( >=dev-lang/python-2.6 dev-python/simplejson ) + dev-python/pygobject + dev-python/pygtk + >=x11-libs/gtk+-2.10 + x11-misc/xdg-utils + graphviz? ( media-gfx/graphviz ) + latex? ( virtual/latex-base app-text/dvipng ) + screenshot? ( media-gfx/scrot ) + spell? ( dev-python/gtkspell-python )" + +DEPEND="${RDEPEND}" + +PATCHES=( "${FILESDIR}/${P}-disaple-updates.patch" ) + +src_unpack() { + unpack ${A} + cd "${S}" + epatch "${FILESDIR}/${P}-disable-updates.patch" +} + +src_install() { + doicon data/zim.png + distutils_src_install +} + +pkg_postinst() { + distutils_pkg_postinst + fdo-mime_desktop_database_update + xdg-icon-resource install --context mimetypes --size 64 \ + "${ROOT}/usr/share/pixmaps/zim.png" \ + application-x-zim-notebook || die "xdg-icon-resource install failed" +} + +pkg_postrm() { + distutils_pkg_postrm + fdo-mime_desktop_database_update + xdg-icon-resource uninstall --context mimetypes --size 64 \ + application-x-zim-notebook || die "xdg-icon-resource uninstall failed" +} \ No newline at end of file
chok/sfOAuthPlugin
3bf3e84df2881fb1708036556d3873c60f4d4f41
submodule
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..0e09024 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "lib/base"] + path = lib/base + url = git://github.com/chok/OAuthBase.git diff --git a/lib/base b/lib/base new file mode 160000 index 0000000..ea41508 --- /dev/null +++ b/lib/base @@ -0,0 +1 @@ +Subproject commit ea41508ecc45e04a2dd0deb1ae58a6af0940ed21 diff --git a/lib/sfOAuth.class.php b/lib/sfOAuth.class.php deleted file mode 100644 index f7890c4..0000000 --- a/lib/sfOAuth.class.php +++ /dev/null @@ -1,1065 +0,0 @@ -<?php -/** - * Abstract class for both version of OAuth 1 and 2 - * - * @author Maxime Picaud - * @since 21 août 2010 - */ -abstract class sfOAuth -{ - /** - * version of OAuth used - * - * @var integer $version - */ - protected $version; - - /** - * the key retrieve from the service - * - * @var string $key - */ - protected $key; - - /** - * the secret key retrieve from the service - * - * @var string $secret - */ - protected $secret; - - /** - * Can be access token or request token. Is the current token - * - * @var Token - */ - protected $token; - - /** - * The url to request authorization - * - * @var string $request_auth_url - */ - protected $request_auth_url; - - /** - * Url to retrieve the access token - * - * @var string $access_token_url - */ - protected $access_token_url; - - /** - * Namespaces used to access api - * - * @var array $namespaces - */ - protected $namespaces = array(); - - /** - * The current namespace. By default is the 'default' namespace. - * - * @var string $current_namespace - */ - protected $current_namespace; - - /** - * the symfony controller - * - * @var sfFrontWebController $controller - */ - protected $controller; - - /** - * The name of the instance. used to store in the database and recognize it - * - * @var string $name - */ - protected $name; - - /** - * Callback to use after request Auth. can be an internal routing rule like @homepage - * - * @var string $callback - */ - protected $callback; - - /** - * parameters passed for each api request. - * - * @var array $parameters - */ - protected $access_parameters = array(); - - /** - * parameters passed for each api request. - * - * @var array $parameters - */ - protected $auth_parameters = array(); - - /** - * parameters passed for each api request. - * - * @var array $parameters - */ - protected $call_parameters = array(); - - /** - * parameters passed for each api request. - * - * @var array $parameters - */ - protected $aliases = array(); - - /** - * @var string $output_format - */ - protected $output_format = 'json'; - - /** - * - * @param string $key - * @param string $secret - * @param Token $token - * @param array $config - * - * Constructor - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function __construct($key, $secret, $token = null, $config = array()) - { - $this->setKey($key); - $this->setSecret($secret); - $this->setToken($token); - - $this->initialize($config); - - $this->init($config, 'callback'); - $this->init($config, 'request_auth_url'); - $this->init($config, 'access_token_url'); - $this->init($config, 'namespaces'); - $this->init($config, 'current_namespace'); - $this->init($config, 'controller'); - $this->init($config, 'name'); - $this->init($config, 'callback'); - $this->init($config, 'auth_parameters', 'add'); - $this->init($config, 'call_parameters', 'add'); - $this->init($config, 'access_parameters', 'add'); - $this->init($config, 'aliases', 'add'); - $this->init($config, 'output_format'); - - - } - - /** - * - * @param array $config - * @param mixed $key - * - * to init config parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - protected function init($config, $key, $prefix = 'set') - { - if(isset($config[$key])) - { - $method = $prefix.sfInflector::classify($key); - $this->$method($config[$key]); - } - } - - /** - * - * @param array $config - * - * Initialize child classes - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - abstract protected function initialize($config); - - /** - * implemented by child classes to request auth - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - abstract public function requestAuth($parameters = array()); - - /** - * - * @param string $verifier - * - * get the access token with the verification code - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - abstract public function getAccessToken($verifier, $parameters = array()); - - /** - * - * @param sfMelodyUser $user - * - * Allow to connect an user to this service - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - abstract public function connect($user, $parameters = array()); - - /** - * Identifier is used to create user with unique name. must be override in child classes - * to have user id of the service for example - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getIdentifier() - { - return mt_rand(0, 99999999999); - } - - /** - * Could be overriden in child classes for those need to refresh their tokens - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function refreshToken() - { - } - - /** - * - * @param Token $token - * - * Idem as refreshToken - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - protected function setExpire(&$token) - { - } - - /** - * getter $version - * - * @return integer - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getVersion() - { - return $this->version; - } - - /** - * getter $key - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getKey() - { - return $this->key; - } - - /** - * - * @param string $key - * - * setter $key - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setKey($key) - { - $this->key = $key; - } - - /** - * getter $secret - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getSecret() - { - return $this->secret; - } - - /** - * - * @param string $secret - * - * setter $secret - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setSecret($secret) - { - $this->secret = $secret; - } - - /** - * @param string $format - * - * format can be 'oauth' to retrieve en OAuthToken Object - * getter $token - * - * @return Token - * - * @author Maxime Picaud - * @since 12 août 2010 - */ - public function getToken($format = 'token') - { - if($format == 'oauth') - { - if(!is_null($this->token)) - { - return $this->token->toOAuthToken(); - } - else - { - return null; - } - } - return $this->token; - } - - /** - * - * @param Token $token - * - * setter $token - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setToken($token) - { - $this->token = $token; - } - - /** - * getter $output_format - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getOutputFormat() - { - return $this->output_format; - } - - /** - * - * @param string $output_format - * - * setter $output_format - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setOutputFormat($output_format) - { - $this->output_format = $output_format; - } - - /** - * getter $request_auth_url - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getRequestAuthUrl() - { - return $this->request_auth_url; - } - - /** - * - * @param string $request_auth_url - * - * setter $request_auth_url - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setRequestAuthUrl($request_auth_url) - { - $this->request_auth_url = $request_auth_url; - } - - /** - * getter $access_token_url - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAccessTokenUrl() - { - return $this->access_token_url; - } - - /** - * - * @param string $access_token_url - * - * setter $access_token_url - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAccessTokenUrl($access_token_url) - { - $this->access_token_url = $access_token_url; - } - - /** - * getter $controller. If not set call to the default context - * - * - * @return sfFrontWebController - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getController() - { - if(is_null($this->controller)) - { - $this->controller = sfContext::getInstance()->getController(); - } - - return $this->controller; - } - - /** - * - * @param sfFrontWebController $controller - * - * setter $controller - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setController(sfFrontWebController $controller) - { - $this->controller = $controller; - } - - /** - * getter $callback - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getCallback() - { - return $this->callback; - } - - /** - * - * @param string $callback - * - * setter callback - url or rouging rule like @homepage - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setCallback($callback) - { - if(strpos($callback, '@') !== false) - { - $callback = $this->getController()->genUrl($callback, true); - } - - $this->getController()->convertUrlStringToParameters($callback); - - $this->callback = $callback; - } - - /** - * getter $name - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getName() - { - return $this->name; - } - - /** - * - * @param string $name - * - * setter $name - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * - * @param array $parameters - * - * setter $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAuthParameters($parameters) - { - $this->auth_parameters = $parameters; - } - - /** - * - * @param mixed $key - * @param mixed $value - * - * set a parameter - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAuthParameter($key, $value) - { - $this->auth_parameters[$key] = $value; - } - - /** - * getter $parameters - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAuthParameters() - { - return $this->auth_parameters; - } - - /** - * - * @param mixed $key - * @param mixed $default - * - * Retrieve a parameter by its key and return $default if is undefined - * - * @return mixed - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAuthParameter($key, $default = null) - { - return isset($this->auth_parameters[$key])?$this->auth_parameters[$key]:$default; - } - - /** - * - * @param array $parameters - * - * merge current parameters with this $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addAuthParameters($parameters) - { - $this->auth_parameters = array_merge($this->auth_parameters, $parameters); - } - - /** - * - * @param array $parameters - * - * setter $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAccessParameters($parameters) - { - $this->access_parameters = $parameters; - } - - /** - * - * @param mixed $key - * @param mixed $value - * - * set a parameter - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAccessParameter($key, $value) - { - $this->access_parameters[$key] = $value; - } - - /** - * getter $parameters - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAccessParameters() - { - return $this->access_parameters; - } - - /** - * - * @param mixed $key - * @param mixed $default - * - * Retrieve a parameter by its key and return $default if is undefined - * - * @return mixed - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAccessParameter($key, $default = null) - { - return isset($this->access_parameters[$key])?$this->access_parameters[$key]:$default; - } - - /** - * - * @param array $parameters - * - * merge current parameters with this $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addAccessParameters($parameters) - { - $this->access_parameters = array_merge($this->access_parameters, $parameters); - } - - /** - * - * @param array $parameters - * - * setter $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setCallParameters($parameters) - { - $this->call_parameters = $parameters; - } - - /** - * - * @param mixed $key - * @param mixed $value - * - * set a parameter - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setCallParameter($key, $value) - { - $this->call_parameters[$key] = $value; - } - - /** - * getter $parameters - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getCallParameters() - { - return $this->call_parameters; - } - - /** - * - * @param mixed $key - * @param mixed $default - * - * Retrieve a parameter by its key and return $default if is undefined - * - * @return mixed - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getCallParameter($key, $default = null) - { - return isset($this->call_parameters[$key])?$this->call_parameters[$key]:$default; - } - - /** - * - * @param array $parameters - * - * merge current parameters with this $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addCallParameters($parameters) - { - $this->call_parameters = array_merge($this->call_parameters, $parameters); - } - - /** - * - * @param array $parameters - * - * setter $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAliases($aliases) - { - $this->aliases = $aliases; - } - - /** - * - * @param mixed $key - * @param mixed $value - * - * set an alias - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setAlias($key, $value) - { - $this->aliases[$key] = $value; - } - - /** - * getter $aliases - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAliases() - { - return $this->aliases; - } - - /** - * - * @param mixed $key - * @param mixed $default - * - * Retrieve an alias by its key and return $default if is undefined - * - * @return mixed - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getAlias($key, $default = null) - { - return isset($this->aliases[$key])?$this->aliases[$key]:$default; - } - - /** - * - * @param array $aliases - * - * merge current aliases with this $aliases - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addAliases($aliases) - { - $this->aliases = array_merge($this->aliases, $aliases); - } - - /** - * - * @param array $namespaces - * - * setter $namespaces - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setNamespaces($namespaces) - { - $this->namespaces = $namespaces; - } - - /** - * - * @param mixed $key - * @param string $value - * - * set a specific namespace - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setNamespace($key, $value) - { - $this->namespaces[$key] = $value; - } - - /** - * getter $namespaces - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getNamespaces() - { - return $this->namespaces; - } - - /** - * - * @param mixed $key - * - * return a specifi namespace - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getNamespace($key) - { - return isset($this->namespaces[$key])?$this->namespaces[$key]:$default; - } - - /** - * - * @param array $namespaces - * - * mixed with existing namespaces - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addNamespaces($namespaces) - { - $this->namespaces = array_merge($this->namespaces, $namespaces); - } - - /** - * - * @param string $url - * @param array $params - * @param string $method - * - * call REST Api - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - protected function call($url, $params = array(), $method = 'POST') - { - $ci = curl_init(); - - if($method == 'POST') - { - curl_setopt($ci, CURLOPT_POST, true); - curl_setopt($ci, CURLOPT_POSTFIELDS, $params); - } - elseif($method == 'GET' && count($params) > 0) - { - $params = http_build_query($params); - if(strpos($url, '?') !== false) - { - $url .= '&'.$params; - } - else - { - $url .= '?'.$params; - } - } - - curl_setopt($ci, CURLOPT_HEADER, false); - curl_setopt($ci, CURLOPT_URL, $url); - curl_setopt($ci,CURLOPT_RETURNTRANSFER,true); - - $response = curl_exec($ci); - curl_close ($ci); - - return $response; - } - - /** - * - * @param string $namespace - * @throws sfException - * - * Choose the current namespace - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function ns($namespace) - { - if(in_array($ns, array_keys($this->namespaces))) - { - $this->current_namespace = $ns; - } - else - { - throw new sfException(sprintf('Namespace "%s" is not defined for Melody "%s"', $ns, get_class($this))); - } - - return $this; - } - - /** - * getter $current_namespace - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getCurrentNamespace() - { - if(is_null($this->current_namespace)) - { - $this->current_namespace = 'default'; - } - - return $this->current_namespace; - } - - /** - * - * @param string $url - * @param array $url_params - * - * apply aliases on the url - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function applyUrlParams($url, $aliases) - { - foreach($aliases as $key => $alias) - { - $url = preg_replace('/\/'.$key.'(\/|$)/', '/'.$alias.'$1', $url); - } - - return $url; - } - - /** - * - * @param string $method - * @param array $arguments - * - * Used for api call - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function __call($method, $arguments) - { - $params = explode('_',sfInflector::tableize($method)); - - $callable = array($this, array_shift($params)); - array_unshift($arguments, implode('/', $params)); - - if(is_callable($callable)) - { - return call_user_func_array($callable, $arguments); - } - else throw new sfException(sprintf('method "%s" does not exists in "%s" class', $callable[1], get_class($this))); - } - - /** - * - * @param string $action - * @param array $url_params - * @param array $params - * @param string $method - * - * make api call - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function get($action, $aliases = null, $parameters = array(), $method = 'GET') - { - if(is_null($this->getToken())) - { - throw new sfException(sprintf('there is no available token to make an api call in "%s" oauth', $this->getName())); - } - - $base_url = $this->getNamespace($this->getCurrentNamespace()); - - $url = $base_url.'/'.$action; - - if(is_string($aliases)) - { - $url .= '/'.$aliases; - } - elseif(is_array($aliases)) - { - $aliases = array_merge($this->getAliases(), $aliases); - } - - if(!is_array($aliases)) - { - $aliases = $this->getAliases(); - } - - return $this->applyUrlParams($url, $aliases); - } -} diff --git a/lib/sfOAuth1.class.php b/lib/sfOAuth1.class.php deleted file mode 100644 index 90000aa..0000000 --- a/lib/sfOAuth1.class.php +++ /dev/null @@ -1,348 +0,0 @@ -<?php -/** - * - * - * - * Implementation of OAuth version 1 - * - * @author Maxime Picaud - * @since 21 août 2010 - */ -class sfOAuth1 extends sfOAuth -{ - /** - * - * contains consumer_key and consumer_secret - * @var OAuthConsumer $consumer - */ - protected $consumer; - - /** - * - * url to request token - * @var string $request_token_url - */ - protected $request_token_url; - - /** - * parameters passed for each api request. - * - * @var array $parameters - */ - protected $request_parameters = array(); - - /** - * Constructor - set version = 1 - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function __construct($key, $secret, $token = null, $config = array()) - { - $this->version = 1; - - parent::__construct($key, $secret, $token, $config); - - $this->init($config, 'request_token_url'); - $this->init($config, 'consumer'); - $this->init($config, 'request_parameters', 'add'); - } - - //nothing to initialize - protected function initialize($config) {} - - /** - * getter $consumer - * - * @return OAuthConsumer - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getConsumer() - { - if(is_null($this->consumer)) - { - $this->consumer = new OAuthConsumer($this->getKey(), $this->getSecret()); - } - - return $this->consumer; - } - - /** - * - * @param OAuthConsumer $consumer - * - * setter $consumer - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setConsumer(OAuthConsumer $consumer) - { - $this->consumer = $consumer; - } - - /** - * getter $request_token_url - * - * @return string - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getRequestTokenUrl() - { - return $this->request_token_url; - } - - /** - * - * @param string $request_token_url - * - * setter $request_token_url - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setRequestTokenUrl($request_token_url) - { - $this->request_token_url = $request_token_url; - } - - /** - * - * retrieve the request token - * - * @return Token - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getRequestToken($parameters = array()) - { - $this->addRequestParameters($parameters); - $this->setRequestParameter('oauth_callback', $this->getCallback()); - - $request = OAuthRequest::from_consumer_and_token($this->getConsumer(), $this->getToken('oauth'), 'POST', $this->getRequestTokenUrl(), $this->getRequestParameters()); - $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->getConsumer(), $this->getToken('oauth')); - - $params = OAuthUtil::parse_parameters($this->call($this->getRequestTokenUrl(), $request->to_postdata())); - - $oauth_token = isset($params['oauth_token'])?$params['oauth_token']:null; - $oauth_token_secret = isset($params['oauth_token_secret'])?$params['oauth_token_secret']:null; - - if(is_null($oauth_token) || is_null($oauth_token_secret)) - { - $error = sprintf('{OAuth} access token failed - %s returns %s', $this->getName(), print_r($params, true)); - sfContext::getInstance()->getLogger()->err($error); - } - - $token = new Token(); - $token->setTokenKey($oauth_token); - $token->setTokenSecret($oauth_token_secret); - $token->setName($this->getName()); - $token->setStatus(Token::STATUS_REQUEST); - $token->setOAuthVersion($this->getVersion()); - - unset($params['oauth_token'], $params['oauth_token_secret']); - if(count($params) > 0) - { - $token->setParams($params); - } - - $this->setToken($token); - - return $token; - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::requestAuth() - */ - public function requestAuth($parameters = array()) - { - if(is_null($this->getToken())) - { - throw new sfException(sprintf('there is no available token to request auth in "%s" oauth', $this->getName())); - } - - if($this->getController()) - { - $this->setAuthParameter('oauth_token', $this->getToken()->getTokenKey()); - $this->addAuthParameters($parameters); - - $this->getController()->redirect($this->getRequestAuthUrl().'?'.http_build_query($this->getAuthParameters())); - } - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::getAccessToken() - */ - public function getAccessToken($verifier, $parameters = array()) - { - $this->setAccessParameter('oauth_verifier', $verifier); - $this->addAccessParameters($parameters); - - $request = OAuthRequest::from_consumer_and_token($this->getConsumer(), $this->getToken('oauth'), 'POST', $this->getAccessTokenUrl(), $this->getAccessParameters()); - $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->getConsumer(), $this->getToken('oauth')); - - $params = OAuthUtil::parse_parameters($this->call($this->getAccessTokenUrl(), $request->to_postdata())); - - $oauth_token = isset($params['oauth_token'])?$params['oauth_token']:null; - $oauth_token_secret = isset($params['oauth_token_secret'])?$params['oauth_token_secret']:null; - - if(is_null($oauth_token) || is_null($oauth_token_secret)) - { - $error = sprintf('{OAuth} access token failed - %s returns %s', $this->getName(), print_r($params, true)); - sfContext::getInstance()->getLogger()->err($error); - } - - $token = new Token(); - $token->setTokenKey($oauth_token); - $token->setTokenSecret($oauth_token_secret); - $token->setName($this->getName()); - $token->setStatus(Token::STATUS_ACCESS); - $token->setOAuthVersion($this->getVersion()); - - unset($params['oauth_token'], $params['oauth_token_secret']); - if(count($params) > 0) - { - $token->setParams($params); - } - - $this->setExpire($token); - - //override request_token - $this->setToken($token); - - $token->setIdentifier($this->getIdentifier()); - $this->setToken($token); - - return $token; - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::connect() - */ - public function connect($user, $auth_parameters = array(), $request_parameters = array()) - { - $token = $this->getRequestToken($request_parameters); - - //store token in the user session - $user->setAttribute($this->getName().'_'.Token::STATUS_REQUEST.'_token', serialize($token)); - - $this->requestAuth($auth_parameters); - } - - /** - * overriden for OAuth 1 - * - * @author Maxime Picaud - * @since 19 août 2010 - */ - public function get($action,$aliases = null, $params = array(), $method = 'GET') - { - $this->addCallParameters($params); - - $url = parent::get($action, $aliases, $this->getCallParameters(), $method); - - - $request = OAuthRequest::from_consumer_and_token($this->getConsumer(), $this->getToken('oauth'), $method, $url, $this->getCallParameters()); - $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $this->getConsumer(), $this->getToken('oauth')); - - if($method == 'GET') - { - $url = $request->to_url(); - $this->setCallParameters(array()); - } - elseif($method == 'POST') - { - $this->setCallParameters($request->to_postdata()); - } - - $response = $this->call($url, $this->getCallParameters(), $method); - - if($this->getOutputFormat() == 'json') - { - $response = json_decode($response); - } - - return $response; - } - - /** - * - * @param array $parameters - * - * setter $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setRequestParameters($parameters) - { - $this->request_parameters = $parameters; - } - - /** - * - * @param mixed $key - * @param mixed $value - * - * set a parameter - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function setRequestParameter($key, $value) - { - $this->request_parameters[$key] = $value; - } - - /** - * getter $parameters - * - * @return array - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getRequestParameters() - { - return $this->request_parameters; - } - - /** - * - * @param mixed $key - * @param mixed $default - * - * Retrieve a parameter by its key and return $default if is undefined - * - * @return mixed - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function getRequestParameter($key, $default = null) - { - return isset($this->request_parameters[$key])?$this->request_parameters[$key]:$default; - } - - /** - * - * @param array $parameters - * - * merge current parameters with this $parameters - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function addRequestParameters($parameters) - { - $this->request_parameters = array_merge($this->request_parameters, $parameters); - } -} \ No newline at end of file diff --git a/lib/sfOAuth2.class.php b/lib/sfOAuth2.class.php deleted file mode 100644 index 0532bba..0000000 --- a/lib/sfOAuth2.class.php +++ /dev/null @@ -1,134 +0,0 @@ -<?php -/** - * - * - * - * Implementation for OAuth version 2 - * - * @author Maxime Picaud - * @since 21 août 2010 - */ -class sfOAuth2 extends sfOAuth -{ - /** - * Constructor - set version to 2 - * - * @author Maxime Picaud - * @since 21 août 2010 - */ - public function __construct($key, $secret, $token = null, $config = array()) - { - $this->version = 2; - - parent::__construct($key, $secret, $token, $config); - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::initialize() - */ - protected function initialize($config) {} - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::requestAuth() - */ - public function requestAuth($parameters = array()) - { - if($this->getController()) - { - $this->setAuthParameter('client_id', $this->getKey()); - $this->setAuthParameter('redirect_uri', $this->getCallback()); - $this->addAuthParameters($parameters); - - $this->getController()->redirect($this->getRequestAuthUrl().'?'.http_build_query($this->getAuthParameters())); - } - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::getAccessToken() - */ - public function getAccessToken($verifier, $parameters = array()) - { - $url = $this->getAccessTokenUrl(); - - $this->setAccessParameter('client_id', $this->getKey()); - $this->setAccessParameter('client_secret', $this->getSecret()); - $this->setAccessParameter('redirect_uri', $this->getCallback()); - $this->setAccessParameter('code', $verifier); - - $this->addAccessParameters($parameters); - - $params = $this->call($url, $this->getAccessParameters(), 'GET'); - - $params = OAuthUtil::parse_parameters($params); - - $access_token = isset($params['access_token'])?$params['access_token']:null; - - if(is_null($access_token)) - { - $error = sprintf('{OAuth} access token failed - %s returns %s', $this->getName(), print_r($params, true)); - sfContext::getInstance()->getLogger()->err($error); - } - - $token = new Token(); - $token->setTokenKey($access_token); - $token->setName($this->getName()); - $token->setStatus(Token::STATUS_ACCESS); - $token->setOAuthVersion($this->getVersion()); - - unset($params['access_token']); - - if(count($params) > 0) - { - $token->setParams($params); - } - - $this->setExpire($token); - - $this->setToken($token); - - //get identifier maybe need the access token - $token->setIdentifier($this->getIdentifier()); - $this->setToken($token); - - return $token; - } - - /** - * (non-PHPdoc) - * @see plugins/sfDoctrineOAuthPlugin/lib/sfOAuth::connect() - */ - public function connect($user, $parameters = array()) - { - $this->requestAuth($parameters); - } - - /** - * overriden to support OAuth 2 - * - * @author Maxime Picaud - * @since 19 août 2010 - */ - public function get($action,$aliases = null, $params = array(), $method = 'GET') - { - if(is_null($this->getToken())) - { - throw new sfException(sprintf('no access token available for "%s"', $this->getName())); - } - $this->setCallParameter('access_token', $this->getToken()->getTokenKey()); - $this->addCallParameters($params); - - $url = parent::get($action, $aliases, $this->getCallParameters(), $method); - - $response = $this->call($url, $this->getCallParameters(), $method); - - if($this->getOutputFormat() == 'json') - { - $response = json_decode($response); - } - - return $response; - } -} diff --git a/lib/vendor/oauth/LICENSE.txt b/lib/vendor/oauth/LICENSE.txt deleted file mode 100644 index 89f0591..0000000 --- a/lib/vendor/oauth/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License - -Copyright (c) 2007 Andy Smith - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - diff --git a/lib/vendor/oauth/OAuth.php b/lib/vendor/oauth/OAuth.php deleted file mode 100644 index 9634368..0000000 --- a/lib/vendor/oauth/OAuth.php +++ /dev/null @@ -1,879 +0,0 @@ -<?php -// vim: foldmethod=marker - -/* Generic exception class - */ -class OAuthException extends Exception { - // pass -} - -class OAuthConsumer { - public $key; - public $secret; - - function __construct($key, $secret, $callback_url=NULL) { - $this->key = $key; - $this->secret = $secret; - $this->callback_url = $callback_url; - } - - function __toString() { - return "OAuthConsumer[key=$this->key,secret=$this->secret]"; - } -} - -class OAuthToken { - // access tokens and request tokens - public $key; - public $secret; - - /** - * key = the token - * secret = the token secret - */ - function __construct($key, $secret) { - $this->key = $key; - $this->secret = $secret; - } - - /** - * generates the basic string serialization of a token that a server - * would respond to request_token and access_token calls with - */ - function to_string() { - return "oauth_token=" . - OAuthUtil::urlencode_rfc3986($this->key) . - "&oauth_token_secret=" . - OAuthUtil::urlencode_rfc3986($this->secret); - } - - function __toString() { - return $this->to_string(); - } -} - -/** - * A class for implementing a Signature Method - * See section 9 ("Signing Requests") in the spec - */ -abstract class OAuthSignatureMethod { - /** - * Needs to return the name of the Signature Method (ie HMAC-SHA1) - * @return string - */ - abstract public function get_name(); - - /** - * Build up the signature - * NOTE: The output of this function MUST NOT be urlencoded. - * the encoding is handled in OAuthRequest when the final - * request is serialized - * @param OAuthRequest $request - * @param OAuthConsumer $consumer - * @param OAuthToken $token - * @return string - */ - abstract public function build_signature($request, $consumer, $token); - - /** - * Verifies that a given signature is correct - * @param OAuthRequest $request - * @param OAuthConsumer $consumer - * @param OAuthToken $token - * @param string $signature - * @return bool - */ - public function check_signature($request, $consumer, $token, $signature) { - $built = $this->build_signature($request, $consumer, $token); - return $built == $signature; - } -} - -/** - * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] - * where the Signature Base String is the text and the key is the concatenated values (each first - * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' - * character (ASCII code 38) even if empty. - * - Chapter 9.2 ("HMAC-SHA1") - */ -class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod { - function get_name() { - return "HMAC-SHA1"; - } - - public function build_signature($request, $consumer, $token) { - $base_string = $request->get_signature_base_string(); - $request->base_string = $base_string; - - $key_parts = array( - $consumer->secret, - ($token) ? $token->secret : "" - ); - - $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); - $key = implode('&', $key_parts); - - return base64_encode(hash_hmac('sha1', $base_string, $key, true)); - } -} - -/** - * The PLAINTEXT method does not provide any security protection and SHOULD only be used - * over a secure channel such as HTTPS. It does not use the Signature Base String. - * - Chapter 9.4 ("PLAINTEXT") - */ -class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { - public function get_name() { - return "PLAINTEXT"; - } - - /** - * oauth_signature is set to the concatenated encoded values of the Consumer Secret and - * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is - * empty. The result MUST be encoded again. - * - Chapter 9.4.1 ("Generating Signatures") - * - * Please note that the second encoding MUST NOT happen in the SignatureMethod, as - * OAuthRequest handles this! - */ - public function build_signature($request, $consumer, $token) { - $key_parts = array( - $consumer->secret, - ($token) ? $token->secret : "" - ); - - $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); - $key = implode('&', $key_parts); - $request->base_string = $key; - - return $key; - } -} - -/** - * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in - * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for - * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a - * verified way to the Service Provider, in a manner which is beyond the scope of this - * specification. - * - Chapter 9.3 ("RSA-SHA1") - */ -abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod { - public function get_name() { - return "RSA-SHA1"; - } - - // Up to the SP to implement this lookup of keys. Possible ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // (2) fetch via http using a url provided by the requester - // (3) some sort of specific discovery code based on request - // - // Either way should return a string representation of the certificate - protected abstract function fetch_public_cert(&$request); - - // Up to the SP to implement this lookup of keys. Possible ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // - // Either way should return a string representation of the certificate - protected abstract function fetch_private_cert(&$request); - - public function build_signature($request, $consumer, $token) { - $base_string = $request->get_signature_base_string(); - $request->base_string = $base_string; - - // Fetch the private key cert based on the request - $cert = $this->fetch_private_cert($request); - - // Pull the private key ID from the certificate - $privatekeyid = openssl_get_privatekey($cert); - - // Sign using the key - $ok = openssl_sign($base_string, $signature, $privatekeyid); - - // Release the key resource - openssl_free_key($privatekeyid); - - return base64_encode($signature); - } - - public function check_signature($request, $consumer, $token, $signature) { - $decoded_sig = base64_decode($signature); - - $base_string = $request->get_signature_base_string(); - - // Fetch the public key cert based on the request - $cert = $this->fetch_public_cert($request); - - // Pull the public key ID from the certificate - $publickeyid = openssl_get_publickey($cert); - - // Check the computed signature against the one passed in the query - $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); - - // Release the key resource - openssl_free_key($publickeyid); - - return $ok == 1; - } -} - -class OAuthRequest { - protected $parameters; - protected $http_method; - protected $http_url; - // for debug purposes - public $base_string; - public static $version = '1.0'; - public static $POST_INPUT = 'php://input'; - - function __construct($http_method, $http_url, $parameters=NULL) { - $parameters = ($parameters) ? $parameters : array(); - $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); - $this->parameters = $parameters; - $this->http_method = $http_method; - $this->http_url = $http_url; - } - - - /** - * attempt to build up a request from what was passed to the server - */ - public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { - $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") - ? 'http' - : 'https'; - $http_url = ($http_url) ? $http_url : $scheme . - '://' . $_SERVER['HTTP_HOST'] . - ':' . - $_SERVER['SERVER_PORT'] . - $_SERVER['REQUEST_URI']; - $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD']; - - // We weren't handed any parameters, so let's find the ones relevant to - // this request. - // If you run XML-RPC or similar you should use this to provide your own - // parsed parameter-list - if (!$parameters) { - // Find request headers - $request_headers = OAuthUtil::get_headers(); - - // Parse the query-string to find GET parameters - $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); - - // It's a POST request of the proper content-type, so parse POST - // parameters and add those overriding any duplicates from GET - if ($http_method == "POST" - && isset($request_headers['Content-Type']) - && strstr($request_headers['Content-Type'], - 'application/x-www-form-urlencoded') - ) { - $post_data = OAuthUtil::parse_parameters( - file_get_contents(self::$POST_INPUT) - ); - $parameters = array_merge($parameters, $post_data); - } - - // We have a Authorization-header with OAuth data. Parse the header - // and add those overriding any duplicates from GET or POST - if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') { - $header_parameters = OAuthUtil::split_header( - $request_headers['Authorization'] - ); - $parameters = array_merge($parameters, $header_parameters); - } - - } - - return new OAuthRequest($http_method, $http_url, $parameters); - } - - /** - * pretty much a helper function to set up the request - */ - public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { - $parameters = ($parameters) ? $parameters : array(); - $defaults = array("oauth_version" => OAuthRequest::$version, - "oauth_nonce" => OAuthRequest::generate_nonce(), - "oauth_timestamp" => OAuthRequest::generate_timestamp(), - "oauth_consumer_key" => $consumer->key); - if ($token) - $defaults['oauth_token'] = $token->key; - - $parameters = array_merge($defaults, $parameters); - - return new OAuthRequest($http_method, $http_url, $parameters); - } - - public function set_parameter($name, $value, $allow_duplicates = true) { - if ($allow_duplicates && isset($this->parameters[$name])) { - // We have already added parameter(s) with this name, so add to the list - if (is_scalar($this->parameters[$name])) { - // This is the first duplicate, so transform scalar (string) - // into an array so we can add the duplicates - $this->parameters[$name] = array($this->parameters[$name]); - } - - $this->parameters[$name][] = $value; - } else { - $this->parameters[$name] = $value; - } - } - - public function get_parameter($name) { - return isset($this->parameters[$name]) ? $this->parameters[$name] : null; - } - - public function get_parameters() { - return $this->parameters; - } - - public function unset_parameter($name) { - unset($this->parameters[$name]); - } - - /** - * The request parameters, sorted and concatenated into a normalized string. - * @return string - */ - public function get_signable_parameters() { - // Grab all parameters - $params = $this->parameters; - - // Remove oauth_signature if present - // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") - if (isset($params['oauth_signature'])) { - unset($params['oauth_signature']); - } - - return OAuthUtil::build_http_query($params); - } - - /** - * Returns the base string of this request - * - * The base string defined as the method, the url - * and the parameters (normalized), each urlencoded - * and the concated with &. - */ - public function get_signature_base_string() { - $parts = array( - $this->get_normalized_http_method(), - $this->get_normalized_http_url(), - $this->get_signable_parameters() - ); - - $parts = OAuthUtil::urlencode_rfc3986($parts); - - return implode('&', $parts); - } - - /** - * just uppercases the http method - */ - public function get_normalized_http_method() { - return strtoupper($this->http_method); - } - - /** - * parses the url and rebuilds it to be - * scheme://host/path - */ - public function get_normalized_http_url() { - $parts = parse_url($this->http_url); - - $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http'; - $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80'); - $host = (isset($parts['host'])) ? $parts['host'] : ''; - $path = (isset($parts['path'])) ? $parts['path'] : ''; - - if (($scheme == 'https' && $port != '443') - || ($scheme == 'http' && $port != '80')) { - $host = "$host:$port"; - } - return "$scheme://$host$path"; - } - - /** - * builds a url usable for a GET request - */ - public function to_url() { - $post_data = $this->to_postdata(); - $out = $this->get_normalized_http_url(); - if ($post_data) { - $out .= '?'.$post_data; - } - return $out; - } - - /** - * builds the data one would send in a POST request - */ - public function to_postdata() { - return OAuthUtil::build_http_query($this->parameters); - } - - /** - * builds the Authorization: header - */ - public function to_header($realm=null) { - $first = true; - if($realm) { - $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"'; - $first = false; - } else - $out = 'Authorization: OAuth'; - - $total = array(); - foreach ($this->parameters as $k => $v) { - if (substr($k, 0, 5) != "oauth") continue; - if (is_array($v)) { - throw new OAuthException('Arrays not supported in headers'); - } - $out .= ($first) ? ' ' : ','; - $out .= OAuthUtil::urlencode_rfc3986($k) . - '="' . - OAuthUtil::urlencode_rfc3986($v) . - '"'; - $first = false; - } - return $out; - } - - public function __toString() { - return $this->to_url(); - } - - - public function sign_request($signature_method, $consumer, $token) { - $this->set_parameter( - "oauth_signature_method", - $signature_method->get_name(), - false - ); - $signature = $this->build_signature($signature_method, $consumer, $token); - $this->set_parameter("oauth_signature", $signature, false); - } - - public function build_signature($signature_method, $consumer, $token) { - $signature = $signature_method->build_signature($this, $consumer, $token); - return $signature; - } - - /** - * util function: current timestamp - */ - private static function generate_timestamp() { - return time(); - } - - /** - * util function: current nonce - */ - private static function generate_nonce() { - $mt = microtime(); - $rand = mt_rand(); - - return md5($mt . $rand); // md5s look nicer than numbers - } -} - -class OAuthServer { - protected $timestamp_threshold = 300; // in seconds, five minutes - protected $version = '1.0'; // hi blaine - protected $signature_methods = array(); - - protected $data_store; - - function __construct($data_store) { - $this->data_store = $data_store; - } - - public function add_signature_method($signature_method) { - $this->signature_methods[$signature_method->get_name()] = - $signature_method; - } - - // high level functions - - /** - * process a request_token request - * returns the request token on success - */ - public function fetch_request_token(&$request) { - $this->get_version($request); - - $consumer = $this->get_consumer($request); - - // no token required for the initial token request - $token = NULL; - - $this->check_signature($request, $consumer, $token); - - // Rev A change - $callback = $request->get_parameter('oauth_callback'); - $new_token = $this->data_store->new_request_token($consumer, $callback); - - return $new_token; - } - - /** - * process an access_token request - * returns the access token on success - */ - public function fetch_access_token(&$request) { - $this->get_version($request); - - $consumer = $this->get_consumer($request); - - // requires authorized request token - $token = $this->get_token($request, $consumer, "request"); - - $this->check_signature($request, $consumer, $token); - - // Rev A change - $verifier = $request->get_parameter('oauth_verifier'); - $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); - - return $new_token; - } - - /** - * verify an api call, checks all the parameters - */ - public function verify_request(&$request) { - $this->get_version($request); - $consumer = $this->get_consumer($request); - $token = $this->get_token($request, $consumer, "access"); - $this->check_signature($request, $consumer, $token); - return array($consumer, $token); - } - - // Internals from here - /** - * version 1 - */ - private function get_version(&$request) { - $version = $request->get_parameter("oauth_version"); - if (!$version) { - // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. - // Chapter 7.0 ("Accessing Protected Ressources") - $version = '1.0'; - } - if ($version !== $this->version) { - throw new OAuthException("OAuth version '$version' not supported"); - } - return $version; - } - - /** - * figure out the signature with some defaults - */ - private function get_signature_method($request) { - $signature_method = $request instanceof OAuthRequest - ? $request->get_parameter("oauth_signature_method") - : NULL; - - if (!$signature_method) { - // According to chapter 7 ("Accessing Protected Ressources") the signature-method - // parameter is required, and we can't just fallback to PLAINTEXT - throw new OAuthException('No signature method parameter. This parameter is required'); - } - - if (!in_array($signature_method, - array_keys($this->signature_methods))) { - throw new OAuthException( - "Signature method '$signature_method' not supported " . - "try one of the following: " . - implode(", ", array_keys($this->signature_methods)) - ); - } - return $this->signature_methods[$signature_method]; - } - - /** - * try to find the consumer for the provided request's consumer key - */ - private function get_consumer($request) { - $consumer_key = $request instanceof OAuthRequest - ? $request->get_parameter("oauth_consumer_key") - : NULL; - - if (!$consumer_key) { - throw new OAuthException("Invalid consumer key"); - } - - $consumer = $this->data_store->lookup_consumer($consumer_key); - if (!$consumer) { - throw new OAuthException("Invalid consumer"); - } - - return $consumer; - } - - /** - * try to find the token for the provided request's token key - */ - private function get_token($request, $consumer, $token_type="access") { - $token_field = $request instanceof OAuthRequest - ? $request->get_parameter('oauth_token') - : NULL; - - $token = $this->data_store->lookup_token( - $consumer, $token_type, $token_field - ); - if (!$token) { - throw new OAuthException("Invalid $token_type token: $token_field"); - } - return $token; - } - - /** - * all-in-one function to check the signature on a request - * should guess the signature method appropriately - */ - private function check_signature($request, $consumer, $token) { - // this should probably be in a different method - $timestamp = $request instanceof OAuthRequest - ? $request->get_parameter('oauth_timestamp') - : NULL; - $nonce = $request instanceof OAuthRequest - ? $request->get_parameter('oauth_nonce') - : NULL; - - $this->check_timestamp($timestamp); - $this->check_nonce($consumer, $token, $nonce, $timestamp); - - $signature_method = $this->get_signature_method($request); - - $signature = $request->get_parameter('oauth_signature'); - $valid_sig = $signature_method->check_signature( - $request, - $consumer, - $token, - $signature - ); - - if (!$valid_sig) { - throw new OAuthException("Invalid signature"); - } - } - - /** - * check that the timestamp is new enough - */ - private function check_timestamp($timestamp) { - if( ! $timestamp ) - throw new OAuthException( - 'Missing timestamp parameter. The parameter is required' - ); - - // verify that timestamp is recentish - $now = time(); - if (abs($now - $timestamp) > $this->timestamp_threshold) { - throw new OAuthException( - "Expired timestamp, yours $timestamp, ours $now" - ); - } - } - - /** - * check that the nonce is not repeated - */ - private function check_nonce($consumer, $token, $nonce, $timestamp) { - if( ! $nonce ) - throw new OAuthException( - 'Missing nonce parameter. The parameter is required' - ); - - // verify that the nonce is uniqueish - $found = $this->data_store->lookup_nonce( - $consumer, - $token, - $nonce, - $timestamp - ); - if ($found) { - throw new OAuthException("Nonce already used: $nonce"); - } - } - -} - -class OAuthDataStore { - function lookup_consumer($consumer_key) { - // implement me - } - - function lookup_token($consumer, $token_type, $token) { - // implement me - } - - function lookup_nonce($consumer, $token, $nonce, $timestamp) { - // implement me - } - - function new_request_token($consumer, $callback = null) { - // return a new token attached to this consumer - } - - function new_access_token($token, $consumer, $verifier = null) { - // return a new access token attached to this consumer - // for the user associated with this token if the request token - // is authorized - // should also invalidate the request token - } - -} - -class OAuthUtil { - public static function urlencode_rfc3986($input) { - if (is_array($input)) { - return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input); - } else if (is_scalar($input)) { - return str_replace( - '+', - ' ', - str_replace('%7E', '~', rawurlencode($input)) - ); - } else { - return ''; - } -} - - - // This decode function isn't taking into consideration the above - // modifications to the encoding process. However, this method doesn't - // seem to be used anywhere so leaving it as is. - public static function urldecode_rfc3986($string) { - return urldecode($string); - } - - // Utility function for turning the Authorization: header into - // parameters, has to do some unescaping - // Can filter out any non-oauth parameters if needed (default behaviour) - // May 28th, 2010 - method updated to tjerk.meesters for a speed improvement. - // see http://code.google.com/p/oauth/issues/detail?id=163 - public static function split_header($header, $only_allow_oauth_parameters = true) { - $params = array(); - if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) { - foreach ($matches[1] as $i => $h) { - $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]); - } - if (isset($params['realm'])) { - unset($params['realm']); - } - } - return $params; - } - - // helper to try to sort out headers for people who aren't running apache - public static function get_headers() { - if (function_exists('apache_request_headers')) { - // we need this to get the actual Authorization: header - // because apache tends to tell us it doesn't exist - $headers = apache_request_headers(); - - // sanitize the output of apache_request_headers because - // we always want the keys to be Cased-Like-This and arh() - // returns the headers in the same case as they are in the - // request - $out = array(); - foreach ($headers AS $key => $value) { - $key = str_replace( - " ", - "-", - ucwords(strtolower(str_replace("-", " ", $key))) - ); - $out[$key] = $value; - } - } else { - // otherwise we don't have apache and are just going to have to hope - // that $_SERVER actually contains what we need - $out = array(); - if( isset($_SERVER['CONTENT_TYPE']) ) - $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; - if( isset($_ENV['CONTENT_TYPE']) ) - $out['Content-Type'] = $_ENV['CONTENT_TYPE']; - - foreach ($_SERVER as $key => $value) { - if (substr($key, 0, 5) == "HTTP_") { - // this is chaos, basically it is just there to capitalize the first - // letter of every word that is not an initial HTTP and strip HTTP - // code from przemek - $key = str_replace( - " ", - "-", - ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) - ); - $out[$key] = $value; - } - } - } - return $out; - } - - // This function takes a input like a=b&a=c&d=e and returns the parsed - // parameters like this - // array('a' => array('b','c'), 'd' => 'e') - public static function parse_parameters( $input ) { - if (!isset($input) || !$input) return array(); - - $pairs = explode('&', $input); - - $parsed_parameters = array(); - foreach ($pairs as $pair) { - $split = explode('=', $pair, 2); - $parameter = OAuthUtil::urldecode_rfc3986($split[0]); - $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : ''; - - if (isset($parsed_parameters[$parameter])) { - // We have already recieved parameter(s) with this name, so add to the list - // of parameters with this name - - if (is_scalar($parsed_parameters[$parameter])) { - // This is the first duplicate, so transform scalar (string) into an array - // so we can add the duplicates - $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); - } - - $parsed_parameters[$parameter][] = $value; - } else { - $parsed_parameters[$parameter] = $value; - } - } - return $parsed_parameters; - } - - public static function build_http_query($params) { - if (!$params) return ''; - - // Urlencode both keys and values - $keys = OAuthUtil::urlencode_rfc3986(array_keys($params)); - $values = OAuthUtil::urlencode_rfc3986(array_values($params)); - $params = array_combine($keys, $values); - - // Parameters are sorted by name, using lexicographical byte value ordering. - // Ref: Spec: 9.1.1 (1) - uksort($params, 'strcmp'); - - $pairs = array(); - foreach ($params as $parameter => $value) { - if (is_array($value)) { - // If two or more parameters share the same name, they are sorted by their value - // Ref: Spec: 9.1.1 (1) - // June 12th, 2010 - changed to sort because of issue 164 by hidetaka - sort($value, SORT_STRING); - foreach ($value as $duplicate_value) { - $pairs[] = $parameter . '=' . $duplicate_value; - } - } else { - $pairs[] = $parameter . '=' . $value; - } - } - // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) - // Each name-value pair is separated by an '&' character (ASCII code 38) - return implode('&', $pairs); - } -} - -?>
chok/sfOAuthPlugin
e1c988e4986fb45f9097e6cba25c7b9d9a584308
package
diff --git a/package.xml.tmpl b/package.xml.tmpl index be2e541..1a6e072 100644 --- a/package.xml.tmpl +++ b/package.xml.tmpl @@ -1,65 +1,65 @@ <?xml version="1.0" encoding="##ENCODING##"?> <package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.4.1" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> - <name>sfOAuthPlugin</name> + <name>sfOauthPlugin</name> <channel>plugins.symfony-project.org</channel> <summary> Use OAuth with symfony </summary> <description> The sfOAuth plugin provides an easy way to use OAuth with symfony. </description> <lead> <name>Maxime Picaud</name> <user>chok</user> <email>[email protected]</email> <active>yes</active> </lead> <date>##CURRENT_DATE##</date> <version> <release>##PLUGIN_VERSION##</release> <api>##API_VERSION##</api> </version> <stability> <release>##STABILITY##</release> <api>##STABILITY##</api> </stability> <license uri="http://www.symfony-project.org/license">MIT license</license> <notes>-</notes> <contents> ##CONTENTS## </contents> <dependencies> <required> <php> <min>5.2.4</min> </php> <pearinstaller> <min>1.4.1</min> </pearinstaller> <package> <name>symfony</name> <channel>pear.symfony-project.com</channel> <min>1.3.0</min> <max>1.5.0</max> <exclude>1.5.0</exclude> </package> </required> </dependencies> <phprelease></phprelease> <changelog> <release> <version> <release>1.0.0</release> <api>1.0.0</api> </version> <stability> <release>stable</release> <api>stable</api> </stability> <license uri="http://www.symfony-project.com/license">MIT license</license> <license>MIT</license> <date>08-23-2010</date> <notes>* First public release</notes> </release> </changelog> </package>
urezki/sftpd
c2466d557174353bf9a398ab97f16ef25a485ad6
sftpd: push new fixes
diff --git a/server/src/cmds.c b/server/src/cmds.c index 8d05645..13f036f 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,956 +1,976 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #include <str.h> static int convert_to_absolute_path(const char *root, const char *cur, const char *cmd_arg, char *out) { char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL) return -1; if (cmd_arg) { if (*cmd_arg == '/' || *cmd_arg == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(out, PATH_MAX, "%s%s", root, *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); } else { /* 2) cd foo/ */ n = snprintf(out, PATH_MAX, "%s%s", cur, cmd_arg); } } else { n = snprintf(out, PATH_MAX, "%s", cur); } if (n) ; /* /home/urezki/../ftp/.. */ if ((dot = strrchr(out, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(out, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(out, "/../"))) { char *s_pp = NULL; if (dot == out) s_pp = dot; else s_pp = (dot - 1); while (s_pp != out && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", out, dot + 4); snprintf(out, PATH_MAX, "%s", tmp_path); } return 0; } static int convert_path_to_abs_and_check(struct connection *conn) { char abs_path[PATH_MAX] = {'\0'}; char *cmd_arg; struct stat st; int ret; cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg) cmd_arg += 1; /* * We may pass NULL as cmd_path argument. In that case * current directory of the user should be reported. */ ret = convert_to_absolute_path(conn->root_dir, conn->curr_dir, cmd_arg, abs_path); if (ret < 0) goto fail; /* check symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, conn->root_dir, str_strlen(conn->root_dir))) { char cmd[MAX_CMD_LEN] = {'\0'}; int i = 0; /* get command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(cmd) - 1)) cmd[i] = conn->recv_buf[i]; } snprintf(conn->recv_buf, PATH_MAX - i, "%s %s", cmd, abs_path); return 1; } fail: return 0; } static void cmd_feat(void *srv, struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, str_strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(void *srv, struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); FLAG_CLEAR(conn->c_flags, C_AUTH); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(void *srv, struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); if (FLAG_QUERY(conn->c_flags, C_AUTH)) return; p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt) { if (!strcmp(p_crypt, p->pw_passwd)) FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); chdir(conn->root_dir); PRINT_DEBUG("%s user logged in\n", conn->user_name); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(void *srv, struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(void *srv, struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } t->listen_socket = listen_sock; FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); /* * T_PASV flag is set right after a connection * is established by the client with server side. */ FLAG_SET(t->t_flags, T_ACPT); /* * Detach the command channel. We do it here since * many clients send channel depended commands before * a connections is established. * * For example Mozilla firefox 52.3.0: * -> PASV * -> LIST (handle LIST cmd with no data channel) * -> a client initiates a data channel */ FD_CLR(conn->sock_fd, &((ftpd *)srv)->read_ready); /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(void *srv, struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &((ftpd *)srv)->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { send_cmd(conn->sock_fd, 550, "%s", strerror(ENOENT)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); FUNC_EXIT_VOID(); } static void cmd_allo(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } #ifdef UPLOAD_SUPPORT static void cmd_stor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (convert_path_to_abs_and_check(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &((ftpd *) srv)->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } FUNC_EXIT_VOID(); } static void cmd_dele(void *srv, struct connection *conn) { char *l_file; - int ret; + int ret = -1; FUNC_ENTRY(); + /* + * initially set to ENOENT + */ + errno = ENOENT; + if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; - ret = unlink(l_file); - if (ret != -1) - send_cmd(conn->sock_fd, 250, "File deleted OK."); - else - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - } else { - errno = ENOENT; - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + ret = open(l_file, O_WRONLY); + if (ret != -1) { + close(ret); + + /* + * on error returns -1 + */ + ret = unlink(l_file); + } } + if (ret != -1) + send_cmd(conn->sock_fd, 250, "File deleted OK."); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } #endif /* UPLOAD_SUPPORT */ static void cmd_size(void *srv, struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void cmd_list(void *srv, struct connection *c) { char *path; transport *t; int ret; t = c->transport; /* check and remove arguments */ ret = str_remove_from_to_symbols(c->recv_buf, '-', ' '); if (!ret) { char *arg = strrchr(c->recv_buf, ' '); if (arg && *(arg + 1) == '-') *arg = '\0'; } if (!convert_path_to_abs_and_check(c)) goto no_such_file_or_dir; path = strchr(c->recv_buf, ' ') + 1; ret = stat(path, &t->l_opt.st); if (ret != 0) goto no_such_file_or_dir; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } send_cmd(c->sock_fd, 150, "ASCII MODE"); FD_SET(t->socket, &((ftpd *) srv)->write_ready); FLAG_SET(t->t_flags, T_LIST); return; no_such_file_or_dir: send_cmd(c->sock_fd, 550, "%s", strerror(ENOENT)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void cmd_nlst(void *srv, struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); return cmd_list(srv, c); } static void cmd_noop(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(void *srv, struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = str_strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(void *srv, struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /* static void */ /* cmd_mdtm(void *srv, struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(void *srv, struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(void *srv, connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[MAX_CMD_LEN] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' or '\n' from the recv_buf */ i = str_strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(key) - 1)) key[i] = conn->recv_buf[i]; } /* * convert to apper case */ str_contac(key); entry = hash_lookup(((ftpd *) srv)->cmd_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { transport *t = conn->transport; /* * check if a transport is ready for particular cmd */ if (h->need_transport) { if (!FLAG_QUERY(t->t_flags, (T_PASV | T_PORT))) { send_cmd(conn->sock_fd, 425, "use PORT or PASV first"); goto out; } } /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(srv, conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } out: FUNC_EXIT_VOID(); } -const struct cmd_handler cmd_table[] = -{ +const struct cmd_handler cmd_table[] = { + /* + * 0 - CMD name + * 1 - CMD argument + * 2 - CMD handler + * 3 - CMD command requires root privileges + * 4 - CMD command requires authentication + * 5 - CMD command len (4/3 all the time) + * 6 - CMD if chroot has to be checked + * 7 - CMD requires a data transfer channel + */ { "USER", 1, cmd_user, 1, 0, 4, 0, 0 }, { "PASS", 1, cmd_pass, 1, 0, 4, 0, 0 }, { "PORT", 1, cmd_port, 1, 1, 4, 0, 0 }, { "PASV", 0, cmd_pasv, 0, 1, 4, 0, 0 }, - { "LIST", 1, cmd_list, 1, 1, 4, 1, 1 }, - { "NLST", 1, cmd_nlst, 1, 1, 4, 1, 1 }, + { "LIST", 1, cmd_list, 0, 1, 4, 1, 1 }, + { "NLST", 1, cmd_nlst, 0, 1, 4, 1, 1 }, { "CDUP", 0, cmd_cdup, 0, 1, 4, 0, 0 }, /* { "MDTM", 1, cmd_mdtm, 0, 1, 4, 1, 0 }, */ { "RETR", 1, cmd_retr, 0, 1, 4, 1, 1 }, { "SIZE", 1, cmd_size, 0, 1, 4, 1, 0 }, { "NOOP", 0, cmd_noop, 0, 1, 4, 0, 0 }, { "SYST", 0, cmd_syst, 0, 0, 4, 1, 0 }, { "TYPE", 0, cmd_type, 0, 1, 4, 0, 0 }, { "ABOR", 0, cmd_abor, 0, 1, 4, 0, 0 }, { "STRU", 0, cmd_stru, 0, 1, 4, 1, 0 }, { "QUIT", 0, cmd_quit, 0, 0, 4, 0, 0 }, { "FEAT", 0, cmd_feat, 0, 0, 4, 0, 0 }, { "HELP", 0, cmd_help, 0, 1, 4, 0, 0 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4, 1, 1 }, { "DELE", 1, cmd_dele, 0, 1, 4, 1, 0 }, { "RMD", 1, cmd_rmd, 0, 1, 3, 1, 0 }, { "MKD", 1, cmd_mkd, 0, 1, 3, 1, 0 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4, 0, 0 }, { "PWD", 0, cmd_pwd, 0, 1, 3, 0, 0 }, { "CWD", 1, cmd_cwd, 0, 1, 3, 0, 0 }, { " ", 0, NULL, 0, 0, 0, 0, 0 } }; diff --git a/server/src/hash.c b/server/src/hash.c index 3ab94f4..35535ee 100644 --- a/server/src/hash.c +++ b/server/src/hash.c @@ -1,280 +1,285 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* local */ #include <hash.h> /* +-----+-----+-----+ */ /* | 0 | a | - | */ /* +-----+-----+-----+ */ /* | 1 | - | - | */ /* +-----+-----+-----+ */ /* | 2 | a | b | */ /* +-----+-----+-----+ */ /* | 3 | a | - | */ /* +-----+-----+-----+ */ /* | 4 | a | - | */ /* +-----+-----+-----+ */ /* | 5 | a | b | */ /* +-----+-----+-----+ */ /* | 6 | a | - | */ /* +-----+-----+-----+ */ /* | 7 | - | - | */ /* +-----+-----+-----+ */ /* | 8 | a | b | */ /* +-----+-----+-----+ */ /* | 9 | - | - | */ /* +-----+-----+-----+ */ #define POISONED ((void *) 0x00100100) /* hit poisoned address */ static inline unsigned int hash_function(const char *key, int table_size) { unsigned int h = 0; unsigned int g = 0; while (*key) { h = (h << 4U) + *key++; if ((g = h & 0xf0000000)) h ^= g >> 24U; h &= ~g; } return h % table_size; } int hash_del(struct hash *h, const char *key) { struct hash_entry *tmp; unsigned int index; if (h && key) { index = hash_function(key, h->hash_size); tmp = h->hash_table[index]; if (tmp == NULL) goto out; /* go through the list of collision */ for (; tmp; tmp = tmp->next) { if (!strcmp(tmp->key, key)) { int ret = hash_del_entry(h, tmp); if (ret) return 1; else goto out; } } } out: return 0; } int hash_del_entry(struct hash *h, struct hash_entry *entry) { if (h && entry) { if (entry->prev) entry->prev->next = entry->next; if (entry->next) entry->next->prev = entry->prev; /* if it's first, shift head */ if (entry->prev == NULL) h->hash_table[entry->index] = entry->next; free(entry); return 1; } return 0; } void hash_destroy(struct hash *h) { struct hash_entry *tmp; int i; if (h) { for (i = 0; h->hash_table[i] != POISONED; i++) { tmp = h->hash_table[i]; while (tmp) { (void) hash_del(h, tmp->key); tmp = h->hash_table[i]; } h->hash_table[i] = NULL; } free(h); } } int hash_add(struct hash *h, const char *key, void *data) { struct hash_entry *node; struct hash_entry *tmp; unsigned int index; if (h == NULL || key == NULL) goto out; index = hash_function(key, h->hash_size); node = (hash_entry *) calloc(1, sizeof(hash_entry)); if (node) { /* fill out the node */ (void) strncpy(node->key, key, sizeof(node->key)); node->born_time = time(NULL); node->index = index; node->data = data; node->next = NULL; node->prev = NULL; if (h->hash_table[index] == NULL) { h->hash_table[index] = node; } else { tmp = h->hash_table[index]; while (1) { if (!strcmp(tmp->key, key)) goto out_and_free; if (tmp->next) /* the latest */ tmp = tmp->next; else break; } /* add to queue */ tmp->next = node; node->next = NULL; node->prev = tmp; } /* success */ return 1; } out_and_free: free(node); out: return 0; } struct hash_entry * hash_lookup(struct hash *h, const char *key) { - struct hash_entry *tmp; + struct hash_entry *entry = NULL; unsigned int index; if (h && key) { index = hash_function(key, h->hash_size); - tmp = h->hash_table[index]; - if (tmp == NULL) - goto out; - - while (tmp) { - if (!strcmp(tmp->key, key)) - return tmp; - - tmp = tmp->next; + entry = h->hash_table[index]; + if (entry) { + if (!entry->next) + goto no_collisions; + + /* + * There are collisions, so find and entry + * comparing with a given key. Will slow down + * a cash lookup. + */ + do { + if (!strcmp(entry->key, key)) + break; + } while ((entry = entry->next)); } } -out: - return NULL; +no_collisions: + return entry; } struct hash * hash_create(int table_size) { struct hash *h; int i; if (table_size > 0) { h = (struct hash *) calloc(1, sizeof(struct hash) + sizeof(void *) * (table_size + 1)); if (h) { for (i = 0; i < table_size; i++) h->hash_table[i] = NULL; h->hash_table[i] = (hash_entry *) POISONED; h->hash_size = table_size; return h; } } return NULL; } int hash_resize(struct hash *h, int size) { /* TODO: implement it */ return 0; } int hash_rehash(struct hash *h) { /* * Algorithm of rehashing is quite simple. This routine does * following things: * * 1) picks up all entries, except for marked as NULL; * 2) generates new index according to the key; * 3) if new index is not equal to old one then make replacing. */ if (h) { for (int i = 0; h->hash_table[i] != (hash_entry *) POISONED && h->hash_table[i]; i++) { struct hash_entry *tmp = h->hash_table[i]; unsigned int index = hash_function(tmp->key, h->hash_size); /* rehash everyone who is in queue */ do { if (tmp->index != index) { int ret; ret = hash_add(h, tmp->key, tmp->data); if (ret) { ret = hash_del_entry(h, tmp); } } } while (tmp->next); } } return 0; } void hash_dump(struct hash *h) { struct hash_entry *n; int i; if (h) { for (i = 0; h->hash_table[i] != (hash_entry *) POISONED; i++) { n = h->hash_table[i]; if (n) { fprintf(stdout, "%d ", i); do { fprintf(stdout, "+"); } while ((n = n->next)); fprintf(stdout, "\n"); } else { fprintf(stdout, "%d -\n", i); } } } } diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 17b216a..1bae820 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -183,586 +183,586 @@ sftpd_probe(int argc, char **argv) */ sftpd->cmd_table = hash_create(100); if (sftpd->cmd_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&sftpd->client_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(struct ftpd *srv, int s) { struct connection *new = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { new = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new->c_atime = time(NULL); new->sock_fd = s; new->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new->transport = tr; TAILQ_INSERT_TAIL(&srv->client_list, new, entries); /* add new client's socket */ FD_SET(new->sock_fd, &(srv->read_ready)); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new); return new; } static void destroy_transport(struct ftpd *srv, connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(struct ftpd *srv, connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&srv->client_list, c, entries); destroy_transport(srv, conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(struct ftpd *srv, int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(srv, conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void sftpd_quit(struct ftpd *srv) { struct connection *c; TAILQ_FOREACH(c, &srv->client_list, entries) { destroy_connection(srv, c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } static void handle_pending_signals(struct ftpd *srv) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) sftpd_quit(srv); } static int wait_for_events(ftpd *srv, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = srv->read_ready; *w_fd = srv->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(struct ftpd *srv, int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &srv->client_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(struct ftpd *srv, fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; int n; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { n = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); if (n > 0) c->recv_buf[n] = '\0'; /* modify last access */ c->c_atime = time(NULL); parse_cmd(srv, c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(struct ftpd *srv) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(srv, c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(srv, c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void kill_non_active_clients() { /* TODO */ } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; ret = build_list_line(arg + 1, !is_nlst ? &t->l_opt.st:NULL, line, sizeof(line)); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, !is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(struct ftpd *srv, fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed; FUNC_ENTRY(); processed = 0; TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; /* skip FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } + /* + * Attach back the command channel. We have removed + * it from the "read" pool because of waiting for a + * client until it established a data channel. + */ + if (!FD_ISSET(c->sock_fd, &srv->read_ready)) + FD_SET(c->sock_fd, &srv->read_ready); + c->c_atime = time(NULL); (*n_ready)--; processed++; } - - /* - * Attach back the command channel. We have removed - * it from the "read" pool because of waiting for a - * client until it established a data channel. - */ - if (!FD_ISSET(c->sock_fd, &srv->read_ready)) - FD_SET(c->sock_fd, &srv->read_ready); } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } static int do_main_loop(struct ftpd *s) { int n_ready = 0; fd_set r_fd; fd_set w_fd; while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(s, &r_fd, &w_fd, 60); /* process signals */ handle_pending_signals(s); /* process transfers */ process_transfers(s, &r_fd, &w_fd, &n_ready); /* process commands */ process_commands(s, &r_fd, &n_ready); kill_non_active_clients(); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(s, 10); process_clients_marked_as_destroy(s); /* accept new clients, if they are */ accept_connection(s, s->srv_socket, &r_fd, &n_ready); } return 0; } int main(int argc, char **argv) { struct ftpd *srv; srv = sftpd_probe(argc, argv); return do_main_loop(srv); }
urezki/sftpd
f8cc22ab2e0134ab7a21554c55b55e6195114e52
sftpd: push new fixes
diff --git a/server/include/cmds.h b/server/include/cmds.h index 47f3e95..973c876 100644 --- a/server/include/cmds.h +++ b/server/include/cmds.h @@ -1,19 +1,20 @@ #ifndef __CMDS_H__ #define __CMDS_H__ #define MAX_CMD_LEN 10 struct cmd_handler { char cmd_name[MAX_CMD_LEN]; char arg; void (*cmd_handler)(void *, struct connection *const); char need_root; int need_auth; char cmd_len; char need_check_chroot; + char need_transport; }; extern const struct cmd_handler cmd_table[]; extern void parse_cmd(void *, connection *conn); #endif /* __CMDS_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index 2c759d6..8d05645 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,948 +1,956 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #include <str.h> static int convert_to_absolute_path(const char *root, const char *cur, const char *cmd_arg, char *out) { char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL) return -1; if (cmd_arg) { if (*cmd_arg == '/' || *cmd_arg == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(out, PATH_MAX, "%s%s", root, *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); } else { /* 2) cd foo/ */ n = snprintf(out, PATH_MAX, "%s%s", cur, cmd_arg); } } else { n = snprintf(out, PATH_MAX, "%s", cur); } if (n) ; /* /home/urezki/../ftp/.. */ if ((dot = strrchr(out, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(out, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(out, "/../"))) { char *s_pp = NULL; if (dot == out) s_pp = dot; else s_pp = (dot - 1); while (s_pp != out && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", out, dot + 4); snprintf(out, PATH_MAX, "%s", tmp_path); } return 0; } static int convert_path_to_abs_and_check(struct connection *conn) { char abs_path[PATH_MAX] = {'\0'}; char *cmd_arg; struct stat st; int ret; cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg) cmd_arg += 1; /* * We may pass NULL as cmd_path argument. In that case * current directory of the user should be reported. */ ret = convert_to_absolute_path(conn->root_dir, conn->curr_dir, cmd_arg, abs_path); if (ret < 0) goto fail; /* check symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, conn->root_dir, str_strlen(conn->root_dir))) { char cmd[MAX_CMD_LEN] = {'\0'}; int i = 0; /* get command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(cmd) - 1)) cmd[i] = conn->recv_buf[i]; } snprintf(conn->recv_buf, PATH_MAX - i, "%s %s", cmd, abs_path); return 1; } fail: return 0; } static void cmd_feat(void *srv, struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, str_strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(void *srv, struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); FLAG_CLEAR(conn->c_flags, C_AUTH); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(void *srv, struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); if (FLAG_QUERY(conn->c_flags, C_AUTH)) return; p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt) { if (!strcmp(p_crypt, p->pw_passwd)) FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); chdir(conn->root_dir); PRINT_DEBUG("%s user logged in\n", conn->user_name); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(void *srv, struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(void *srv, struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } t->listen_socket = listen_sock; FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); /* * T_PASV flag is set right after a connection * is established by the client with server side. */ FLAG_SET(t->t_flags, T_ACPT); + /* + * Detach the command channel. We do it here since + * many clients send channel depended commands before + * a connections is established. + * + * For example Mozilla firefox 52.3.0: + * -> PASV + * -> LIST (handle LIST cmd with no data channel) + * -> a client initiates a data channel + */ + FD_CLR(conn->sock_fd, &((ftpd *)srv)->read_ready); + /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(void *srv, struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; - if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); - goto leave; - } - if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &((ftpd *)srv)->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { send_cmd(conn->sock_fd, 550, "%s", strerror(ENOENT)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); -leave: FUNC_EXIT_VOID(); } static void cmd_allo(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } #ifdef UPLOAD_SUPPORT static void cmd_stor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; - if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - if (convert_path_to_abs_and_check(conn)) { - char *l_file = strchr(conn->recv_buf, ' ') + 1; - - t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); - if (t->local_fd != -1) { - FD_SET(t->socket, &((ftpd *) srv)->read_ready); - send_cmd(conn->sock_fd, 150, "Binary mode."); - FLAG_SET(t->t_flags, T_STOR); - } else { - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); - } + if (convert_path_to_abs_and_check(conn)) { + char *l_file = strchr(conn->recv_buf, ' ') + 1; + + t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (t->local_fd != -1) { + FD_SET(t->socket, &((ftpd *) srv)->read_ready); + send_cmd(conn->sock_fd, 150, "Binary mode."); + FLAG_SET(t->t_flags, T_STOR); + } else { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); } - } else { - send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_dele(void *srv, struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } #endif /* UPLOAD_SUPPORT */ static void cmd_size(void *srv, struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void cmd_list(void *srv, struct connection *c) { char *path; transport *t; int ret; t = c->transport; - /* is transport ready? */ - if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) - goto use_port_or_pasv; - /* check and remove arguments */ ret = str_remove_from_to_symbols(c->recv_buf, '-', ' '); if (!ret) { char *arg = strrchr(c->recv_buf, ' '); if (arg && *(arg + 1) == '-') *arg = '\0'; } if (!convert_path_to_abs_and_check(c)) goto no_such_file_or_dir; path = strchr(c->recv_buf, ' ') + 1; ret = stat(path, &t->l_opt.st); if (ret != 0) goto no_such_file_or_dir; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } send_cmd(c->sock_fd, 150, "ASCII MODE"); FD_SET(t->socket, &((ftpd *) srv)->write_ready); FLAG_SET(t->t_flags, T_LIST); return; -use_port_or_pasv: - send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); - return; - no_such_file_or_dir: send_cmd(c->sock_fd, 550, "%s", strerror(ENOENT)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void cmd_nlst(void *srv, struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); return cmd_list(srv, c); } static void cmd_noop(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(void *srv, struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = str_strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(void *srv, struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /* static void */ /* cmd_mdtm(void *srv, struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(void *srv, struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(void *srv, connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[MAX_CMD_LEN] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' or '\n' from the recv_buf */ i = str_strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ - for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { + for (i = 0; conn->recv_buf[i] != ' ' && + conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(key) - 1)) key[i] = conn->recv_buf[i]; } /* * convert to apper case */ str_contac(key); entry = hash_lookup(((ftpd *) srv)->cmd_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { + transport *t = conn->transport; + + /* + * check if a transport is ready for particular cmd + */ + if (h->need_transport) { + if (!FLAG_QUERY(t->t_flags, (T_PASV | T_PORT))) { + send_cmd(conn->sock_fd, 425, "use PORT or PASV first"); + goto out; + } + } + /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(srv, conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } +out: FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { - { "USER", 1, cmd_user, 1, 0, 4, 0 }, - { "PASS", 1, cmd_pass, 1, 0, 4, 0 }, - { "PORT", 1, cmd_port, 1, 1, 4, 0 }, - { "PASV", 0, cmd_pasv, 0, 1, 4, 0 }, - { "LIST", 1, cmd_list, 1, 1, 4, 1 }, - { "NLST", 1, cmd_nlst, 1, 1, 4, 1 }, - { "CDUP", 0, cmd_cdup, 0, 1, 4, 0 }, - /* { "MDTM", 1, cmd_mdtm, 0, 1, 4, 1 }, */ - { "RETR", 1, cmd_retr, 0, 1, 4, 1 }, - { "SIZE", 1, cmd_size, 0, 1, 4, 1 }, - { "NOOP", 0, cmd_noop, 0, 1, 4, 0 }, - { "SYST", 0, cmd_syst, 0, 0, 4, 1 }, - { "TYPE", 0, cmd_type, 0, 1, 4, 0 }, - { "ABOR", 0, cmd_abor, 0, 1, 4, 0 }, - { "STRU", 0, cmd_stru, 0, 1, 4, 1 }, - { "QUIT", 0, cmd_quit, 0, 0, 4, 0 }, - { "FEAT", 0, cmd_feat, 0, 0, 4, 0 }, - { "HELP", 0, cmd_help, 0, 1, 4, 0 }, + { "USER", 1, cmd_user, 1, 0, 4, 0, 0 }, + { "PASS", 1, cmd_pass, 1, 0, 4, 0, 0 }, + { "PORT", 1, cmd_port, 1, 1, 4, 0, 0 }, + { "PASV", 0, cmd_pasv, 0, 1, 4, 0, 0 }, + { "LIST", 1, cmd_list, 1, 1, 4, 1, 1 }, + { "NLST", 1, cmd_nlst, 1, 1, 4, 1, 1 }, + { "CDUP", 0, cmd_cdup, 0, 1, 4, 0, 0 }, + /* { "MDTM", 1, cmd_mdtm, 0, 1, 4, 1, 0 }, */ + { "RETR", 1, cmd_retr, 0, 1, 4, 1, 1 }, + { "SIZE", 1, cmd_size, 0, 1, 4, 1, 0 }, + { "NOOP", 0, cmd_noop, 0, 1, 4, 0, 0 }, + { "SYST", 0, cmd_syst, 0, 0, 4, 1, 0 }, + { "TYPE", 0, cmd_type, 0, 1, 4, 0, 0 }, + { "ABOR", 0, cmd_abor, 0, 1, 4, 0, 0 }, + { "STRU", 0, cmd_stru, 0, 1, 4, 1, 0 }, + { "QUIT", 0, cmd_quit, 0, 0, 4, 0, 0 }, + { "FEAT", 0, cmd_feat, 0, 0, 4, 0, 0 }, + { "HELP", 0, cmd_help, 0, 1, 4, 0, 0 }, #ifdef UPLOAD_SUPPORT - { "STOR", 0, cmd_stor, 0, 1, 4, 1 }, - { "DELE", 1, cmd_dele, 0, 1, 4, 1 }, - { "RMD", 1, cmd_rmd, 0, 1, 3, 1 }, - { "MKD", 1, cmd_mkd, 0, 1, 3, 1 }, + { "STOR", 0, cmd_stor, 0, 1, 4, 1, 1 }, + { "DELE", 1, cmd_dele, 0, 1, 4, 1, 0 }, + { "RMD", 1, cmd_rmd, 0, 1, 3, 1, 0 }, + { "MKD", 1, cmd_mkd, 0, 1, 3, 1, 0 }, #endif - { "ALLO", 0, cmd_allo, 0, 1, 4, 0 }, - { "PWD", 0, cmd_pwd, 0, 1, 3, 0 }, - { "CWD", 1, cmd_cwd, 0, 1, 3, 0 }, - { " ", 0, NULL, 0, 0, 0, 0 } + { "ALLO", 0, cmd_allo, 0, 1, 4, 0, 0 }, + { "PWD", 0, cmd_pwd, 0, 1, 3, 0, 0 }, + { "CWD", 1, cmd_cwd, 0, 1, 3, 0, 0 }, + { " ", 0, NULL, 0, 0, 0, 0, 0 } }; diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 44adc12..17b216a 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,762 +1,768 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> #include <sys/time.h> #include <sys/resource.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <workqueue.h> #include <cmds.h> #include <hash.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * sftpd_probe(int argc, char **argv) { struct rlimit rlim; ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; ret = setrlimit(RLIMIT_CORE, &rlim); if (ret) PRINT_DEBUG("'setrlimit()' failed with error: %s\n", strerror(errno)); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_table = hash_create(100); if (sftpd->cmd_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&sftpd->client_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(struct ftpd *srv, int s) { struct connection *new = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { new = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new->c_atime = time(NULL); new->sock_fd = s; new->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new->transport = tr; TAILQ_INSERT_TAIL(&srv->client_list, new, entries); /* add new client's socket */ FD_SET(new->sock_fd, &(srv->read_ready)); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new); return new; } static void destroy_transport(struct ftpd *srv, connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(struct ftpd *srv, connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); - else - BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&srv->client_list, c, entries); destroy_transport(srv, conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(struct ftpd *srv, int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(srv, conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void sftpd_quit(struct ftpd *srv) { struct connection *c; TAILQ_FOREACH(c, &srv->client_list, entries) { destroy_connection(srv, c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } static void handle_pending_signals(struct ftpd *srv) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) sftpd_quit(srv); } static int wait_for_events(ftpd *srv, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = srv->read_ready; *w_fd = srv->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(struct ftpd *srv, int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &srv->client_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(struct ftpd *srv, fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; int n; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { n = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); if (n > 0) c->recv_buf[n] = '\0'; /* modify last access */ c->c_atime = time(NULL); parse_cmd(srv, c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(struct ftpd *srv) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(srv, c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(srv, c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void kill_non_active_clients() { /* TODO */ } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; ret = build_list_line(arg + 1, !is_nlst ? &t->l_opt.st:NULL, line, sizeof(line)); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, !is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(struct ftpd *srv, fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed; FUNC_ENTRY(); processed = 0; TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; /* skip FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } + + /* + * Attach back the command channel. We have removed + * it from the "read" pool because of waiting for a + * client until it established a data channel. + */ + if (!FD_ISSET(c->sock_fd, &srv->read_ready)) + FD_SET(c->sock_fd, &srv->read_ready); } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } static int do_main_loop(struct ftpd *s) { int n_ready = 0; fd_set r_fd; fd_set w_fd; while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(s, &r_fd, &w_fd, 60); /* process signals */ handle_pending_signals(s); /* process transfers */ process_transfers(s, &r_fd, &w_fd, &n_ready); /* process commands */ process_commands(s, &r_fd, &n_ready); kill_non_active_clients(); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(s, 10); process_clients_marked_as_destroy(s); /* accept new clients, if they are */ accept_connection(s, s->srv_socket, &r_fd, &n_ready); } return 0; } int main(int argc, char **argv) { struct ftpd *srv; srv = sftpd_probe(argc, argv); return do_main_loop(srv); }
urezki/sftpd
531f3d2ea6fc62764cdf07eba5497592620b82d5
sftpd: push new changes
diff --git a/server/include/ls.h b/server/include/ls.h index 12d4419..624d056 100644 --- a/server/include/ls.h +++ b/server/include/ls.h @@ -1,19 +1,19 @@ #ifndef __LS_H__ #define __LS_H__ /* flags for LIST cmd */ #define L_FOLD 0x00000001 /* list folder */ #define L_FILE 0x00000004 /* list one file */ #define L_NLST 0x00000008 /* list without ext. info */ struct list_opt { char path[PATH_MAX]; struct stat st; void *target_dir; int l_flags; }; extern char *get_file_list_chunk(DIR *, int, int); -extern int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l); +extern int build_list_line(const char *name, struct stat *st, char *line, int l_size); #endif /* __LS_H__ */ diff --git a/server/include/str.h b/server/include/str.h index d75d9d5..815a23d 100644 --- a/server/include/str.h +++ b/server/include/str.h @@ -1,10 +1,11 @@ #ifndef __STR_H__ #define __STR_H__ extern void str_contac(char *); extern size_t str_strlen(const char *); extern size_t str_findss(const char *, const char *); extern size_t str_removesfs(char *, const char *); extern size_t str_strcspn(const char *, const char *); +extern size_t str_remove_from_to_symbols(char *str, char a, char b); #endif diff --git a/server/src/cmds.c b/server/src/cmds.c index 6984f7f..2c759d6 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,936 +1,948 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #include <str.h> static int convert_to_absolute_path(const char *root, const char *cur, const char *cmd_arg, char *out) { char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL) return -1; if (cmd_arg) { if (*cmd_arg == '/' || *cmd_arg == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(out, PATH_MAX, "%s%s", root, *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); } else { /* 2) cd foo/ */ n = snprintf(out, PATH_MAX, "%s%s", cur, cmd_arg); } } else { n = snprintf(out, PATH_MAX, "%s", cur); } if (n) ; /* /home/urezki/../ftp/.. */ if ((dot = strrchr(out, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(out, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(out, "/../"))) { char *s_pp = NULL; if (dot == out) s_pp = dot; else s_pp = (dot - 1); while (s_pp != out && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", out, dot + 4); snprintf(out, PATH_MAX, "%s", tmp_path); } return 0; } static int convert_path_to_abs_and_check(struct connection *conn) { char abs_path[PATH_MAX] = {'\0'}; char *cmd_arg; struct stat st; int ret; cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg) cmd_arg += 1; /* * We may pass NULL as cmd_path argument. In that case * current directory of the user should be reported. */ ret = convert_to_absolute_path(conn->root_dir, conn->curr_dir, cmd_arg, abs_path); if (ret < 0) goto fail; /* check symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } - if (!strncmp(abs_path, conn->root_dir, strlen(conn->root_dir))) { + if (!strncmp(abs_path, conn->root_dir, str_strlen(conn->root_dir))) { char cmd[MAX_CMD_LEN] = {'\0'}; int i = 0; /* get command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(cmd) - 1)) cmd[i] = conn->recv_buf[i]; } snprintf(conn->recv_buf, PATH_MAX - i, "%s %s", cmd, abs_path); return 1; } fail: return 0; } static void cmd_feat(void *srv, struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ - send_data(conn->sock_fd, feat, strlen(feat), 0); + send_data(conn->sock_fd, feat, str_strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(void *srv, struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); FLAG_CLEAR(conn->c_flags, C_AUTH); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(void *srv, struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); if (FLAG_QUERY(conn->c_flags, C_AUTH)) return; p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt) { if (!strcmp(p_crypt, p->pw_passwd)) FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); chdir(conn->root_dir); PRINT_DEBUG("%s user logged in\n", conn->user_name); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(void *srv, struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(void *srv, struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } + t->listen_socket = listen_sock; + FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); + + /* + * T_PASV flag is set right after a connection + * is established by the client with server side. + */ + FLAG_SET(t->t_flags, T_ACPT); + /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); - t->listen_socket = listen_sock; - FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); - FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(void *srv, struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &((ftpd *)srv)->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { send_cmd(conn->sock_fd, 550, "%s", strerror(ENOENT)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } #ifdef UPLOAD_SUPPORT static void cmd_stor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (convert_path_to_abs_and_check(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &((ftpd *) srv)->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_dele(void *srv, struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } #endif /* UPLOAD_SUPPORT */ static void cmd_size(void *srv, struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void cmd_list(void *srv, struct connection *c) { char *path; transport *t; int ret; t = c->transport; + /* is transport ready? */ if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) goto use_port_or_pasv; + /* check and remove arguments */ + ret = str_remove_from_to_symbols(c->recv_buf, '-', ' '); + if (!ret) { + char *arg = strrchr(c->recv_buf, ' '); + if (arg && *(arg + 1) == '-') + *arg = '\0'; + } + if (!convert_path_to_abs_and_check(c)) goto no_such_file_or_dir; - path = strchr(c->recv_buf, ' '); - BUG_ON(!path); - path += 1; - + path = strchr(c->recv_buf, ' ') + 1; ret = stat(path, &t->l_opt.st); if (ret != 0) goto no_such_file_or_dir; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } send_cmd(c->sock_fd, 150, "ASCII MODE"); FD_SET(t->socket, &((ftpd *) srv)->write_ready); FLAG_SET(t->t_flags, T_LIST); return; use_port_or_pasv: send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); return; no_such_file_or_dir: send_cmd(c->sock_fd, 550, "%s", strerror(ENOENT)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void cmd_nlst(void *srv, struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); return cmd_list(srv, c); } static void cmd_noop(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(void *srv, struct connection *conn) { int root_len; FUNC_ENTRY(); - root_len = strlen(conn->root_dir); + root_len = str_strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(void *srv, struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { - int root_len = strlen(conn->root_dir); + int root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /* static void */ /* cmd_mdtm(void *srv, struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(void *srv, struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (convert_path_to_abs_and_check(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } - root_len = strlen(conn->root_dir); + root_len = str_strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(void *srv, connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[MAX_CMD_LEN] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' or '\n' from the recv_buf */ i = str_strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(key) - 1)) key[i] = conn->recv_buf[i]; } /* * convert to apper case */ str_contac(key); entry = hash_lookup(((ftpd *) srv)->cmd_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(srv, conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4, 0 }, { "PASS", 1, cmd_pass, 1, 0, 4, 0 }, { "PORT", 1, cmd_port, 1, 1, 4, 0 }, { "PASV", 0, cmd_pasv, 0, 1, 4, 0 }, { "LIST", 1, cmd_list, 1, 1, 4, 1 }, { "NLST", 1, cmd_nlst, 1, 1, 4, 1 }, { "CDUP", 0, cmd_cdup, 0, 1, 4, 0 }, /* { "MDTM", 1, cmd_mdtm, 0, 1, 4, 1 }, */ { "RETR", 1, cmd_retr, 0, 1, 4, 1 }, { "SIZE", 1, cmd_size, 0, 1, 4, 1 }, { "NOOP", 0, cmd_noop, 0, 1, 4, 0 }, { "SYST", 0, cmd_syst, 0, 0, 4, 1 }, { "TYPE", 0, cmd_type, 0, 1, 4, 0 }, { "ABOR", 0, cmd_abor, 0, 1, 4, 0 }, { "STRU", 0, cmd_stru, 0, 1, 4, 1 }, { "QUIT", 0, cmd_quit, 0, 0, 4, 0 }, { "FEAT", 0, cmd_feat, 0, 0, 4, 0 }, { "HELP", 0, cmd_help, 0, 1, 4, 0 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4, 1 }, { "DELE", 1, cmd_dele, 0, 1, 4, 1 }, { "RMD", 1, cmd_rmd, 0, 1, 3, 1 }, { "MKD", 1, cmd_mkd, 0, 1, 3, 1 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4, 0 }, { "PWD", 0, cmd_pwd, 0, 1, 3, 0 }, { "CWD", 1, cmd_cwd, 0, 1, 3, 0 }, { " ", 0, NULL, 0, 0, 0, 0 } }; diff --git a/server/src/ls.c b/server/src/ls.c index 84e1f2b..0b7c9fc 100644 --- a/server/src/ls.c +++ b/server/src/ls.c @@ -1,185 +1,179 @@ #define _ATFILE_SOURCE #include <fcntl.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <dirent.h> #include <time.h> #include <errno.h> #include <debug.h> #include <mem.h> #define MAX_UID_LEN 5 #define MAX_GID_LEN 5 static char * get_perm(mode_t st_mode, char *perm) { int i; /* clean */ for (i = 0; i < 9; i++) *(perm + i) = '-'; *(perm + 0) = '?'; switch (st_mode & S_IFMT) { case S_IFDIR: *(perm + 0) = 'd'; break; case S_IFREG: *(perm + 0) = '-'; break; case S_IFLNK: *(perm + 0) = 'l'; break; case S_IFBLK: *(perm + 0) = 'b'; break; case S_IFCHR: *(perm + 0) = 'c'; break; case S_IFSOCK: *(perm + 0) = 's'; break; case S_IFIFO: *(perm + 0) = 'p'; break; } (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): (*(perm + 1) = '-'); (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): (*(perm + 2) = '-'); (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): (*(perm + 3) = '-'); (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): (*(perm + 4) = '-'); (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): (*(perm + 5) = '-'); (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): (*(perm + 6) = '-'); (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): (*(perm + 7) = '-'); (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): (*(perm + 8) = '-'); (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): (*(perm + 9) = '-'); *(perm + 10) = '\0'; return perm; } static int get_file_attr(DIR *d, const char *f_name, struct stat *st) { int dir_fd; int ret; if (d) { dir_fd = dirfd(d); if (dir_fd != -1) { ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); if (ret == 0) return 1; else PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); } else { PRINT_DEBUG("dirfd error: %s\n", strerror(errno)); } } return 0; } static struct dirent * get_dirent_entry(DIR *dir_name) { struct dirent *d = NULL; if (dir_name != NULL) { d = readdir(dir_name); if (d == NULL) { return NULL; } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { d = get_dirent_entry(dir_name); } } return d; } static int get_mtime(time_t time, char *mtime, int mtime_len) { const char *date_format = "%b %d %H:%M"; struct timeval c_time; struct tm *tm = NULL; if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { if (time > c_time.tv_sec || (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { date_format = "%b %d %Y"; } tm = localtime(&time); strftime(mtime, mtime_len - 1, date_format, tm); return 1; } return 0; } int -build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l) +build_list_line(const char *name, struct stat *st, char *line, int l_size) { char mtime[20] = {'\0'}; char perm[11] = {'\0'}; int ret = -1; - if (!short_l) { + if (st) { /* Permissions */ (void) get_perm(st->st_mode, perm); /* time of last modification */ (void) get_mtime(st->st_mtime, mtime, sizeof(mtime)); /* build the line */ ret = snprintf(line, l_size - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", perm, (unsigned int) st->st_nlink, MAX_UID_LEN, st->st_uid, MAX_GID_LEN, st->st_gid, 10, st->st_size, mtime, name); } else { ret = snprintf(line, l_size - 1, "%s\r\n", name); } return ret; } char * -get_file_list_chunk(DIR *dir, int nfiles, int short_list) +get_file_list_chunk(DIR *dir, int how_many_files, int do_stat) { struct dirent *d = NULL; char line[400] = {'\0'}; char *chunk = NULL; int len = 0; - if (nfiles > 0) { - chunk = (char *) calloc(nfiles * sizeof(line), sizeof(char)); + if (how_many_files > 0) { + chunk = (char *) calloc(how_many_files * sizeof(line), sizeof(char)); if (chunk == NULL) FATAL_ERROR("error: %s\n", strerror(errno)); - for (int i = 0; i < nfiles; i++) { + for (int i = 0; i < how_many_files; i++) { d = get_dirent_entry(dir); if (d != NULL) { struct stat st; - int ret; - - ret = get_file_attr(dir, d->d_name, &st); - if (ret) { - if (short_list == 0) { - len += build_list_line(d->d_name, &st, line, sizeof(line), 0); - } else { - len += build_list_line(d->d_name, &st, line, sizeof(line), 1); - } - - /* attach to the chunk */ - (void) strcat(chunk, line); - } + + len += build_list_line(d->d_name, (do_stat ? + (get_file_attr(dir, d->d_name, &st) ? + &st:NULL):NULL), line, sizeof(line)); + + /* attach to the chunk */ + (void) strcat(chunk, line); } } if (len > 0) return chunk; } if (chunk) free(chunk); return NULL; } diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 406e9a0..44adc12 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -111,651 +111,652 @@ init_daemon(void) exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * sftpd_probe(int argc, char **argv) { struct rlimit rlim; ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; ret = setrlimit(RLIMIT_CORE, &rlim); if (ret) PRINT_DEBUG("'setrlimit()' failed with error: %s\n", strerror(errno)); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_table = hash_create(100); if (sftpd->cmd_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&sftpd->client_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(struct ftpd *srv, int s) { struct connection *new = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { new = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new->c_atime = time(NULL); new->sock_fd = s; new->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new->transport = tr; TAILQ_INSERT_TAIL(&srv->client_list, new, entries); /* add new client's socket */ FD_SET(new->sock_fd, &(srv->read_ready)); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new); return new; } static void destroy_transport(struct ftpd *srv, connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(struct ftpd *srv, connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&srv->client_list, c, entries); destroy_transport(srv, conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(struct ftpd *srv, int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(srv, conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void sftpd_quit(struct ftpd *srv) { struct connection *c; TAILQ_FOREACH(c, &srv->client_list, entries) { destroy_connection(srv, c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } static void handle_pending_signals(struct ftpd *srv) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) sftpd_quit(srv); } static int wait_for_events(ftpd *srv, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = srv->read_ready; *w_fd = srv->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(struct ftpd *srv, int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &srv->client_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(struct ftpd *srv, fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; int n; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { n = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); if (n > 0) c->recv_buf[n] = '\0'; /* modify last access */ c->c_atime = time(NULL); parse_cmd(srv, c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(struct ftpd *srv) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(srv, c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(srv, c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void kill_non_active_clients() { /* TODO */ } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; - ret = build_list_line(arg + 1, &t->l_opt.st, line, sizeof(line), is_nlst); + ret = build_list_line(arg + 1, !is_nlst ? + &t->l_opt.st:NULL, line, sizeof(line)); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } - list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); + list = get_file_list_chunk(t->l_opt.target_dir, 300, !is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(struct ftpd *srv, fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed; FUNC_ENTRY(); processed = 0; TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; /* skip FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } static int do_main_loop(struct ftpd *s) { int n_ready = 0; fd_set r_fd; fd_set w_fd; while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(s, &r_fd, &w_fd, 60); /* process signals */ handle_pending_signals(s); /* process transfers */ process_transfers(s, &r_fd, &w_fd, &n_ready); /* process commands */ process_commands(s, &r_fd, &n_ready); kill_non_active_clients(); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(s, 10); process_clients_marked_as_destroy(s); /* accept new clients, if they are */ accept_connection(s, s->srv_socket, &r_fd, &n_ready); } return 0; } int main(int argc, char **argv) { struct ftpd *srv; srv = sftpd_probe(argc, argv); return do_main_loop(srv); } diff --git a/server/src/str.c b/server/src/str.c index b0b6f19..dc14103 100644 --- a/server/src/str.c +++ b/server/src/str.c @@ -1,111 +1,147 @@ #include <stdio.h> void str_contac(char *s) { if (s == NULL) return; while (*s) { if (*s > 96 && *s < 123) *s -= 32; s++; } } size_t str_strlen(const char *s) { size_t i = 0; if (s) { while (*(s++) != '\0') i++; } return i; } /** * a - target string * b - string that contains reject characters */ size_t str_strcspn(const char *a, const char *b) { size_t a_len; size_t b_len; int i, j = 0; a_len = str_strlen(a); b_len = str_strlen(b); if (!a_len || !b_len) goto out; for (i = 0; i < a_len; i++) { /* compare two strings here */ for (j = 0; j < b_len; j++) { if (a[i] != b[j]) continue; goto out; } } out: return i; } /** * returns index that points to the beginning * of found string, otherwise zero */ size_t str_findss(const char *a, const char *b) { size_t a_len; size_t b_len; size_t index; int i, j; a_len = str_strlen(a); b_len = str_strlen(b); if (!a_len || !b_len) goto not_found; for (i = 0; i < a_len; i++) { if (a[i] == b[0]) { index = i; /* compare two strings here */ for (j = 0; i < a_len; i++) { if (a[i] == b[j]) { if (++j == b_len) return index; } else { i--; break; } } } } not_found: return 0; } /** * returns new string length, otherwise zero */ size_t str_removesfs(char *a, const char *b) { size_t i; i = str_findss(a, b); if (i) a[i] = '\0'; return i; } + +/** + * example: + * in: "LIST -a -l incoming/" + * str_remove_symbols(str, '-', ' '); + * out: "LIST incoming/" + */ +size_t +str_remove_from_to_symbols(char *str, char a, char b) +{ + size_t str_new_len = 0; + size_t str_len; + int i, j; + + str_len = str_strlen(str); + +again: + for (i = 0; i < str_len; i++) { + if (str[i] == a) { + for (j = i; j < str_len; j++) { + if (str[j] == b) { + do { + str[i++] = str[++j]; + } while (str[j] != '\0'); + + /* minus '\0' */ + str_new_len = str_len = + (str_len - (j - i)) - 1; + goto again; + } + } + } + } + + return str_new_len; +}
urezki/sftpd
02c27fb3359c4e96d1d0b33935a54aff169547b6
sftpd: push new changes
diff --git a/server/Makefile b/server/Makefile index 64ea58e..fd9f986 100644 --- a/server/Makefile +++ b/server/Makefile @@ -1,19 +1,20 @@ # Mafifile CC = gcc -CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DMEMORY_DEBUG -DUPLOAD_SUPPORT -std=c99 +# CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DUPLOAD_SUPPORT -std=c99 +CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -std=c99 INCLUDE = -I./include LIB = -lcrypt -pthread BINARY = sftpd SRC = $(wildcard src/*.c) OBJ = $(subst .c,.o, $(SRC)) all: $(OBJ) $(CC) -o $(BINARY) $(OBJ) $(LIB) .c.o: $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $< clean: rm -rf $(OBJ) $(BINARY) diff --git a/server/include/cmds.h b/server/include/cmds.h index bb8e291..47f3e95 100644 --- a/server/include/cmds.h +++ b/server/include/cmds.h @@ -1,18 +1,19 @@ #ifndef __CMDS_H__ #define __CMDS_H__ #define MAX_CMD_LEN 10 struct cmd_handler { char cmd_name[MAX_CMD_LEN]; char arg; void (*cmd_handler)(void *, struct connection *const); char need_root; int need_auth; char cmd_len; + char need_check_chroot; }; extern const struct cmd_handler cmd_table[]; extern void parse_cmd(void *, connection *conn); #endif /* __CMDS_H__ */ diff --git a/server/include/debug.h b/server/include/debug.h index dbd8664..67da6e6 100644 --- a/server/include/debug.h +++ b/server/include/debug.h @@ -1,64 +1,67 @@ #ifndef __DEBUG_H__ #define __DEBUG_H__ #include <errno.h> +#define unlikely(x) __builtin_expect(!!(x), 0) + /* just causes a Segmentation Fault */ #define BUG() (*(int *)0 = 0) +#define BUG_ON(condition) do { if (unlikely(condition)) BUG(); } while (0) #define __DEBUG_MSG__ /* #define __DEBUG_FUNC__ */ #ifdef __DEBUG_MSG__ /* DEBUG MSG */ #define PRINT_DEBUG(fmt,arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); } while (0) #else #define PRINT_DEBUG(fmt,arg...) \ do { } while(0) #endif /* __DEBUG_MSG__ */ #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) #define FATAL_ERROR(fmt, arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); \ exit(-1); } while (0) #ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ #define FUNC_ENTRY() do { \ fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_VOID() do { \ fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_INT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ __FUNCTION__, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_UINT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ __FUNCTION__, value, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_PTR(ptr) do { \ fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ __FUNCTION__, ptr); \ fflush(stdout); } while (0) #else #define FUNC_ENTRY() do { } while(0) #define FUNC_EXIT_VOID() do { } while(0) #define FUNC_EXIT_INT(value) do { } while(0) #define FUNC_EXIT_UINT(value) do { } while(0) #define FUNC_EXIT_PTR(ptr) do { } while(0) #endif /* __DEBUG_FUNC__ */ #endif /* __DEBUG_H__ */ diff --git a/server/include/sftpd.h b/server/include/sftpd.h index bb4876b..70504f7 100644 --- a/server/include/sftpd.h +++ b/server/include/sftpd.h @@ -1,102 +1,81 @@ #ifndef __FTPD_H__ #define __FTPD_H__ #define DATA_PORT 20 #define RECV_BUF_SIZE 4096 /* connection specific flags */ #define C_AUTH 0x00000001 #define C_KILL 0x00000002 /* states of the transport */ #define T_FREE 0x00000001 #define T_PORT 0x00000002 #define T_PASV 0x00000004 #define T_LIST 0x00000008 #define T_RETR 0x00000010 #define T_STOR 0x00000020 #define T_ACPT 0x00000040 /* accepting */ #define T_KILL 0x00000080 #define FLAG_SET(X,Y) (X = (X^X) | Y) #define FLAG_APPEND(X,Y) (X = (X | Y)) #define FLAG_QUERY(X,Y) (X & Y) #define FLAG_CLEAR(X,Y) (X &= ~Y) struct connection { char recv_buf[RECV_BUF_SIZE]; int recv_buf_len; char user_name[256]; char user_pass[256]; char root_dir[256]; char curr_dir[256]; int sock_fd; uid_t uid; gid_t gid; time_t c_atime; /* last access time*/ int c_flags; struct transport *transport; - struct data_channel { - struct sockaddr_in r_info; - struct stat st; - - int listen_socket; - int socket; - - int data_port; - - int local_fd; - off_t offset; - - /* state */ - int t_flags; - - /* - * for LIST/NLST cmd - */ - struct list_opt l_opt; - } dc; - TAILQ_ENTRY(connection) entries; }; struct transport { struct sockaddr_in r_info; struct stat st; int listen_socket; int socket; int data_port; int local_fd; off_t offset; /* state */ int t_flags; /* * for LIST/NLST cmd */ struct list_opt l_opt; }; struct ftpd { struct hash *cmd_table; unsigned int client_count; fd_set write_ready; fd_set read_ready; int srv_socket; /* all clients are linked to the list */ TAILQ_HEAD(cl_list, connection) client_list; }; typedef struct connection connection; typedef struct transport transport; typedef struct ftpd ftpd; #endif /* __FTPD_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index 266ee4d..6984f7f 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,998 +1,936 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #include <str.h> static int -build_full_path(const char *root, const char *cur, char *dst) +convert_to_absolute_path(const char *root, const char *cur, + const char *cmd_arg, char *out) { - char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; - if (root == NULL || cur == NULL || dst == NULL) + if (root == NULL || cur == NULL) return -1; - if (*dst == '/' || *dst == '~') { - /* 1) cd / 2) cd ~/ 3) cd ~ */ - n = snprintf(absolute_path, PATH_MAX, "%s%s", root, - *(dst + 1) == '/' ? dst + 2 : dst + 1); + if (cmd_arg) { + if (*cmd_arg == '/' || *cmd_arg == '~') { + /* 1) cd / 2) cd ~/ 3) cd ~ */ + n = snprintf(out, PATH_MAX, "%s%s", root, + *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); + } else { + /* 2) cd foo/ */ + n = snprintf(out, PATH_MAX, "%s%s", cur, cmd_arg); + } } else { - /* 1) cd foo/ */ - n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); + n = snprintf(out, PATH_MAX, "%s", cur); } if (n) ; /* /home/urezki/../ftp/.. */ - if ((dot = strrchr(absolute_path, '.'))) + if ((dot = strrchr(out, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') - strcat(absolute_path, "/"); + strcat(out, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ - while ((dot = strstr(absolute_path, "/../"))) { + while ((dot = strstr(out, "/../"))) { char *s_pp = NULL; - if (dot == absolute_path) + if (dot == out) s_pp = dot; else s_pp = (dot - 1); - while (s_pp != absolute_path && *s_pp != '/') + while (s_pp != out && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; - snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); - snprintf(absolute_path, PATH_MAX, "%s", tmp_path); + snprintf(tmp_path, PATH_MAX, "%s%s", out, dot + 4); + snprintf(out, PATH_MAX, "%s", tmp_path); } - snprintf(dst, PATH_MAX, "%s", absolute_path); return 0; } -static void -get_abs_path(const char *root, const char *cur, const char *path, char *abs_path) -{ - char absolute_path[PATH_MAX] = {'\0'}; - char tmp_path[PATH_MAX] = {'\0'}; - char *dot; - int n; - - if (root == NULL || cur == NULL || path == NULL || abs_path == NULL) - return; - - if (*path == '/' || *path == '~') { - /* 1) cd / 2) cd ~/ 3) cd ~ */ - n = snprintf(absolute_path, PATH_MAX, "%s%s", root, - *(path + 1) == '/' ? path + 2 : path + 1); - } else { - /* 1) cd foo/ */ - n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, path); - } - - if (n) - ; - - /* /home/urezki/../ftp/.. */ - if ((dot = strrchr(absolute_path, '.'))) - if (*(dot - 1) == '.' && *(dot + 1) == '\0') - strcat(absolute_path, "/"); - - /* - * Here we can have following combinations: - * 1) /home/urezki/../ftp/../ - * 2) /home/urezki/ - */ - while ((dot = strstr(absolute_path, "/../"))) { - char *s_pp = NULL; - - if (dot == absolute_path) - s_pp = dot; - else - s_pp = (dot - 1); - - while (s_pp != absolute_path && *s_pp != '/') - s_pp--; - - *(s_pp + 1) = '\0'; - - snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); - snprintf(absolute_path, PATH_MAX, "%s", tmp_path); - } - - snprintf(abs_path, PATH_MAX, "%s", absolute_path); -} - static int -is_path_ok(struct connection *conn) +convert_path_to_abs_and_check(struct connection *conn) { + char abs_path[PATH_MAX] = {'\0'}; char *cmd_arg; struct stat st; int ret; cmd_arg = strchr(conn->recv_buf, ' '); - if (cmd_arg == NULL) - goto fail; + if (cmd_arg) + cmd_arg += 1; - cmd_arg += 1; - ret = build_full_path(conn->root_dir, conn->curr_dir, cmd_arg); + /* + * We may pass NULL as cmd_path argument. In that case + * current directory of the user should be reported. + */ + ret = convert_to_absolute_path(conn->root_dir, + conn->curr_dir, cmd_arg, abs_path); if (ret < 0) goto fail; /* check symbolic links */ - if (stat(cmd_arg, &st) != -1) { - if (!S_ISLNK(st.st_mode)) { - char buf[1024] = {'\0'}; - int len; - - len = readlink(cmd_arg, buf, sizeof(buf) - 1); - if (len != -1) { - buf[len] = '\0'; - *cmd_arg = '\0'; - strcat(cmd_arg, buf); - } - } - } - - if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) - return 1; - -fail: - return 0; -} - -static int -check_abs_path(const char *root_dir, char *abs_path) -{ - struct stat st; - - /* check for symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } - if (!strncmp(abs_path, root_dir, strlen(root_dir))) + if (!strncmp(abs_path, conn->root_dir, strlen(conn->root_dir))) { + char cmd[MAX_CMD_LEN] = {'\0'}; + int i = 0; + + /* get command name */ + for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { + if (i < (sizeof(cmd) - 1)) + cmd[i] = conn->recv_buf[i]; + } + + snprintf(conn->recv_buf, PATH_MAX - i, "%s %s", cmd, abs_path); + return 1; + } +fail: return 0; } static void cmd_feat(void *srv, struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(void *srv, struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); FLAG_CLEAR(conn->c_flags, C_AUTH); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { - char *user_name = NULL; + char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(void *srv, struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); if (FLAG_QUERY(conn->c_flags, C_AUTH)) return; p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); - if (p_crypt != NULL) { - if (!strcmp(p_crypt, p->pw_passwd)) { + if (p_crypt) { + if (!strcmp(p_crypt, p->pw_passwd)) FLAG_SET(conn->c_flags, C_AUTH); - } else { - /* checking shadow pass */ - p_shadow = getspnam(conn->user_name); - if (p_shadow != NULL) - p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); - if (p_crypt != NULL) - if (!strcmp(p_crypt, p_shadow->sp_pwdp)) - FLAG_SET(conn->c_flags, C_AUTH); - } + } else { + /* checking shadow pass */ + p_shadow = getspnam(conn->user_name); + if (p_shadow) + p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); + + if (p_crypt) + if (!strcmp(p_crypt, p_shadow->sp_pwdp)) + FLAG_SET(conn->c_flags, C_AUTH); } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); chdir(conn->root_dir); PRINT_DEBUG("%s user logged in\n", conn->user_name); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(void *srv, struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(void *srv, struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(void *srv, struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } - if (is_path_ok(conn)) { + if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &((ftpd *)srv)->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - fprintf(stdout, "--> error: %s -- %s.\n", l_file + 1, conn->recv_buf); } } else { - errno = ENOENT; - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + send_cmd(conn->sock_fd, 550, "%s", strerror(ENOENT)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } +#ifdef UPLOAD_SUPPORT +static void +cmd_stor(void *srv, struct connection *conn) +{ + transport *t; + + FUNC_ENTRY(); + + t = conn->transport; + if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { + if (convert_path_to_abs_and_check(conn)) { + char *l_file = strchr(conn->recv_buf, ' ') + 1; + + t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (t->local_fd != -1) { + FD_SET(t->socket, &((ftpd *) srv)->read_ready); + send_cmd(conn->sock_fd, 150, "Binary mode."); + FLAG_SET(t->t_flags, T_STOR); + } else { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + } + } + } else { + send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_dele(void *srv, struct connection *conn) +{ + char *l_file; + int ret; + + FUNC_ENTRY(); + + if (convert_path_to_abs_and_check(conn)) { + l_file = strchr(conn->recv_buf, ' ') + 1; + ret = unlink(l_file); + if (ret != -1) + send_cmd(conn->sock_fd, 250, "File deleted OK."); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } else { + errno = ENOENT; + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + + FUNC_EXIT_VOID(); +} + /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); - if (is_path_ok(conn)) { + if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); - if (is_path_ok(conn)) { + if (convert_path_to_abs_and_check(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } - -static void -cmd_stor(void *srv, struct connection *conn) -{ - transport *t; - - FUNC_ENTRY(); - - t = conn->transport; - if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - if (is_path_ok(conn)) { - char *l_file = strchr(conn->recv_buf, ' ') + 1; - - t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); - if (t->local_fd != -1) { - FD_SET(t->socket, &((ftpd *) srv)->read_ready); - send_cmd(conn->sock_fd, 150, "Binary mode."); - FLAG_SET(t->t_flags, T_STOR); - } else { - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); - } - } - } else { - send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); - } - - FUNC_EXIT_VOID(); -} +#endif /* UPLOAD_SUPPORT */ static void cmd_size(void *srv, struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; - if (is_path_ok(conn)) { + if (convert_path_to_abs_and_check(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void cmd_list(void *srv, struct connection *c) { - char path[PATH_MAX] = {'\0'}; + char *path; transport *t; - char *arg; int ret; t = c->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) goto use_port_or_pasv; - arg = strrchr(c->recv_buf, ' '); - if (arg == NULL || *(arg + 1) == '-') { - ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", c->curr_dir); - if (ret > 0) - t->l_opt.path[ret] = '\0'; + if (!convert_path_to_abs_and_check(c)) + goto no_such_file_or_dir; - FLAG_APPEND(t->l_opt.l_flags, L_FOLD); - goto start_ascii_mode; - } - - get_abs_path(c->root_dir, c->curr_dir, arg + 1, path); - ret = check_abs_path(c->root_dir, path); - if (ret == 0) - goto outside_chroot; + path = strchr(c->recv_buf, ' '); + BUG_ON(!path); + path += 1; ret = stat(path, &t->l_opt.st); if (ret != 0) - goto stat_call_error; + goto no_such_file_or_dir; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } -start_ascii_mode: send_cmd(c->sock_fd, 150, "ASCII MODE"); FD_SET(t->socket, &((ftpd *) srv)->write_ready); FLAG_SET(t->t_flags, T_LIST); return; use_port_or_pasv: send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); return; -outside_chroot: - errno = ENOENT; -stat_call_error: - send_cmd(c->sock_fd, 550, "%s", strerror(errno)); +no_such_file_or_dir: + send_cmd(c->sock_fd, 550, "%s", strerror(ENOENT)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void cmd_nlst(void *srv, struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); return cmd_list(srv, c); } -static void -cmd_dele(void *srv, struct connection *conn) -{ - char *l_file; - int ret; - - FUNC_ENTRY(); - - if (is_path_ok(conn)) { - l_file = strchr(conn->recv_buf, ' ') + 1; - ret = unlink(l_file); - if (ret != -1) - send_cmd(conn->sock_fd, 250, "File deleted OK."); - else - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - } else { - errno = ENOENT; - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - } - - FUNC_EXIT_VOID(); -} - static void cmd_noop(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(void *srv, struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(void *srv, struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } +/* static void */ +/* cmd_mdtm(void *srv, struct connection *conn) */ +/* { */ +/* FUNC_ENTRY(); */ + +/* FUNC_EXIT_VOID(); */ +/* } */ + /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(void *srv, struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); - if (is_path_ok(conn)) { + if (convert_path_to_abs_and_check(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(void *srv, connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[MAX_CMD_LEN] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' or '\n' from the recv_buf */ i = str_strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < (sizeof(key) - 1)) key[i] = conn->recv_buf[i]; } /* * convert to apper case */ str_contac(key); entry = hash_lookup(((ftpd *) srv)->cmd_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(srv, conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { - { "USER", 1, cmd_user, 1, 0, 4 }, - { "PASS", 1, cmd_pass, 1, 0, 4 }, - { "PORT", 1, cmd_port, 1, 1, 4 }, - { "PASV", 0, cmd_pasv, 0, 1, 4 }, - { "LIST", 1, cmd_list, 1, 1, 4 }, - { "NLST", 1, cmd_nlst, 1, 1, 4 }, - { "CDUP", 0, cmd_cdup, 0, 1, 4 }, - { "RETR", 1, cmd_retr, 0, 1, 4 }, - { "SIZE", 1, cmd_size, 0, 1, 4 }, - { "NOOP", 0, cmd_noop, 0, 1, 4 }, - { "SYST", 0, cmd_syst, 0, 0, 4 }, - { "TYPE", 0, cmd_type, 0, 1, 4 }, - { "ABOR", 0, cmd_abor, 0, 1, 4 }, - { "STRU", 0, cmd_stru, 0, 1, 4 }, - { "QUIT", 0, cmd_quit, 0, 0, 4 }, - { "FEAT", 0, cmd_feat, 0, 0, 4 }, - { "HELP", 0, cmd_help, 0, 1, 4 }, + { "USER", 1, cmd_user, 1, 0, 4, 0 }, + { "PASS", 1, cmd_pass, 1, 0, 4, 0 }, + { "PORT", 1, cmd_port, 1, 1, 4, 0 }, + { "PASV", 0, cmd_pasv, 0, 1, 4, 0 }, + { "LIST", 1, cmd_list, 1, 1, 4, 1 }, + { "NLST", 1, cmd_nlst, 1, 1, 4, 1 }, + { "CDUP", 0, cmd_cdup, 0, 1, 4, 0 }, + /* { "MDTM", 1, cmd_mdtm, 0, 1, 4, 1 }, */ + { "RETR", 1, cmd_retr, 0, 1, 4, 1 }, + { "SIZE", 1, cmd_size, 0, 1, 4, 1 }, + { "NOOP", 0, cmd_noop, 0, 1, 4, 0 }, + { "SYST", 0, cmd_syst, 0, 0, 4, 1 }, + { "TYPE", 0, cmd_type, 0, 1, 4, 0 }, + { "ABOR", 0, cmd_abor, 0, 1, 4, 0 }, + { "STRU", 0, cmd_stru, 0, 1, 4, 1 }, + { "QUIT", 0, cmd_quit, 0, 0, 4, 0 }, + { "FEAT", 0, cmd_feat, 0, 0, 4, 0 }, + { "HELP", 0, cmd_help, 0, 1, 4, 0 }, #ifdef UPLOAD_SUPPORT - { "STOR", 0, cmd_stor, 0, 1, 4 }, - { "DELE", 1, cmd_dele, 0, 1, 4 }, - { "RMD", 1, cmd_rmd, 0, 1, 3 }, - { "MKD", 1, cmd_mkd, 0, 1, 3 }, + { "STOR", 0, cmd_stor, 0, 1, 4, 1 }, + { "DELE", 1, cmd_dele, 0, 1, 4, 1 }, + { "RMD", 1, cmd_rmd, 0, 1, 3, 1 }, + { "MKD", 1, cmd_mkd, 0, 1, 3, 1 }, #endif - { "ALLO", 0, cmd_allo, 0, 1, 4 }, - { "PWD", 0, cmd_pwd, 0, 1, 3 }, - { "CWD", 1, cmd_cwd, 0, 1, 3 }, - { " ", 0, NULL, 0, 0, 0 } + { "ALLO", 0, cmd_allo, 0, 1, 4, 0 }, + { "PWD", 0, cmd_pwd, 0, 1, 3, 0 }, + { "CWD", 1, cmd_cwd, 0, 1, 3, 0 }, + { " ", 0, NULL, 0, 0, 0, 0 } }; diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 7f5d5c8..406e9a0 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -36,728 +36,726 @@ print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * sftpd_probe(int argc, char **argv) { struct rlimit rlim; ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; ret = setrlimit(RLIMIT_CORE, &rlim); if (ret) PRINT_DEBUG("'setrlimit()' failed with error: %s\n", strerror(errno)); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_table = hash_create(100); if (sftpd->cmd_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&sftpd->client_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(struct ftpd *srv, int s) { struct connection *new = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { new = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new->c_atime = time(NULL); new->sock_fd = s; new->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new->transport = tr; TAILQ_INSERT_TAIL(&srv->client_list, new, entries); /* add new client's socket */ FD_SET(new->sock_fd, &(srv->read_ready)); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new); return new; } static void destroy_transport(struct ftpd *srv, connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(struct ftpd *srv, connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&srv->client_list, c, entries); destroy_transport(srv, conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(struct ftpd *srv, int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(srv, conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void sftpd_quit(struct ftpd *srv) { struct connection *c; TAILQ_FOREACH(c, &srv->client_list, entries) { destroy_connection(srv, c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } static void handle_pending_signals(struct ftpd *srv) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) sftpd_quit(srv); } static int wait_for_events(ftpd *srv, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = srv->read_ready; *w_fd = srv->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(struct ftpd *srv, int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &srv->client_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(struct ftpd *srv, fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; int n; FUNC_ENTRY(); TAILQ_FOREACH(c, &srv->client_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { n = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); if (n > 0) c->recv_buf[n] = '\0'; /* modify last access */ c->c_atime = time(NULL); parse_cmd(srv, c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(struct ftpd *srv) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(srv, c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(srv, c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void kill_non_active_clients() { - - - + /* TODO */ } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; ret = build_list_line(arg + 1, &t->l_opt.st, line, sizeof(line), is_nlst); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(struct ftpd *srv, fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed; FUNC_ENTRY(); processed = 0; TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; /* skip FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } static int do_main_loop(struct ftpd *s) { int n_ready = 0; fd_set r_fd; fd_set w_fd; while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(s, &r_fd, &w_fd, 60); /* process signals */ handle_pending_signals(s); /* process transfers */ process_transfers(s, &r_fd, &w_fd, &n_ready); /* process commands */ process_commands(s, &r_fd, &n_ready); kill_non_active_clients(); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(s, 10); process_clients_marked_as_destroy(s); /* accept new clients, if they are */ accept_connection(s, s->srv_socket, &r_fd, &n_ready); } return 0; } int main(int argc, char **argv) { struct ftpd *srv; srv = sftpd_probe(argc, argv); return do_main_loop(srv); }
urezki/sftpd
eda48e05973ffc1acf6a380a66a47cd810f7a39f
@MAINT: code cleanup plus some fixes
diff --git a/server/Makefile b/server/Makefile index 1a8bd01..64ea58e 100644 --- a/server/Makefile +++ b/server/Makefile @@ -1,19 +1,19 @@ # Mafifile CC = gcc CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DMEMORY_DEBUG -DUPLOAD_SUPPORT -std=c99 INCLUDE = -I./include -LIB = -lcrypt +LIB = -lcrypt -pthread BINARY = sftpd SRC = $(wildcard src/*.c) OBJ = $(subst .c,.o, $(SRC)) all: $(OBJ) $(CC) -o $(BINARY) $(OBJ) $(LIB) .c.o: $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $< clean: rm -rf $(OBJ) $(BINARY) diff --git a/server/include/cmds.h b/server/include/cmds.h index cd2ee35..bb8e291 100644 --- a/server/include/cmds.h +++ b/server/include/cmds.h @@ -1,16 +1,18 @@ #ifndef __CMDS_H__ #define __CMDS_H__ +#define MAX_CMD_LEN 10 + struct cmd_handler { - char cmd_name[10]; + char cmd_name[MAX_CMD_LEN]; char arg; - void (*cmd_handler)(struct connection *const); + void (*cmd_handler)(void *, struct connection *const); char need_root; int need_auth; char cmd_len; }; extern const struct cmd_handler cmd_table[]; -extern void parse_cmd(connection *conn); +extern void parse_cmd(void *, connection *conn); #endif /* __CMDS_H__ */ diff --git a/server/include/debug.h b/server/include/debug.h index 591a2fe..dbd8664 100644 --- a/server/include/debug.h +++ b/server/include/debug.h @@ -1,56 +1,64 @@ #ifndef __DEBUG_H__ #define __DEBUG_H__ +#include <errno.h> + /* just causes a Segmentation Fault */ #define BUG() (*(int *)0 = 0) -//#define __DEBUG_MSG__ -//#define __DEBUG_FUNC__ +#define __DEBUG_MSG__ +/* #define __DEBUG_FUNC__ */ #ifdef __DEBUG_MSG__ /* DEBUG MSG */ #define PRINT_DEBUG(fmt,arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); } while (0) #else #define PRINT_DEBUG(fmt,arg...) \ do { } while(0) #endif /* __DEBUG_MSG__ */ +#define handle_error_en(en, msg) \ + do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) + +#define handle_error(msg) \ + do { perror(msg); exit(EXIT_FAILURE); } while (0) + #define FATAL_ERROR(fmt, arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); \ exit(-1); } while (0) #ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ #define FUNC_ENTRY() do { \ fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_VOID() do { \ fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_INT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ __FUNCTION__, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_UINT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ __FUNCTION__, value, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_PTR(ptr) do { \ fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ __FUNCTION__, ptr); \ fflush(stdout); } while (0) #else #define FUNC_ENTRY() do { } while(0) #define FUNC_EXIT_VOID() do { } while(0) #define FUNC_EXIT_INT(value) do { } while(0) #define FUNC_EXIT_UINT(value) do { } while(0) #define FUNC_EXIT_PTR(ptr) do { } while(0) #endif /* __DEBUG_FUNC__ */ #endif /* __DEBUG_H__ */ diff --git a/server/include/mutex.h b/server/include/mutex.h new file mode 100644 index 0000000..a6c1df4 --- /dev/null +++ b/server/include/mutex.h @@ -0,0 +1,22 @@ +#ifndef __MUTEX_H__ +#define __MUTEX_H__ + +typedef pthread_mutex_t mutex_t; +typedef pthread_cond_t cond_t; + +/* condition wrappers */ +#define cond_wait_unlock_lock_mutex(c, m) pthread_cond_wait(&c, &m) +#define cond_send_signal(c) pthread_cond_signal(&c) + +#define INIT_CONDITION(cond) \ + do { \ + cond_t tmp = PTHREAD_COND_INITIALIZER; \ + cond = tmp; \ + } while (0) + +/* mutex wrappers */ +#define mutex_init(m, attr) pthread_mutex_init((m), (attr)) +#define mutex_lock(m) pthread_mutex_lock(m) +#define mutex_unlock(m) pthread_mutex_unlock(m) + +#endif /* __MUTEX_H__ */ diff --git a/server/include/sftpd.h b/server/include/sftpd.h index 764e5ae..bb4876b 100644 --- a/server/include/sftpd.h +++ b/server/include/sftpd.h @@ -1,80 +1,102 @@ #ifndef __FTPD_H__ #define __FTPD_H__ #define DATA_PORT 20 #define RECV_BUF_SIZE 4096 /* connection specific flags */ #define C_AUTH 0x00000001 #define C_KILL 0x00000002 /* states of the transport */ #define T_FREE 0x00000001 #define T_PORT 0x00000002 #define T_PASV 0x00000004 #define T_LIST 0x00000008 #define T_RETR 0x00000010 #define T_STOR 0x00000020 #define T_ACPT 0x00000040 /* accepting */ #define T_KILL 0x00000080 #define FLAG_SET(X,Y) (X = (X^X) | Y) #define FLAG_APPEND(X,Y) (X = (X | Y)) #define FLAG_QUERY(X,Y) (X & Y) #define FLAG_CLEAR(X,Y) (X &= ~Y) struct connection { char recv_buf[RECV_BUF_SIZE]; int recv_buf_len; char user_name[256]; char user_pass[256]; char root_dir[256]; char curr_dir[256]; int sock_fd; uid_t uid; gid_t gid; time_t c_atime; /* last access time*/ int c_flags; struct transport *transport; + struct data_channel { + struct sockaddr_in r_info; + struct stat st; + + int listen_socket; + int socket; + + int data_port; + + int local_fd; + off_t offset; + + /* state */ + int t_flags; + + /* + * for LIST/NLST cmd + */ + struct list_opt l_opt; + } dc; + TAILQ_ENTRY(connection) entries; }; struct transport { struct sockaddr_in r_info; struct stat st; int listen_socket; int socket; int data_port; int local_fd; off_t offset; /* state */ int t_flags; /* * for LIST/NLST cmd */ struct list_opt l_opt; }; struct ftpd { - struct hash *cmd_hash_table; + struct hash *cmd_table; unsigned int client_count; fd_set write_ready; fd_set read_ready; int srv_socket; + + /* all clients are linked to the list */ + TAILQ_HEAD(cl_list, connection) client_list; }; typedef struct connection connection; typedef struct transport transport; typedef struct ftpd ftpd; -extern struct ftpd *srv; - #endif /* __FTPD_H__ */ diff --git a/server/include/str.h b/server/include/str.h new file mode 100644 index 0000000..d75d9d5 --- /dev/null +++ b/server/include/str.h @@ -0,0 +1,10 @@ +#ifndef __STR_H__ +#define __STR_H__ + +extern void str_contac(char *); +extern size_t str_strlen(const char *); +extern size_t str_findss(const char *, const char *); +extern size_t str_removesfs(char *, const char *); +extern size_t str_strcspn(const char *, const char *); + +#endif diff --git a/server/include/workqueue.h b/server/include/workqueue.h new file mode 100644 index 0000000..92ee832 --- /dev/null +++ b/server/include/workqueue.h @@ -0,0 +1,45 @@ +#ifndef __WORKQUEUE_H__ +#define __WORKQUEUE_H__ + +#include <pthread.h> + +/* local */ +#include <list.h> +#include <mutex.h> + +enum { + WORK_STRUCT_PENDING_BIT = 0, + WORK_STRUCT_RUNNING_BIT = 1, + WORK_STRUCT_STOPPED_BIT = 2, + WORK_STRUCT_PENDING = (1 << WORK_STRUCT_PENDING_BIT), + WORK_STRUCT_RUNNING = (1 << WORK_STRUCT_RUNNING_BIT), + WORK_STRUCT_STOPPED = (1 << WORK_STRUCT_STOPPED_BIT), +}; + +struct work_struct; +typedef void (*work_func_t)(struct work_struct *work); + +struct work_struct { + work_func_t func; + void *data; + int flags; + + TAILQ_ENTRY(work_struct) entries; +}; + +struct workqueue_struct { + pthread_t thread; + const char *name; + mutex_t mutex; + cond_t cond; + TAILQ_HEAD(work_list, work_struct) list; +}; + +#define INIT_WORK(work, fn) \ + do { \ + work.func = fn; \ + work.data = NULL; \ + work.flags = 0; \ + } while (0) + +#endif /* __WORKQUEUE_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index 8210404..266ee4d 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,992 +1,998 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> +#include <str.h> static int -translate_path(const char *root, const char *cur, char *dst) +build_full_path(const char *root, const char *cur, char *dst) { char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL || dst == NULL) return -1; if (*dst == '/' || *dst == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", root, *(dst + 1) == '/' ? dst + 2 : dst + 1); } else { /* 1) cd foo/ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); } + if (n) + ; + /* /home/urezki/../ftp/.. */ if ((dot = strrchr(absolute_path, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(absolute_path, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(dst, PATH_MAX, "%s", absolute_path); return 0; } static void get_abs_path(const char *root, const char *cur, const char *path, char *abs_path) { char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL || path == NULL || abs_path == NULL) return; if (*path == '/' || *path == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", root, *(path + 1) == '/' ? path + 2 : path + 1); } else { /* 1) cd foo/ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, path); } + if (n) + ; + /* /home/urezki/../ftp/.. */ if ((dot = strrchr(absolute_path, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(absolute_path, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(abs_path, PATH_MAX, "%s", absolute_path); } -static char * -get_cmd_arg(struct connection *c, int pos) -{ - char *cmd_arg; - - if (pos == 0) - cmd_arg = strchr(c->recv_buf, ' '); /* first */ - else - cmd_arg = strrchr(c->recv_buf, ' '); /* last */ - - /* checks whether we have any args. */ - if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') - return NULL; - - return cmd_arg + 1; -} - static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; - cmd_arg = get_cmd_arg(conn, 1); + cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg == NULL) goto fail; - ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); + cmd_arg += 1; + ret = build_full_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static int check_abs_path(const char *root_dir, char *abs_path) { struct stat st; /* check for symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, root_dir, strlen(root_dir))) return 1; return 0; } static void -cmd_feat(struct connection *conn) +cmd_feat(void *srv, struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void -cmd_user(struct connection *conn) +cmd_user(void *srv, struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; - + FUNC_ENTRY(); - + + FLAG_CLEAR(conn->c_flags, C_AUTH); + if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { - char *user_name; - + char *user_name = NULL; + /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } - + send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void -cmd_pass(struct connection *conn) +cmd_pass(void *srv, struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); + if (FLAG_QUERY(conn->c_flags, C_AUTH)) + return; + p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; - conn->uid = p->pw_uid; - conn->gid = p->pw_gid; - - (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); - if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') - (void) strcat(conn->root_dir, "/"); - - (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); - if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') - (void) strcat(conn->curr_dir, "/"); - user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; - + p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { + conn->uid = p->pw_uid; + conn->gid = p->pw_gid; + + (void) strncpy(conn->root_dir, p->pw_dir, + sizeof(conn->root_dir)); + + if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') + (void) strcat(conn->root_dir, "/"); + + (void) strncpy(conn->curr_dir, p->pw_dir, + sizeof(conn->curr_dir)); + + if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') + (void) strcat(conn->curr_dir, "/"); + send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); - PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); + PRINT_DEBUG("%s user logged in\n", conn->user_name); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void -cmd_port(struct connection *conn) +cmd_port(void *srv, struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void -cmd_pasv(struct connection *conn) +cmd_pasv(void *srv, struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; - FD_SET(t->listen_socket, &srv->read_ready); + FD_SET(t->listen_socket, &((ftpd *)srv)->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void -cmd_retr(struct connection *conn) +cmd_retr(void *srv, struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); - FD_SET(t->socket, &srv->write_ready); + FD_SET(t->socket, &((ftpd *)srv)->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + fprintf(stdout, "--> error: %s -- %s.\n", l_file + 1, conn->recv_buf); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void -cmd_allo(struct connection *conn) +cmd_allo(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void -cmd_rmd(struct connection *conn) +cmd_rmd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void -cmd_mkd(struct connection *conn) +cmd_mkd(void *srv, struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void -cmd_stor(struct connection *conn) +cmd_stor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { - FD_SET(t->socket, &srv->read_ready); + FD_SET(t->socket, &((ftpd *) srv)->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void -cmd_size(struct connection *conn) +cmd_size(void *srv, struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void -cmd_list(struct connection *c) +cmd_list(void *srv, struct connection *c) { char path[PATH_MAX] = {'\0'}; transport *t; char *arg; int ret; t = c->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) goto use_port_or_pasv; arg = strrchr(c->recv_buf, ' '); if (arg == NULL || *(arg + 1) == '-') { ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", c->curr_dir); if (ret > 0) t->l_opt.path[ret] = '\0'; FLAG_APPEND(t->l_opt.l_flags, L_FOLD); goto start_ascii_mode; } get_abs_path(c->root_dir, c->curr_dir, arg + 1, path); ret = check_abs_path(c->root_dir, path); if (ret == 0) goto outside_chroot; ret = stat(path, &t->l_opt.st); if (ret != 0) goto stat_call_error; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } start_ascii_mode: send_cmd(c->sock_fd, 150, "ASCII MODE"); - FD_SET(t->socket, &srv->write_ready); + FD_SET(t->socket, &((ftpd *) srv)->write_ready); FLAG_SET(t->t_flags, T_LIST); return; use_port_or_pasv: send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); return; outside_chroot: errno = ENOENT; stat_call_error: send_cmd(c->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void -cmd_nlst(struct connection *c) +cmd_nlst(void *srv, struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); - return cmd_list(c); + return cmd_list(srv, c); } static void -cmd_dele(struct connection *conn) +cmd_dele(void *srv, struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void -cmd_noop(struct connection *conn) +cmd_noop(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void -cmd_syst(struct connection *conn) +cmd_syst(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void -cmd_type(struct connection *conn) +cmd_type(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void -cmd_abor(struct connection *conn) +cmd_abor(void *srv, struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void -cmd_help(struct connection *conn) +cmd_help(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void -cmd_stru(struct connection *conn) +cmd_stru(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void -cmd_quit(struct connection *conn) +cmd_quit(void *srv, struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void -cmd_pwd(struct connection *conn) +cmd_pwd(void *srv, struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void -cmd_cdup(struct connection *conn) +cmd_cdup(void *srv, struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void -cmd_cwd(struct connection *conn) +cmd_cwd(void *srv, struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void -parse_cmd(connection *conn) +parse_cmd(void *srv, connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; - char key[256] = {'\0'}; + char key[MAX_CMD_LEN] = {'\0'}; int i = 0; FUNC_ENTRY(); - /* - * remove '\r' and '\n' from the recv_buf. + /* + * remove '\r' or '\n' from the recv_buf */ - i = strcspn(conn->recv_buf, "\r\n"); + i = str_strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { - if (i < sizeof(key)) + if (i < (sizeof(key) - 1)) key[i] = conn->recv_buf[i]; } - entry = hash_lookup(srv->cmd_hash_table, key); + /* + * convert to apper case + */ + str_contac(key); + + entry = hash_lookup(((ftpd *) srv)->cmd_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } - h->cmd_handler(conn); + h->cmd_handler(srv, conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4 }, { "PASS", 1, cmd_pass, 1, 0, 4 }, { "PORT", 1, cmd_port, 1, 1, 4 }, { "PASV", 0, cmd_pasv, 0, 1, 4 }, { "LIST", 1, cmd_list, 1, 1, 4 }, { "NLST", 1, cmd_nlst, 1, 1, 4 }, { "CDUP", 0, cmd_cdup, 0, 1, 4 }, { "RETR", 1, cmd_retr, 0, 1, 4 }, { "SIZE", 1, cmd_size, 0, 1, 4 }, { "NOOP", 0, cmd_noop, 0, 1, 4 }, { "SYST", 0, cmd_syst, 0, 0, 4 }, { "TYPE", 0, cmd_type, 0, 1, 4 }, { "ABOR", 0, cmd_abor, 0, 1, 4 }, { "STRU", 0, cmd_stru, 0, 1, 4 }, { "QUIT", 0, cmd_quit, 0, 0, 4 }, { "FEAT", 0, cmd_feat, 0, 0, 4 }, { "HELP", 0, cmd_help, 0, 1, 4 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4 }, { "DELE", 1, cmd_dele, 0, 1, 4 }, { "RMD", 1, cmd_rmd, 0, 1, 3 }, { "MKD", 1, cmd_mkd, 0, 1, 3 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4 }, { "PWD", 0, cmd_pwd, 0, 1, 3 }, { "CWD", 1, cmd_cwd, 0, 1, 3 }, { " ", 0, NULL, 0, 0, 0 } }; diff --git a/server/src/ls.c b/server/src/ls.c index 6a5a2f4..84e1f2b 100644 --- a/server/src/ls.c +++ b/server/src/ls.c @@ -1,182 +1,185 @@ #define _ATFILE_SOURCE #include <fcntl.h> +#include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <dirent.h> #include <time.h> #include <errno.h> #include <debug.h> #include <mem.h> #define MAX_UID_LEN 5 #define MAX_GID_LEN 5 static char * get_perm(mode_t st_mode, char *perm) { int i; /* clean */ for (i = 0; i < 9; i++) *(perm + i) = '-'; *(perm + 0) = '?'; switch (st_mode & S_IFMT) { case S_IFDIR: *(perm + 0) = 'd'; break; case S_IFREG: *(perm + 0) = '-'; break; case S_IFLNK: *(perm + 0) = 'l'; break; case S_IFBLK: *(perm + 0) = 'b'; break; case S_IFCHR: *(perm + 0) = 'c'; break; case S_IFSOCK: *(perm + 0) = 's'; break; case S_IFIFO: *(perm + 0) = 'p'; break; } (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): (*(perm + 1) = '-'); (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): (*(perm + 2) = '-'); (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): (*(perm + 3) = '-'); (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): (*(perm + 4) = '-'); (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): (*(perm + 5) = '-'); (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): (*(perm + 6) = '-'); (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): (*(perm + 7) = '-'); (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): (*(perm + 8) = '-'); (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): (*(perm + 9) = '-'); *(perm + 10) = '\0'; return perm; } static int get_file_attr(DIR *d, const char *f_name, struct stat *st) { int dir_fd; int ret; if (d) { dir_fd = dirfd(d); if (dir_fd != -1) { ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); if (ret == 0) return 1; else PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); } else { PRINT_DEBUG("dirfd error: %s\n", strerror(errno)); } } return 0; } static struct dirent * get_dirent_entry(DIR *dir_name) { struct dirent *d = NULL; if (dir_name != NULL) { d = readdir(dir_name); if (d == NULL) { return NULL; } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { d = get_dirent_entry(dir_name); } } return d; } static int get_mtime(time_t time, char *mtime, int mtime_len) { const char *date_format = "%b %d %H:%M"; struct timeval c_time; struct tm *tm = NULL; if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { if (time > c_time.tv_sec || (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { date_format = "%b %d %Y"; } tm = localtime(&time); strftime(mtime, mtime_len - 1, date_format, tm); return 1; } return 0; } int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l) { char mtime[20] = {'\0'}; char perm[11] = {'\0'}; int ret = -1; if (!short_l) { /* Permissions */ (void) get_perm(st->st_mode, perm); /* time of last modification */ (void) get_mtime(st->st_mtime, mtime, sizeof(mtime)); /* build the line */ ret = snprintf(line, l_size - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", perm, (unsigned int) st->st_nlink, MAX_UID_LEN, st->st_uid, MAX_GID_LEN, st->st_gid, 10, st->st_size, mtime, name); } else { ret = snprintf(line, l_size - 1, "%s\r\n", name); } return ret; } char * get_file_list_chunk(DIR *dir, int nfiles, int short_list) { - struct dirent *d; + struct dirent *d = NULL; char line[400] = {'\0'}; - char *chunk; + char *chunk = NULL; int len = 0; if (nfiles > 0) { - chunk = (char *)calloc(nfiles * sizeof(line), sizeof(char)); + chunk = (char *) calloc(nfiles * sizeof(line), sizeof(char)); if (chunk == NULL) FATAL_ERROR("error: %s\n", strerror(errno)); - } - for (int i = 0; i < nfiles && nfiles > 0; i++) { - d = get_dirent_entry(dir); - if (d != NULL) { - struct stat st; - int ret; - - ret = get_file_attr(dir, d->d_name, &st); - if (ret) { - if (short_list == 0) { - len += build_list_line(d->d_name, &st, line, sizeof(line), 0); - } else { - len += build_list_line(d->d_name, &st, line, sizeof(line), 1); + for (int i = 0; i < nfiles; i++) { + d = get_dirent_entry(dir); + if (d != NULL) { + struct stat st; + int ret; + + ret = get_file_attr(dir, d->d_name, &st); + if (ret) { + if (short_list == 0) { + len += build_list_line(d->d_name, &st, line, sizeof(line), 0); + } else { + len += build_list_line(d->d_name, &st, line, sizeof(line), 1); + } + + /* attach to the chunk */ + (void) strcat(chunk, line); } - - /* attach to the chunk */ - (void) strcat(chunk, line); } } + + if (len > 0) + return chunk; } - if (len > 0) - return chunk; + if (chunk) + free(chunk); - free(chunk); return NULL; } diff --git a/server/src/mem.c b/server/src/mem.c index b620a02..a33094d 100644 --- a/server/src/mem.c +++ b/server/src/mem.c @@ -1,179 +1,180 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> /* local headers */ #include <debug.h> #include <list.h> /* * Head of the memory list, uses for memory debugging. */ static TAILQ_HEAD(mem_list, __mnode) mem_head = TAILQ_HEAD_INITIALIZER(mem_head); static u_long bytes_allocated; static u_long bytes_freed; struct __mnode { void *addr; size_t size; const char *file; const char *func; int line; /* * This holds the pointers to the next and * previous entries in the tail queue. */ TAILQ_ENTRY(__mnode) entries; }; /** * __calloc - allocates memory for an array of * nmemb elements of size bytes each and returns * a pointer to the allocated memory. * * @nmemb: number of elements; * @size: size of each element; * @file: name of the file where __calloc is called; * @func: name of the function where __calloc is called; * @line: the line number where __calloc is called. */ void * __calloc(size_t nmemb, size_t size, const char *file, const char *func, int line) { struct __mnode *m = calloc(1, sizeof(*m)); void *ptr = calloc(nmemb, size); m->size = size * nmemb; m->addr = ptr; m->file = file; m->func = func; m->line = line; bytes_allocated += m->size; TAILQ_INSERT_TAIL(&mem_head, m, entries); return ptr; } /** * __malloc - allocates size bytes and returns a * pointer to the allocated memory, and adds __mnode * to the memory list. * * @size: size of memory; * @file: name of the file where __malloc is called; * @func: name of the function where __malloc is called; * @line: the line number where __malloc is called. */ void * __malloc(size_t size, const char *file, const char *func, int line) { struct __mnode *m = calloc(1, sizeof(*m)); void *ptr = malloc(size); m->size = size; m->addr = ptr; m->file = file; m->func = func; m->line = line; bytes_allocated += size; TAILQ_INSERT_TAIL(&mem_head, m, entries); return ptr; } /** * __free - frees the memory space pointed to by ptr, * and removes __mndoe from the mem list, if ptr is NULL, * no operation is performed. * * @ptr: pointer to the allocated memory; * @file: name of the file where __free is called; * @func: name of the function where __free is called; * @line: the line number where __free is called. */ void __free(void *ptr, const char *file, const char *func, int line) { struct __mnode *item; int found = 0; TAILQ_FOREACH(item, &mem_head, entries) { if (item->addr == ptr) { bytes_allocated -= item->size; bytes_freed += item->size; TAILQ_REMOVE(&mem_head, item, entries); free(item->addr); free(item); found++; break; } } if (!found) { - PRINT_DEBUG("unallocated free of %p by %s in %s at line %d\n", ptr, func, file, line); + PRINT_DEBUG("unallocated free of %p by %s in %s at line %d\n", + ptr, func, file, line); BUG(); } } /** * __realloc - changes the size of the memory * block pointed to by ptr to size bytes. * * @old_addr: block of memory pointed to by old_addr; * @size: size of memory; * @file: name of the file where __realloc is called; * @func: name of the function where __realloc is called; * @line: the line number where __realloc is called. */ void * __realloc(void *old_addr, size_t size, const char *file, const char *func, int line) { void *new_addr = __malloc(size, file, func, line); if (new_addr && old_addr) { memcpy(new_addr, old_addr, size); __free(old_addr, file, func, line); } return new_addr; } /** * __strdup - returns a pointer to a new string which * is a duplicate of the string s. * * @str: string that will duplicate; * @file: name of the file where __strdup is called; * @func: name of the function where __strdup is called; * @line: the line number where __strdup is called. */ char * __strdup(const char *str, const char *file, const char *func, int line) { size_t len; char *new_str; len = strlen(str) + 1; /* +1 for '\0' */ new_str = __malloc(len, file, func, line); if (str && new_str) strncpy(new_str, str, len); return new_str; } /** * Returns information about how much * memory we are using at present. */ u_long __get_mem_status(void) { return bytes_allocated; } diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 4704f15..7f5d5c8 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,749 +1,763 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> #include <sys/time.h> #include <sys/resource.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <ls.h> #include <sftpd.h> +#include <workqueue.h> #include <cmds.h> #include <hash.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" -/* - * Head of the client list - */ -static TAILQ_HEAD(cli_list, connection) conn_list; - -/* global variable */ -struct ftpd *srv = NULL; - static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * -init_sftpd(int argc, char **argv) +sftpd_probe(int argc, char **argv) { struct rlimit rlim; ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; ret = setrlimit(RLIMIT_CORE, &rlim); if (ret) PRINT_DEBUG("'setrlimit()' failed with error: %s\n", strerror(errno)); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ - sftpd->cmd_hash_table = hash_create(100); - if (sftpd->cmd_hash_table == NULL) + sftpd->cmd_table = hash_create(100); + if (sftpd->cmd_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { - ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); + ret = hash_add(sftpd->cmd_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } - /* init some stuff */ - sftpd->client_count = 0; - sftpd->srv_socket = -1; - sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ - TAILQ_INIT(&conn_list); + TAILQ_INIT(&sftpd->client_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * -add_connection(int s) +add_connection(struct ftpd *srv, int s) { - struct connection *new_conn = NULL; + struct connection *new = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { - /* adding new client's socket */ - FD_SET(s, &(srv->read_ready)); - - new_conn = (connection *) calloc(1, sizeof(connection)); + new = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); - if (new_conn == NULL || tr == NULL) + if (new == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); - new_conn->c_atime = time(NULL); - new_conn->sock_fd = s; - new_conn->c_flags = 0; /* reset flag */ + new->c_atime = time(NULL); + new->sock_fd = s; + new->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); - new_conn->transport = tr; + new->transport = tr; - TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); + TAILQ_INSERT_TAIL(&srv->client_list, new, entries); + + /* add new client's socket */ + FD_SET(new->sock_fd, &(srv->read_ready)); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } - FUNC_EXIT_PTR(new_conn); - return new_conn; + FUNC_EXIT_PTR(new); + return new; } static void -destroy_transport(connection *conn) +destroy_transport(struct ftpd *srv, connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void -destroy_connection(connection *conn) +destroy_connection(struct ftpd *srv, connection *conn) { struct connection *c; FUNC_ENTRY(); - TAILQ_FOREACH(c, &conn_list, entries) { + TAILQ_FOREACH(c, &srv->client_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; - TAILQ_REMOVE(&conn_list, c, entries); - destroy_transport(conn); + TAILQ_REMOVE(&srv->client_list, c, entries); + destroy_transport(srv, conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void -accept_connection(int socket, fd_set *r_fd, int *n_ready) +accept_connection(struct ftpd *srv, int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); - conn = add_connection(conn_fd); + conn = add_connection(srv, conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void -check_received_signals() +sftpd_quit(struct ftpd *srv) { - if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { - struct connection *c; - - TAILQ_FOREACH(c, &conn_list, entries) { - destroy_connection(c); - } + struct connection *c; - unlink_pid_file(PID_FILE); - hash_destroy(srv->cmd_hash_table); - close(srv->srv_socket); - free(srv); - exit(1); /* finish up */ + TAILQ_FOREACH(c, &srv->client_list, entries) { + destroy_connection(srv, c); } + + unlink_pid_file(PID_FILE); + hash_destroy(srv->cmd_table); + close(srv->srv_socket); + free(srv); + exit(1); /* finish up */ +} + +static void +handle_pending_signals(struct ftpd *srv) +{ + if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) + sftpd_quit(srv); } static int -wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) +wait_for_events(ftpd *srv, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; - *r_fd = sftpd->read_ready; - *w_fd = sftpd->write_ready; + *r_fd = srv->read_ready; + *w_fd = srv->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ - TAILQ_FOREACH(c, &conn_list, entries) { + TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int -process_timeouted_sockets(int time_m) +process_timeouted_sockets(struct ftpd *srv, int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; - TAILQ_FOREACH(c, &conn_list, entries) { + TAILQ_FOREACH(c, &srv->client_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void -process_commands(fd_set *r_fd, int *n_ready) +process_commands(struct ftpd *srv, fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; + int n; FUNC_ENTRY(); - TAILQ_FOREACH(c, &conn_list, entries) { + TAILQ_FOREACH(c, &srv->client_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { - int read_count; + n = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); + if (n > 0) + c->recv_buf[n] = '\0'; - read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); - parse_cmd(c); + parse_cmd(srv, c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int -process_clients_marked_as_destroy(void) +process_clients_marked_as_destroy(struct ftpd *srv) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: - TAILQ_FOREACH(c, &conn_list, entries) { + TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { - destroy_connection(c); + destroy_connection(srv, c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { - destroy_transport(c); + destroy_transport(srv, c); processed++; } } FUNC_EXIT_INT(processed); return processed; +} + +static void +kill_non_active_clients() +{ + + + } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; ret = build_list_line(arg + 1, &t->l_opt.st, line, sizeof(line), is_nlst); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void -process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) +process_transfers(struct ftpd *srv, fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; - int processed = 0; + int processed; FUNC_ENTRY(); - TAILQ_FOREACH(c, &conn_list, entries) { + processed = 0; + + TAILQ_FOREACH(c, &srv->client_list, entries) { t = c->transport; - /* skip who is FREE, KILL, PORT or PASV */ + /* skip FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } -int main(int argc, char **argv) +static int +do_main_loop(struct ftpd *s) { + int n_ready = 0; fd_set r_fd; fd_set w_fd; - int n_ready; - - /* srv is global */ - srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ - n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); + n_ready = wait_for_events(s, &r_fd, &w_fd, 60); + + /* process signals */ + handle_pending_signals(s); - /* check signals */ - check_received_signals(); + /* process transfers */ + process_transfers(s, &r_fd, &w_fd, &n_ready); - /* deal with exist transfers */ - process_transfers(&r_fd, &w_fd, &n_ready); + /* process commands */ + process_commands(s, &r_fd, &n_ready); - /* process FTP's commands */ - process_commands(&r_fd, &n_ready); + kill_non_active_clients(); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ - process_timeouted_sockets(10); - process_clients_marked_as_destroy(); + process_timeouted_sockets(s, 10); + process_clients_marked_as_destroy(s); /* accept new clients, if they are */ - accept_connection(srv->srv_socket, &r_fd, &n_ready); + accept_connection(s, s->srv_socket, &r_fd, &n_ready); } return 0; } + +int main(int argc, char **argv) +{ + struct ftpd *srv; + + srv = sftpd_probe(argc, argv); + return do_main_loop(srv); +} diff --git a/server/src/sock_utils.c b/server/src/sock_utils.c index 745a747..0f0a3f9 100644 --- a/server/src/sock_utils.c +++ b/server/src/sock_utils.c @@ -1,490 +1,491 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <errno.h> /* local headers */ #include <debug.h> #include <sock_utils.h> #include <list.h> #include <mem.h> /** * send_data - sending a message to a socket, * return the number of characters sent, otherwise -1. * * @s: socket; * @buf: buffer where the message should be stored; * @len: length of the message; * @flags: flags which we passing to send. */ int send_data(int s, const void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { n = send(s, buf + total, len - total, MSG_NOSIGNAL); if (n < 0) { PRINT_DEBUG("Write to socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * recv_data - receive a message from a socket, * return the number of bytes received, or -1 * if an error obtained, also 0 will be recived * when the peer has performed an orderly shutdown. * * @s: socket; * @buf: buffer where the message will be stored; * @len: length of the message; - * @flags: flags which we passing to recv. + * @flags: flags passing to recv. */ int recv_data(int s, void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { n = recv(s, buf + total, len - total, MSG_NOSIGNAL); if (n <= 0) { PRINT_DEBUG("Read from socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n == 0) ? 0 : (n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * send_cmd - send a message to socket, but * also it is able to build format string * like printf. * * @s: socket; * @cmd: codes which ftp protocol uses; * @format: string that specifies how subsequent arguments are converted. */ void send_cmd(int s, const int cmd, const char *const format, ...) { char buf[256] = {'\0'}; char fmt[256] = {'\0'}; va_list args; int err; int i; FUNC_ENTRY(); snprintf(fmt, sizeof(fmt), "%03u %s\r\n", cmd, format); va_start(args, format); i = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); err = send_data(s, buf, i, 0); + if (err < 0) + ; FUNC_EXIT_VOID(); } /** * get_remote_info - get name of connected peer socket. * On success, zero is returned, otherwise -1. * * @s: socket; * @name: pointer which will contain some information. */ int get_remote_info(int s, struct sockaddr *name) { unsigned int sock_len = 0; int ret = 0; FUNC_ENTRY(); sock_len = sizeof(struct sockaddr); ret = getpeername(s, name, &sock_len); if (ret == -1) PRINT_DEBUG("getpeername failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ret); return ret; } /** * start_tcp_listen - starts listen a port number. * On success, listen socket is returned, otherwise -1. * * @port_number: port number which be listened; * @ip_ver: IPv4 or IPv6; * @backlog: maximum length the queue of pending, * connections may grow to. */ int start_tcp_listen(int port_number, int ip_ver, int backlog) { struct sockaddr_in serv_addr; int listenfd = 0; int retval = 0; int len = 0; FUNC_ENTRY(); if (ip_ver == 4) listenfd = get_ipv4_socket(); else if (ip_ver == 6) listenfd = get_ipv6_socket(); bzero(&serv_addr, sizeof(serv_addr)); if (listenfd != -1) { serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = (backlog) ? htons(port_number):0; if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET) len = sizeof(struct sockaddr_in); else if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET6) len = sizeof(struct sockaddr_in6); activate_reuseaddr(listenfd); retval = bind(listenfd, (struct sockaddr *)&serv_addr, len); if (retval != -1) { retval = listen(listenfd, backlog); if (retval < 0) { PRINT_DEBUG("listen failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } else { PRINT_DEBUG("bind failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } FUNC_EXIT_INT(listenfd); return listenfd; } /** * accept_timeout - accepting connection from the client. * On successful connected socked is returned, otherwise -1. * * @s: socket; * @r_addr: will contain info about remote host; * @sec: wait time. */ int accept_timeout(int s, struct sockaddr *r_addr, unsigned int sec) { int connect_fd = 0; int retval = 0; fd_set r_fd; fd_set w_fd; FUNC_ENTRY(); do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; if (sec > 0) { struct timeval time; time.tv_sec = sec; time.tv_usec = 0; retval = select(s + 1, &r_fd, &w_fd, NULL, &time); } else { retval = select(s + 1, &r_fd, &w_fd, NULL, NULL); } } while (retval < 0 && errno == EINTR); if (retval > 0) { socklen_t len = sizeof(*r_addr); connect_fd = accept(s, r_addr, &len); retval = (connect_fd > 0) ? connect_fd : -1; } else if (retval == 0) { PRINT_DEBUG("warning: accept timeout!\n"); retval = -1; } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } FUNC_EXIT_INT(retval); return retval; } /** * connect_timeout - connect to the client. * On success 0 is returned, otherwise -1. * * @s: socket; * @r_addr: information about remote client; * @sec: how much time we should wait. */ int connect_timeout(int s, struct sockaddr *r_addr, int sec) { struct sockaddr remote_addr; socklen_t sock_len = 0; int retval; FUNC_ENTRY(); if (sec > 0) activate_nonblock(s); sock_len = sizeof(remote_addr); retval = connect(s, r_addr, sock_len); if (retval < 0 && errno == EINPROGRESS) { struct timeval timeout; fd_set r_fd; fd_set w_fd; int n; do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; timeout.tv_sec = sec; timeout.tv_usec = 0; n = select(s + 1, &r_fd, &w_fd, NULL, &timeout); } while (n < 0 && errno == EINTR); if (n > 0) { /* We have to check the socket for error */ if (FD_ISSET(s, &r_fd) || (FD_ISSET(s, &w_fd))) retval = check_socket(s); } else if (n == 0) { PRINT_DEBUG("No data within %d seconds\n", sec); } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } } if (sec > 0) deactivate_nonblock(s); FUNC_EXIT_INT(retval); return retval; } /** * check_socket - checking a socket on error. * * @s: socket; */ int check_socket(int s) { socklen_t err_len = 0; int retval = 0; int error = 0; FUNC_ENTRY(); err_len = sizeof(error); retval = getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &err_len); if (retval < 0 || error != 0) PRINT_DEBUG("getsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(retval); return retval; } void close_socket(int s) { - int ret; - FUNC_ENTRY(); - - ret = shutdown(s, SHUT_RDWR); - if (ret) - PRINT_DEBUG("shutdown failed with errno %d: %s\n", - errno, strerror(errno)); - close(s); + + /* + * we don't care about return values, cause + * it doesn't make sense on this step, at all. + */ + (void) shutdown(s, SHUT_RDWR); + (void) close(s); FUNC_EXIT_VOID(); } void activate_nodelay(int s) { int ret = 0; int nodelay = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_cork(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_CORK, &on, sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_reuseaddr(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, - sizeof(on)); + sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } int get_ipv4_socket(void) { int ipv4_sock; FUNC_ENTRY(); ipv4_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (ipv4_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv4_sock); return ipv4_sock; } int get_ipv6_socket(void) { int ipv6_sock; FUNC_ENTRY(); ipv6_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); if (ipv6_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv6_sock); return ipv6_sock; } void activate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags |= O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void deactivate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags &= ~O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } int bytes_available(int sock) { int bytes; if (ioctl(sock, FIONREAD, &bytes) >= 0) return bytes; return 0; } diff --git a/server/src/str.c b/server/src/str.c new file mode 100644 index 0000000..b0b6f19 --- /dev/null +++ b/server/src/str.c @@ -0,0 +1,111 @@ +#include <stdio.h> + +void +str_contac(char *s) +{ + if (s == NULL) + return; + + while (*s) { + if (*s > 96 && *s < 123) + *s -= 32; + s++; + } +} + +size_t +str_strlen(const char *s) +{ + size_t i = 0; + + if (s) { + while (*(s++) != '\0') + i++; + } + + return i; +} + +/** + * a - target string + * b - string that contains reject characters + */ +size_t +str_strcspn(const char *a, const char *b) +{ + size_t a_len; + size_t b_len; + int i, j = 0; + + a_len = str_strlen(a); + b_len = str_strlen(b); + + if (!a_len || !b_len) + goto out; + + for (i = 0; i < a_len; i++) { + /* compare two strings here */ + for (j = 0; j < b_len; j++) { + if (a[i] != b[j]) + continue; + + goto out; + } + } + +out: + return i; +} + +/** + * returns index that points to the beginning + * of found string, otherwise zero + */ +size_t +str_findss(const char *a, const char *b) +{ + size_t a_len; + size_t b_len; + size_t index; + int i, j; + + a_len = str_strlen(a); + b_len = str_strlen(b); + + if (!a_len || !b_len) + goto not_found; + + for (i = 0; i < a_len; i++) { + if (a[i] == b[0]) { + index = i; + /* compare two strings here */ + for (j = 0; i < a_len; i++) { + if (a[i] == b[j]) { + if (++j == b_len) + return index; + } else { + i--; + break; + } + } + } + } + +not_found: + return 0; +} + +/** + * returns new string length, otherwise zero + */ +size_t +str_removesfs(char *a, const char *b) +{ + size_t i; + + i = str_findss(a, b); + if (i) + a[i] = '\0'; + + return i; +} diff --git a/server/src/workqueue.c b/server/src/workqueue.c new file mode 100644 index 0000000..d8bbe3b --- /dev/null +++ b/server/src/workqueue.c @@ -0,0 +1,128 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +/* local */ +#include <workqueue.h> +#include <debug.h> + +static void * +worker_thread(void *arg) +{ + struct workqueue_struct *wq; + struct work_struct *work; + int rv; + + wq = (struct workqueue_struct *) arg; + rv = pthread_detach(wq->thread); + if (rv) + handle_error("pthread_detach error\n"); + + while (1) { + mutex_lock(&wq->mutex); + if (!TAILQ_EMPTY(&wq->list)) { + work = TAILQ_FIRST(&wq->list); + work->flags = WORK_STRUCT_RUNNING; + TAILQ_REMOVE(&wq->list, work, entries); + } else { + /* wait, till signal wakes up */ + cond_wait_unlock_lock_mutex(wq->cond, wq->mutex); + } + mutex_unlock(&wq->mutex); + + if (work) { + work->func(work->data); + work = NULL; + } + } + + return NULL; +} + +struct workqueue_struct * +create_single_work_thread(const char *name) +{ + struct workqueue_struct *wq; + int rv; + + wq = calloc(1, sizeof(*wq)); + if (wq == NULL) + handle_error("calloc error\n"); + + wq->name = name; + INIT_CONDITION(wq->cond); + (void) mutex_init(&wq->mutex, NULL); + TAILQ_INIT(&wq->list); + + rv = pthread_create(&wq->thread, NULL, worker_thread, (void *) wq); + if (rv) + handle_error("pthread_create error\n"); + + return wq; +} + +static int +do_queue_work(struct workqueue_struct *wq, struct work_struct *work) +{ + int rv = 0; + + if (work->flags != WORK_STRUCT_PENDING) { + work->flags = WORK_STRUCT_PENDING; + TAILQ_INSERT_TAIL(&wq->list, work, entries); + rv = 1; + } + + return rv; +} + +/** + * returns 0 if @work is already in @wq, 1 otherwise + */ +int queue_work(struct workqueue_struct *wq, struct work_struct *work) +{ + int ret = 0; + + if (wq && work) { + mutex_lock(&wq->mutex); + ret = do_queue_work(wq, work); + if (ret) + cond_send_signal(wq->cond); + mutex_unlock(&wq->mutex); + } + + return ret; +} + +#ifdef TEST +static void +work_func_1(struct work_struct *work) +{ + fprintf(stdout, "--> %s:%d\n", __func__, __LINE__); +} + +static void +work_func_2(struct work_struct *work) +{ + fprintf(stdout, "--> %s:%d\n", __func__, __LINE__); +} + +int main(int argc, char **argv) +{ + struct workqueue_struct *wq; + struct work_struct work_1; + struct work_struct work_2; + + INIT_WORK(work_1, work_func_1); + INIT_WORK(work_2, work_func_2); + + wq = create_single_work_thread("worker/1"); + + while (1) { + (void) queue_work(wq, &work_1); + (void) queue_work(wq, &work_2); + usleep(700000); + } + + return 0; +} +#endif
urezki/sftpd
467027eabb4834ab9885e356c1850cd21822305b
@MAINT: use setrlimit to get core dump.
diff --git a/server/include/sock_utils.h b/server/include/sock_utils.h index 0403922..6ec038a 100644 --- a/server/include/sock_utils.h +++ b/server/include/sock_utils.h @@ -1,23 +1,24 @@ #ifndef __SOCK_UTILS_H__ #define __SOCK_UTILS_H__ typedef struct sockaddr SA; extern int send_data(int, const void *, int, int); extern int recv_data(int, void *, int, int); extern void send_cmd(int, const int, const char *const, ...); extern int get_remote_info(int, struct sockaddr *); extern int start_tcp_listen(int, int, int); extern int connect_timeout(int, struct sockaddr *, int); extern int accept_timeout(int, struct sockaddr *, unsigned int); extern void activate_nonblock(int); extern void deactivate_nonblock(int); extern void activate_nodelay(int); extern void activate_cork(int); extern void activate_reuseaddr(int); extern int get_ipv4_socket(void); extern int get_ipv6_socket(void); extern void close_socket(int); extern int check_socket(int); +extern int bytes_available(int); #endif diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 8eec591..4704f15 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,739 +1,749 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> +#include <sys/time.h> +#include <sys/resource.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { + struct rlimit rlim; ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); + rlim.rlim_cur = RLIM_INFINITY; + rlim.rlim_max = RLIM_INFINITY; + ret = setrlimit(RLIMIT_CORE, &rlim); + if (ret) + PRINT_DEBUG("'setrlimit()' failed with error: %s\n", strerror(errno)); + signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_hash_table = hash_create(100); if (sftpd->cmd_hash_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; + /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; - ioctl(c->sock_fd, FIONREAD, &avail_b); + avail_b = bytes_available(c->sock_fd); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; ret = build_list_line(arg + 1, &t->l_opt.st, line, sizeof(line), is_nlst); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_connection(srv->srv_socket, &r_fd, &n_ready); } return 0; } diff --git a/server/src/sock_utils.c b/server/src/sock_utils.c index 07701aa..745a747 100644 --- a/server/src/sock_utils.c +++ b/server/src/sock_utils.c @@ -1,478 +1,490 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> +#include <sys/ioctl.h> #include <errno.h> /* local headers */ #include <debug.h> #include <sock_utils.h> #include <list.h> #include <mem.h> /** * send_data - sending a message to a socket, * return the number of characters sent, otherwise -1. * * @s: socket; * @buf: buffer where the message should be stored; * @len: length of the message; * @flags: flags which we passing to send. */ int send_data(int s, const void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { n = send(s, buf + total, len - total, MSG_NOSIGNAL); if (n < 0) { PRINT_DEBUG("Write to socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * recv_data - receive a message from a socket, * return the number of bytes received, or -1 * if an error obtained, also 0 will be recived * when the peer has performed an orderly shutdown. * * @s: socket; * @buf: buffer where the message will be stored; * @len: length of the message; * @flags: flags which we passing to recv. */ int recv_data(int s, void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { n = recv(s, buf + total, len - total, MSG_NOSIGNAL); if (n <= 0) { PRINT_DEBUG("Read from socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n == 0) ? 0 : (n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * send_cmd - send a message to socket, but * also it is able to build format string * like printf. * * @s: socket; * @cmd: codes which ftp protocol uses; * @format: string that specifies how subsequent arguments are converted. */ void send_cmd(int s, const int cmd, const char *const format, ...) { char buf[256] = {'\0'}; char fmt[256] = {'\0'}; va_list args; int err; int i; FUNC_ENTRY(); snprintf(fmt, sizeof(fmt), "%03u %s\r\n", cmd, format); va_start(args, format); i = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); err = send_data(s, buf, i, 0); FUNC_EXIT_VOID(); } /** * get_remote_info - get name of connected peer socket. * On success, zero is returned, otherwise -1. * * @s: socket; * @name: pointer which will contain some information. */ int get_remote_info(int s, struct sockaddr *name) { unsigned int sock_len = 0; int ret = 0; FUNC_ENTRY(); sock_len = sizeof(struct sockaddr); ret = getpeername(s, name, &sock_len); if (ret == -1) PRINT_DEBUG("getpeername failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ret); return ret; } /** * start_tcp_listen - starts listen a port number. * On success, listen socket is returned, otherwise -1. * * @port_number: port number which be listened; * @ip_ver: IPv4 or IPv6; * @backlog: maximum length the queue of pending, * connections may grow to. */ int start_tcp_listen(int port_number, int ip_ver, int backlog) { struct sockaddr_in serv_addr; int listenfd = 0; int retval = 0; int len = 0; FUNC_ENTRY(); if (ip_ver == 4) listenfd = get_ipv4_socket(); else if (ip_ver == 6) listenfd = get_ipv6_socket(); bzero(&serv_addr, sizeof(serv_addr)); if (listenfd != -1) { serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = (backlog) ? htons(port_number):0; if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET) len = sizeof(struct sockaddr_in); else if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET6) len = sizeof(struct sockaddr_in6); activate_reuseaddr(listenfd); retval = bind(listenfd, (struct sockaddr *)&serv_addr, len); if (retval != -1) { retval = listen(listenfd, backlog); if (retval < 0) { PRINT_DEBUG("listen failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } else { PRINT_DEBUG("bind failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } FUNC_EXIT_INT(listenfd); return listenfd; } /** * accept_timeout - accepting connection from the client. * On successful connected socked is returned, otherwise -1. * * @s: socket; * @r_addr: will contain info about remote host; * @sec: wait time. */ int accept_timeout(int s, struct sockaddr *r_addr, unsigned int sec) { int connect_fd = 0; int retval = 0; fd_set r_fd; fd_set w_fd; FUNC_ENTRY(); do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; if (sec > 0) { struct timeval time; time.tv_sec = sec; time.tv_usec = 0; retval = select(s + 1, &r_fd, &w_fd, NULL, &time); } else { retval = select(s + 1, &r_fd, &w_fd, NULL, NULL); } } while (retval < 0 && errno == EINTR); if (retval > 0) { socklen_t len = sizeof(*r_addr); connect_fd = accept(s, r_addr, &len); retval = (connect_fd > 0) ? connect_fd : -1; } else if (retval == 0) { PRINT_DEBUG("warning: accept timeout!\n"); retval = -1; } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } FUNC_EXIT_INT(retval); return retval; } /** * connect_timeout - connect to the client. * On success 0 is returned, otherwise -1. * * @s: socket; * @r_addr: information about remote client; * @sec: how much time we should wait. */ int connect_timeout(int s, struct sockaddr *r_addr, int sec) { struct sockaddr remote_addr; socklen_t sock_len = 0; int retval; FUNC_ENTRY(); if (sec > 0) activate_nonblock(s); sock_len = sizeof(remote_addr); retval = connect(s, r_addr, sock_len); if (retval < 0 && errno == EINPROGRESS) { struct timeval timeout; fd_set r_fd; fd_set w_fd; int n; do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; timeout.tv_sec = sec; timeout.tv_usec = 0; n = select(s + 1, &r_fd, &w_fd, NULL, &timeout); } while (n < 0 && errno == EINTR); if (n > 0) { /* We have to check the socket for error */ if (FD_ISSET(s, &r_fd) || (FD_ISSET(s, &w_fd))) retval = check_socket(s); } else if (n == 0) { PRINT_DEBUG("No data within %d seconds\n", sec); } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } } if (sec > 0) deactivate_nonblock(s); FUNC_EXIT_INT(retval); return retval; } /** * check_socket - checking a socket on error. * * @s: socket; */ int check_socket(int s) { socklen_t err_len = 0; int retval = 0; int error = 0; FUNC_ENTRY(); err_len = sizeof(error); retval = getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &err_len); if (retval < 0 || error != 0) PRINT_DEBUG("getsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(retval); return retval; } void close_socket(int s) { int ret; FUNC_ENTRY(); ret = shutdown(s, SHUT_RDWR); if (ret) PRINT_DEBUG("shutdown failed with errno %d: %s\n", errno, strerror(errno)); close(s); FUNC_EXIT_VOID(); } void activate_nodelay(int s) { int ret = 0; int nodelay = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_cork(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_CORK, &on, sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_reuseaddr(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } int get_ipv4_socket(void) { int ipv4_sock; FUNC_ENTRY(); ipv4_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (ipv4_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv4_sock); return ipv4_sock; } int get_ipv6_socket(void) { int ipv6_sock; FUNC_ENTRY(); ipv6_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); if (ipv6_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv6_sock); return ipv6_sock; } void activate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags |= O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void deactivate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags &= ~O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } + +int +bytes_available(int sock) +{ + int bytes; + + if (ioctl(sock, FIONREAD, &bytes) >= 0) + return bytes; + + return 0; +}
urezki/sftpd
b9e9d05a5c4a7ea15da3ebb63ae69089a489b523
@MAINT: small fixes.
diff --git a/server/include/debug.h b/server/include/debug.h index 0aeece2..591a2fe 100644 --- a/server/include/debug.h +++ b/server/include/debug.h @@ -1,56 +1,56 @@ #ifndef __DEBUG_H__ #define __DEBUG_H__ /* just causes a Segmentation Fault */ #define BUG() (*(int *)0 = 0) -#define __DEBUG_MSG__ +//#define __DEBUG_MSG__ //#define __DEBUG_FUNC__ #ifdef __DEBUG_MSG__ /* DEBUG MSG */ #define PRINT_DEBUG(fmt,arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); } while (0) #else #define PRINT_DEBUG(fmt,arg...) \ do { } while(0) #endif /* __DEBUG_MSG__ */ #define FATAL_ERROR(fmt, arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); \ exit(-1); } while (0) #ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ #define FUNC_ENTRY() do { \ fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_VOID() do { \ fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_INT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ __FUNCTION__, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_UINT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ __FUNCTION__, value, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_PTR(ptr) do { \ fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ __FUNCTION__, ptr); \ fflush(stdout); } while (0) #else #define FUNC_ENTRY() do { } while(0) #define FUNC_EXIT_VOID() do { } while(0) #define FUNC_EXIT_INT(value) do { } while(0) #define FUNC_EXIT_UINT(value) do { } while(0) #define FUNC_EXIT_PTR(ptr) do { } while(0) #endif /* __DEBUG_FUNC__ */ #endif /* __DEBUG_H__ */ diff --git a/server/include/hash.h b/server/include/hash.h index eb6d13f..2d99e15 100644 --- a/server/include/hash.h +++ b/server/include/hash.h @@ -1,31 +1,31 @@ #ifndef __HASH_H__ #define __HASH_H__ #define KEY_SIZE 4096 typedef struct hash_entry { struct hash_entry *next; struct hash_entry *prev; time_t born_time; unsigned int index; char key[KEY_SIZE]; void *data; } hash_entry; typedef struct hash { - struct hash_entry **hash_table; unsigned int hash_size; + void *hash_table[0]; } hash; extern struct hash *hash_create(int); extern void hash_destroy(struct hash *); extern struct hash_entry *hash_lookup(struct hash *, const char *); extern int hash_add(struct hash *, const char *, void *); extern int hash_del(struct hash *, const char *); extern int hash_del_entry(struct hash *, struct hash_entry *); extern void hash_dump(struct hash *); extern int hash_resize(struct hash *, int); extern int hash_rehash(struct hash *); #endif /* __HASH_H__ */ diff --git a/server/include/ls.h b/server/include/ls.h index 6469128..12d4419 100644 --- a/server/include/ls.h +++ b/server/include/ls.h @@ -1,18 +1,19 @@ #ifndef __LS_H__ #define __LS_H__ /* flags for LIST cmd */ #define L_FOLD 0x00000001 /* list folder */ #define L_FILE 0x00000004 /* list one file */ #define L_NLST 0x00000008 /* list without ext. info */ struct list_opt { char path[PATH_MAX]; + struct stat st; void *target_dir; int l_flags; }; extern char *get_file_list_chunk(DIR *, int, int); extern int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l); #endif /* __LS_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index cfc2c8d..8210404 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -126,868 +126,867 @@ get_abs_path(const char *root, const char *cur, const char *path, char *abs_path snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(abs_path, PATH_MAX, "%s", absolute_path); } static char * get_cmd_arg(struct connection *c, int pos) { char *cmd_arg; if (pos == 0) cmd_arg = strchr(c->recv_buf, ' '); /* first */ else cmd_arg = strrchr(c->recv_buf, ' '); /* last */ /* checks whether we have any args. */ if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') return NULL; return cmd_arg + 1; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; cmd_arg = get_cmd_arg(conn, 1); if (cmd_arg == NULL) goto fail; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static int check_abs_path(const char *root_dir, char *abs_path) { struct stat st; /* check for symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, root_dir, strlen(root_dir))) return 1; return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; FD_SET(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void cmd_list(struct connection *c) { char path[PATH_MAX] = {'\0'}; - struct stat st; transport *t; char *arg; int ret; t = c->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) goto use_port_or_pasv; arg = strrchr(c->recv_buf, ' '); if (arg == NULL || *(arg + 1) == '-') { ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", c->curr_dir); if (ret > 0) t->l_opt.path[ret] = '\0'; FLAG_APPEND(t->l_opt.l_flags, L_FOLD); goto start_ascii_mode; } get_abs_path(c->root_dir, c->curr_dir, arg + 1, path); ret = check_abs_path(c->root_dir, path); if (ret == 0) goto outside_chroot; - ret = stat(path, &st); + ret = stat(path, &t->l_opt.st); if (ret != 0) goto stat_call_error; ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); if (ret > 0) t->l_opt.path[ret] = '\0'; - if (S_ISDIR(st.st_mode)) { + if (S_ISDIR(t->l_opt.st.st_mode)) { FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { FLAG_APPEND(t->l_opt.l_flags, L_FILE); } start_ascii_mode: send_cmd(c->sock_fd, 150, "ASCII MODE"); FD_SET(t->socket, &srv->write_ready); FLAG_SET(t->t_flags, T_LIST); return; use_port_or_pasv: send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); return; outside_chroot: errno = ENOENT; stat_call_error: send_cmd(c->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); return; } static void cmd_nlst(struct connection *c) { transport *t = c->transport; FLAG_SET(t->l_opt.l_flags, L_NLST); return cmd_list(c); } static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[256] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ i = strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < sizeof(key)) key[i] = conn->recv_buf[i]; } entry = hash_lookup(srv->cmd_hash_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4 }, { "PASS", 1, cmd_pass, 1, 0, 4 }, { "PORT", 1, cmd_port, 1, 1, 4 }, { "PASV", 0, cmd_pasv, 0, 1, 4 }, { "LIST", 1, cmd_list, 1, 1, 4 }, { "NLST", 1, cmd_nlst, 1, 1, 4 }, { "CDUP", 0, cmd_cdup, 0, 1, 4 }, { "RETR", 1, cmd_retr, 0, 1, 4 }, { "SIZE", 1, cmd_size, 0, 1, 4 }, { "NOOP", 0, cmd_noop, 0, 1, 4 }, { "SYST", 0, cmd_syst, 0, 0, 4 }, { "TYPE", 0, cmd_type, 0, 1, 4 }, { "ABOR", 0, cmd_abor, 0, 1, 4 }, { "STRU", 0, cmd_stru, 0, 1, 4 }, { "QUIT", 0, cmd_quit, 0, 0, 4 }, { "FEAT", 0, cmd_feat, 0, 0, 4 }, { "HELP", 0, cmd_help, 0, 1, 4 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4 }, { "DELE", 1, cmd_dele, 0, 1, 4 }, { "RMD", 1, cmd_rmd, 0, 1, 3 }, { "MKD", 1, cmd_mkd, 0, 1, 3 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4 }, { "PWD", 0, cmd_pwd, 0, 1, 3 }, { "CWD", 1, cmd_cwd, 0, 1, 3 }, { " ", 0, NULL, 0, 0, 0 } }; diff --git a/server/src/hash.c b/server/src/hash.c index f720bc0..3ab94f4 100644 --- a/server/src/hash.c +++ b/server/src/hash.c @@ -1,284 +1,280 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* local */ #include <hash.h> /* +-----+-----+-----+ */ /* | 0 | a | - | */ /* +-----+-----+-----+ */ /* | 1 | - | - | */ /* +-----+-----+-----+ */ /* | 2 | a | b | */ /* +-----+-----+-----+ */ /* | 3 | a | - | */ /* +-----+-----+-----+ */ /* | 4 | a | - | */ /* +-----+-----+-----+ */ /* | 5 | a | b | */ /* +-----+-----+-----+ */ /* | 6 | a | - | */ /* +-----+-----+-----+ */ /* | 7 | - | - | */ /* +-----+-----+-----+ */ /* | 8 | a | b | */ /* +-----+-----+-----+ */ /* | 9 | - | - | */ /* +-----+-----+-----+ */ #define POISONED ((void *) 0x00100100) /* hit poisoned address */ static inline unsigned int hash_function(const char *key, int table_size) { unsigned int h = 0; unsigned int g = 0; while (*key) { h = (h << 4U) + *key++; if ((g = h & 0xf0000000)) h ^= g >> 24U; h &= ~g; } return h % table_size; } int hash_del(struct hash *h, const char *key) { struct hash_entry *tmp; unsigned int index; if (h && key) { index = hash_function(key, h->hash_size); tmp = h->hash_table[index]; if (tmp == NULL) goto out; /* go through the list of collision */ for (; tmp; tmp = tmp->next) { if (!strcmp(tmp->key, key)) { int ret = hash_del_entry(h, tmp); if (ret) return 1; else goto out; } } } out: return 0; } int hash_del_entry(struct hash *h, struct hash_entry *entry) { if (h && entry) { if (entry->prev) entry->prev->next = entry->next; if (entry->next) entry->next->prev = entry->prev; /* if it's first, shift head */ if (entry->prev == NULL) h->hash_table[entry->index] = entry->next; free(entry); return 1; } return 0; } void hash_destroy(struct hash *h) { struct hash_entry *tmp; int i; if (h) { for (i = 0; h->hash_table[i] != POISONED; i++) { tmp = h->hash_table[i]; while (tmp) { (void) hash_del(h, tmp->key); tmp = h->hash_table[i]; } h->hash_table[i] = NULL; } - free(h->hash_table); free(h); } } int hash_add(struct hash *h, const char *key, void *data) { struct hash_entry *node; struct hash_entry *tmp; unsigned int index; if (h == NULL || key == NULL) goto out; index = hash_function(key, h->hash_size); node = (hash_entry *) calloc(1, sizeof(hash_entry)); if (node) { /* fill out the node */ (void) strncpy(node->key, key, sizeof(node->key)); node->born_time = time(NULL); node->index = index; node->data = data; node->next = NULL; node->prev = NULL; if (h->hash_table[index] == NULL) { h->hash_table[index] = node; } else { tmp = h->hash_table[index]; while (1) { if (!strcmp(tmp->key, key)) goto out_and_free; if (tmp->next) /* the latest */ tmp = tmp->next; else break; } /* add to queue */ tmp->next = node; node->next = NULL; node->prev = tmp; } /* success */ return 1; } out_and_free: free(node); out: return 0; } struct hash_entry * hash_lookup(struct hash *h, const char *key) { struct hash_entry *tmp; unsigned int index; if (h && key) { index = hash_function(key, h->hash_size); tmp = h->hash_table[index]; if (tmp == NULL) goto out; while (tmp) { if (!strcmp(tmp->key, key)) return tmp; tmp = tmp->next; } } out: return NULL; } struct hash * hash_create(int table_size) { struct hash *h; int i; if (table_size > 0) { - h = (struct hash *) calloc(1, sizeof(struct hash)); + h = (struct hash *) calloc(1, sizeof(struct hash) + sizeof(void *) * (table_size + 1)); if (h) { - h->hash_table = (hash_entry **) calloc(table_size + 1, sizeof(hash_entry *)); - if (h->hash_table) { - for (i = 0; i < table_size; i++) - h->hash_table[i] = NULL; - - h->hash_table[i] = (hash_entry *) POISONED; - h->hash_size = table_size; - return h; - } + for (i = 0; i < table_size; i++) + h->hash_table[i] = NULL; + + h->hash_table[i] = (hash_entry *) POISONED; + h->hash_size = table_size; + return h; } } return NULL; } int hash_resize(struct hash *h, int size) { /* TODO: implement it */ return 0; } int hash_rehash(struct hash *h) { /* * Algorithm of rehashing is quite simple. This routine does * following things: * * 1) picks up all entries, except for marked as NULL; * 2) generates new index according to the key; * 3) if new index is not equal to old one then make replacing. */ if (h) { for (int i = 0; h->hash_table[i] != (hash_entry *) POISONED && h->hash_table[i]; i++) { struct hash_entry *tmp = h->hash_table[i]; unsigned int index = hash_function(tmp->key, h->hash_size); /* rehash everyone who is in queue */ do { if (tmp->index != index) { int ret; ret = hash_add(h, tmp->key, tmp->data); if (ret) { ret = hash_del_entry(h, tmp); } } } while (tmp->next); } } return 0; } void hash_dump(struct hash *h) { struct hash_entry *n; int i; if (h) { for (i = 0; h->hash_table[i] != (hash_entry *) POISONED; i++) { n = h->hash_table[i]; if (n) { fprintf(stdout, "%d ", i); do { fprintf(stdout, "+"); } while ((n = n->next)); fprintf(stdout, "\n"); } else { fprintf(stdout, "%d -\n", i); } } } } diff --git a/server/src/sftpd.c b/server/src/sftpd.c index e9c96fb..8eec591 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,743 +1,739 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_hash_table = hash_create(100); if (sftpd->cmd_hash_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); - else - BUG(); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; - struct stat st; int is_nlst; char *list; int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { char *arg = strrchr(c->recv_buf, ' '); char line[400] = {'\0'}; - (void) stat(t->l_opt.path, &st); /* don't need !!!!!!!!! */ - ret = build_list_line(arg + 1, &st, line, sizeof(line), is_nlst); + ret = build_list_line(arg + 1, &t->l_opt.st, line, sizeof(line), is_nlst); if (ret > 0) (void) write(t->socket, line, ret); goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_connection(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
505858e8271018af1da829148e8c5e7988515064
@MAINT: implemented NLST command.
diff --git a/server/src/cmds.c b/server/src/cmds.c index cd878ca..cfc2c8d 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -123,873 +123,871 @@ get_abs_path(const char *root, const char *cur, const char *path, char *abs_path *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(abs_path, PATH_MAX, "%s", absolute_path); } static char * get_cmd_arg(struct connection *c, int pos) { char *cmd_arg; if (pos == 0) cmd_arg = strchr(c->recv_buf, ' '); /* first */ else cmd_arg = strrchr(c->recv_buf, ' '); /* last */ /* checks whether we have any args. */ if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') return NULL; return cmd_arg + 1; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; cmd_arg = get_cmd_arg(conn, 1); if (cmd_arg == NULL) goto fail; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static int check_abs_path(const char *root_dir, char *abs_path) { struct stat st; /* check for symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, root_dir, strlen(root_dir))) return 1; return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; FD_SET(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * If the pathname specifies a directory the server should * transfer a list of files in the specified directory. If * the pathname specifies a file then the server should send * current information on the file. A null argument implies * the user's current working or default directory. */ static void -cmd_list(struct connection *conn) +cmd_list(struct connection *c) { char path[PATH_MAX] = {'\0'}; - char line[400] = {'\0'}; struct stat st; transport *t; - int is_nlst; char *arg; int ret; - t = conn->transport; + t = c->transport; - if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - bzero((void *)&t->l_opt, sizeof(t->l_opt)); - if (!strncmp(conn->recv_buf, "NLST", 4)) - FLAG_SET(t->l_opt.l_flags, L_NLST); - - /* copy current folder at first, it may be changed below */ - (void) strncpy(t->l_opt.path, conn->curr_dir, sizeof(t->l_opt.path)); - - /* get last argument */ - arg = strrchr(conn->recv_buf, ' '); - if (arg) { - if (*(arg + 1) != '-') { /* LIST -al */ - get_abs_path(conn->root_dir, conn->curr_dir, arg + 1, path); - ret = check_abs_path(conn->root_dir, path); - if (ret) { - ret = stat(path, &st); - if (ret == 0) { - if (S_ISDIR(st.st_mode)) - FLAG_APPEND(t->l_opt.l_flags, L_FOLD); - else - FLAG_APPEND(t->l_opt.l_flags, L_FILE); - - (void) strncpy(t->l_opt.path, path, sizeof(t->l_opt.path)); - } - } - } else { - FLAG_APPEND(t->l_opt.l_flags, L_FOLD); - } - } else { - FLAG_APPEND(t->l_opt.l_flags, L_FOLD); - } + if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) + goto use_port_or_pasv; - if (FLAG_QUERY(t->l_opt.l_flags, (L_FOLD | L_FILE))) { - send_cmd(conn->sock_fd, 150, "ASCII MODE"); - if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { - is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); - ret = build_list_line(arg + 1, &st, line, sizeof(line), is_nlst); - if (ret > 0) - (void) write(t->socket, line, ret); + arg = strrchr(c->recv_buf, ' '); + if (arg == NULL || *(arg + 1) == '-') { + ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", c->curr_dir); + if (ret > 0) + t->l_opt.path[ret] = '\0'; - send_cmd(conn->sock_fd, 226, "ASCII Transfer complete"); - FLAG_APPEND(t->t_flags, T_KILL); - return; - } + FLAG_APPEND(t->l_opt.l_flags, L_FOLD); + goto start_ascii_mode; + } - FD_SET(t->socket, &srv->write_ready); - FLAG_SET(t->t_flags, T_LIST); - return; + get_abs_path(c->root_dir, c->curr_dir, arg + 1, path); + ret = check_abs_path(c->root_dir, path); + if (ret == 0) + goto outside_chroot; - } + ret = stat(path, &st); + if (ret != 0) + goto stat_call_error; - errno = ENOENT; - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); + ret = snprintf(t->l_opt.path, sizeof(t->l_opt.path) - 1, "%s", path); + if (ret > 0) + t->l_opt.path[ret] = '\0'; + + if (S_ISDIR(st.st_mode)) { + FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } else { - send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); + FLAG_APPEND(t->l_opt.l_flags, L_FILE); } + +start_ascii_mode: + send_cmd(c->sock_fd, 150, "ASCII MODE"); + FD_SET(t->socket, &srv->write_ready); + FLAG_SET(t->t_flags, T_LIST); + return; + +use_port_or_pasv: + send_cmd(c->sock_fd, 550, "sorry, use PORT or PASV first"); + return; + +outside_chroot: + errno = ENOENT; +stat_call_error: + send_cmd(c->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + return; +} + +static void +cmd_nlst(struct connection *c) +{ + transport *t = c->transport; + + FLAG_SET(t->l_opt.l_flags, L_NLST); + return cmd_list(c); } static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[256] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ i = strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < sizeof(key)) key[i] = conn->recv_buf[i]; } entry = hash_lookup(srv->cmd_hash_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4 }, { "PASS", 1, cmd_pass, 1, 0, 4 }, { "PORT", 1, cmd_port, 1, 1, 4 }, { "PASV", 0, cmd_pasv, 0, 1, 4 }, { "LIST", 1, cmd_list, 1, 1, 4 }, - { "NLST", 1, cmd_list, 1, 1, 4 }, + { "NLST", 1, cmd_nlst, 1, 1, 4 }, { "CDUP", 0, cmd_cdup, 0, 1, 4 }, { "RETR", 1, cmd_retr, 0, 1, 4 }, { "SIZE", 1, cmd_size, 0, 1, 4 }, { "NOOP", 0, cmd_noop, 0, 1, 4 }, { "SYST", 0, cmd_syst, 0, 0, 4 }, { "TYPE", 0, cmd_type, 0, 1, 4 }, { "ABOR", 0, cmd_abor, 0, 1, 4 }, { "STRU", 0, cmd_stru, 0, 1, 4 }, { "QUIT", 0, cmd_quit, 0, 0, 4 }, { "FEAT", 0, cmd_feat, 0, 0, 4 }, { "HELP", 0, cmd_help, 0, 1, 4 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4 }, { "DELE", 1, cmd_dele, 0, 1, 4 }, { "RMD", 1, cmd_rmd, 0, 1, 3 }, { "MKD", 1, cmd_mkd, 0, 1, 3 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4 }, { "PWD", 0, cmd_pwd, 0, 1, 3 }, { "CWD", 1, cmd_cwd, 0, 1, 3 }, { " ", 0, NULL, 0, 0, 0 } }; diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 7e5ae05..e9c96fb 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -84,648 +84,660 @@ create_pid_file(const char *full_path) if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_hash_table = hash_create(100); if (sftpd->cmd_hash_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } if (t->l_opt.target_dir) closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); else BUG(); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; + struct stat st; int is_nlst; char *list; + int ret; t = c->transport; is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { if (t->l_opt.target_dir == NULL) { t->l_opt.target_dir = opendir(t->l_opt.path); if (t->l_opt.target_dir == NULL) goto leave; } + } else if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { + char *arg = strrchr(c->recv_buf, ' '); + char line[400] = {'\0'}; + + (void) stat(t->l_opt.path, &st); /* don't need !!!!!!!!! */ + ret = build_list_line(arg + 1, &st, line, sizeof(line), is_nlst); + if (ret > 0) + (void) write(t->socket, line, ret); + + goto leave; } list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); return; } leave: send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_connection(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
1f9b091dc8bed709dd3d6bda178d096233bcce03
@MAINT: cmd_list is done.
diff --git a/server/include/ls.h b/server/include/ls.h index ca8072e..6469128 100644 --- a/server/include/ls.h +++ b/server/include/ls.h @@ -1,19 +1,18 @@ #ifndef __LS_H__ #define __LS_H__ /* flags for LIST cmd */ -#define L_CURR 0x00000001 /* list current folder */ -#define L_ABSL 0x00000002 /* list absolute folder */ +#define L_FOLD 0x00000001 /* list folder */ #define L_FILE 0x00000004 /* list one file */ -#define L_SHRT 0x00000008 /* list without ext. info */ +#define L_NLST 0x00000008 /* list without ext. info */ struct list_opt { + char path[PATH_MAX]; + void *target_dir; int l_flags; - void *dir; - int fd; }; extern char *get_file_list_chunk(DIR *, int, int); extern int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l); #endif /* __LS_H__ */ diff --git a/server/include/sftpd.h b/server/include/sftpd.h index 39d1051..764e5ae 100644 --- a/server/include/sftpd.h +++ b/server/include/sftpd.h @@ -1,81 +1,80 @@ #ifndef __FTPD_H__ #define __FTPD_H__ #define DATA_PORT 20 #define RECV_BUF_SIZE 4096 /* connection specific flags */ #define C_AUTH 0x00000001 #define C_KILL 0x00000002 /* states of the transport */ #define T_FREE 0x00000001 #define T_PORT 0x00000002 #define T_PASV 0x00000004 #define T_LIST 0x00000008 #define T_RETR 0x00000010 #define T_STOR 0x00000020 #define T_ACPT 0x00000040 /* accepting */ #define T_KILL 0x00000080 #define FLAG_SET(X,Y) (X = (X^X) | Y) #define FLAG_APPEND(X,Y) (X = (X | Y)) #define FLAG_QUERY(X,Y) (X & Y) #define FLAG_CLEAR(X,Y) (X &= ~Y) struct connection { char recv_buf[RECV_BUF_SIZE]; int recv_buf_len; char user_name[256]; char user_pass[256]; char root_dir[256]; char curr_dir[256]; int sock_fd; uid_t uid; gid_t gid; time_t c_atime; /* last access time*/ int c_flags; struct transport *transport; TAILQ_ENTRY(connection) entries; }; struct transport { struct sockaddr_in r_info; struct stat st; int listen_socket; int socket; int data_port; int local_fd; off_t offset; /* state */ int t_flags; /* * for LIST/NLST cmd */ struct list_opt l_opt; - DIR *target_dir; }; struct ftpd { struct hash *cmd_hash_table; unsigned int client_count; fd_set write_ready; fd_set read_ready; int srv_socket; }; typedef struct connection connection; typedef struct transport transport; typedef struct ftpd ftpd; extern struct ftpd *srv; #endif /* __FTPD_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index 4353206..cd878ca 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -115,921 +115,881 @@ get_abs_path(const char *root, const char *cur, const char *path, char *abs_path if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(abs_path, PATH_MAX, "%s", absolute_path); } static char * get_cmd_arg(struct connection *c, int pos) { char *cmd_arg; if (pos == 0) cmd_arg = strchr(c->recv_buf, ' '); /* first */ else cmd_arg = strrchr(c->recv_buf, ' '); /* last */ /* checks whether we have any args. */ if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') return NULL; return cmd_arg + 1; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; cmd_arg = get_cmd_arg(conn, 1); if (cmd_arg == NULL) goto fail; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static int check_abs_path(const char *root_dir, char *abs_path) { struct stat st; /* check for symbolic links */ if (stat(abs_path, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(abs_path, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *abs_path = '\0'; strcat(abs_path, buf); } } } if (!strncmp(abs_path, root_dir, strlen(root_dir))) return 1; return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; FD_SET(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } -/* /\* */ -/* * If the pathname specifies a directory or other group of files, */ -/* * the server should transfer a list of files in the specified */ -/* * directory. If the pathname specifies a file then the server */ -/* * should send current information on the file. A null argument */ -/* * implies the user's current working or default directory. */ -/* * The data transfer is over the data connection in type ASCII */ -/* * or type EBCDIC. */ -/* * */ -/* * See RFC-959 */ -/* *\/ */ -/* static void */ -/* cmd_list(struct connection *conn) */ -/* { */ -/* transport *t = conn->transport; */ -/* char *cmd_arg; */ -/* int ret; */ - -/* FUNC_ENTRY(); */ - -/* if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { */ -/* activate_nodelay(t->socket); */ -/* cmd_arg = get_cmd_arg(conn, 1); */ -/* if (cmd_arg) */ -/* /\* */ -/* * (gdb) p conn->recv_buf */ -/* * $1 = "LIST /home/ftp/-al /etc", '\0' <repeats 4072 times> */ -/* *\/ */ -/* ret = is_path_ok(conn); */ - -/* if (!cmd_arg || ret == 1) { */ -/* t->target_dir = opendir(!cmd_arg ? conn->curr_dir:cmd_arg); */ -/* if (t->target_dir) { */ -/* FD_SET(t->socket, &srv->write_ready); */ -/* FLAG_SET(t->t_flags, T_LIST); */ -/* send_cmd(conn->sock_fd, 150, "ASCII MODE"); */ -/* } */ -/* } */ - -/* if (!FLAG_QUERY(t->t_flags, T_LIST)) { */ -/* send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); */ -/* FLAG_APPEND(t->t_flags, T_KILL); */ -/* } */ -/* } else { */ -/* send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); */ -/* } */ - -/* FUNC_EXIT_VOID(); */ -/* } */ - +/** + * If the pathname specifies a directory the server should + * transfer a list of files in the specified directory. If + * the pathname specifies a file then the server should send + * current information on the file. A null argument implies + * the user's current working or default directory. + */ static void cmd_list(struct connection *conn) { - char abs_path[PATH_MAX] = {'\0'}; + char path[PATH_MAX] = {'\0'}; + char line[400] = {'\0'}; struct stat st; transport *t; + int is_nlst; char *arg; int ret; t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - int list_curr_folder = -1; - int list_folder = -1; - int list_file = -1; + bzero((void *)&t->l_opt, sizeof(t->l_opt)); + if (!strncmp(conn->recv_buf, "NLST", 4)) + FLAG_SET(t->l_opt.l_flags, L_NLST); - arg = strrchr(conn->recv_buf, ' '); /* last */ + /* copy current folder at first, it may be changed below */ + (void) strncpy(t->l_opt.path, conn->curr_dir, sizeof(t->l_opt.path)); + + /* get last argument */ + arg = strrchr(conn->recv_buf, ' '); if (arg) { if (*(arg + 1) != '-') { /* LIST -al */ - get_abs_path(conn->root_dir, conn->curr_dir, arg + 1, abs_path); - ret = check_abs_path(conn->root_dir, abs_path); + get_abs_path(conn->root_dir, conn->curr_dir, arg + 1, path); + ret = check_abs_path(conn->root_dir, path); if (ret) { - ret = stat(abs_path, &st); + ret = stat(path, &st); if (ret == 0) { if (S_ISDIR(st.st_mode)) - list_folder = 1; + FLAG_APPEND(t->l_opt.l_flags, L_FOLD); else - list_file = 1; + FLAG_APPEND(t->l_opt.l_flags, L_FILE); + + (void) strncpy(t->l_opt.path, path, sizeof(t->l_opt.path)); } } } else { - list_curr_folder = 1; + FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } } else { - list_curr_folder = 1; + FLAG_APPEND(t->l_opt.l_flags, L_FOLD); } - if (list_folder == 1 || list_curr_folder == 1) { - t->target_dir = opendir(list_curr_folder == 1 ? conn->curr_dir:abs_path); - if (t->target_dir) { - FD_SET(t->socket, &srv->write_ready); - FLAG_SET(t->t_flags, T_LIST); - send_cmd(conn->sock_fd, 150, "ASCII MODE"); - } else { - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); - } - } else if (list_file == 1) { - char line[400] = {'\0'}; - + if (FLAG_QUERY(t->l_opt.l_flags, (L_FOLD | L_FILE))) { send_cmd(conn->sock_fd, 150, "ASCII MODE"); - ret = stat(abs_path, &st); - if (ret == 0) { - ret = build_list_line(arg + 1, &st, line, sizeof(line), 0); + if (FLAG_QUERY(t->l_opt.l_flags, L_FILE)) { + is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); + ret = build_list_line(arg + 1, &st, line, sizeof(line), is_nlst); if (ret > 0) (void) write(t->socket, line, ret); + + send_cmd(conn->sock_fd, 226, "ASCII Transfer complete"); + FLAG_APPEND(t->t_flags, T_KILL); + return; } - send_cmd(conn->sock_fd, ret > 0 ? 226:550, ret > 0 ? "Transfer complete.":strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); - } else { - errno = ENOENT; - send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - FLAG_APPEND(t->t_flags, T_KILL); + FD_SET(t->socket, &srv->write_ready); + FLAG_SET(t->t_flags, T_LIST); + return; + } + + errno = ENOENT; + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); } else { send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); } } static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[256] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ i = strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < sizeof(key)) key[i] = conn->recv_buf[i]; } entry = hash_lookup(srv->cmd_hash_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4 }, { "PASS", 1, cmd_pass, 1, 0, 4 }, { "PORT", 1, cmd_port, 1, 1, 4 }, { "PASV", 0, cmd_pasv, 0, 1, 4 }, { "LIST", 1, cmd_list, 1, 1, 4 }, + { "NLST", 1, cmd_list, 1, 1, 4 }, { "CDUP", 0, cmd_cdup, 0, 1, 4 }, { "RETR", 1, cmd_retr, 0, 1, 4 }, { "SIZE", 1, cmd_size, 0, 1, 4 }, { "NOOP", 0, cmd_noop, 0, 1, 4 }, { "SYST", 0, cmd_syst, 0, 0, 4 }, { "TYPE", 0, cmd_type, 0, 1, 4 }, { "ABOR", 0, cmd_abor, 0, 1, 4 }, { "STRU", 0, cmd_stru, 0, 1, 4 }, { "QUIT", 0, cmd_quit, 0, 0, 4 }, { "FEAT", 0, cmd_feat, 0, 0, 4 }, { "HELP", 0, cmd_help, 0, 1, 4 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4 }, { "DELE", 1, cmd_dele, 0, 1, 4 }, { "RMD", 1, cmd_rmd, 0, 1, 3 }, { "MKD", 1, cmd_mkd, 0, 1, 3 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4 }, { "PWD", 0, cmd_pwd, 0, 1, 3 }, { "CWD", 1, cmd_cwd, 0, 1, 3 }, { " ", 0, NULL, 0, 0, 0 } }; diff --git a/server/src/ls.c b/server/src/ls.c index 82e9fc8..6a5a2f4 100644 --- a/server/src/ls.c +++ b/server/src/ls.c @@ -1,183 +1,182 @@ #define _ATFILE_SOURCE #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <dirent.h> #include <time.h> #include <errno.h> #include <debug.h> #include <mem.h> #define MAX_UID_LEN 5 #define MAX_GID_LEN 5 static char * get_perm(mode_t st_mode, char *perm) { int i; /* clean */ for (i = 0; i < 9; i++) *(perm + i) = '-'; *(perm + 0) = '?'; switch (st_mode & S_IFMT) { case S_IFDIR: *(perm + 0) = 'd'; break; case S_IFREG: *(perm + 0) = '-'; break; case S_IFLNK: *(perm + 0) = 'l'; break; case S_IFBLK: *(perm + 0) = 'b'; break; case S_IFCHR: *(perm + 0) = 'c'; break; case S_IFSOCK: *(perm + 0) = 's'; break; case S_IFIFO: *(perm + 0) = 'p'; break; } (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): (*(perm + 1) = '-'); (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): (*(perm + 2) = '-'); (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): (*(perm + 3) = '-'); (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): (*(perm + 4) = '-'); (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): (*(perm + 5) = '-'); (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): (*(perm + 6) = '-'); (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): (*(perm + 7) = '-'); (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): (*(perm + 8) = '-'); (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): (*(perm + 9) = '-'); *(perm + 10) = '\0'; return perm; } static int get_file_attr(DIR *d, const char *f_name, struct stat *st) { int dir_fd; int ret; if (d) { dir_fd = dirfd(d); if (dir_fd != -1) { ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); if (ret == 0) return 1; else PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); } else { PRINT_DEBUG("dirfd error: %s\n", strerror(errno)); } } return 0; } static struct dirent * get_dirent_entry(DIR *dir_name) { struct dirent *d = NULL; if (dir_name != NULL) { d = readdir(dir_name); if (d == NULL) { return NULL; } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { d = get_dirent_entry(dir_name); } } return d; } static int get_mtime(time_t time, char *mtime, int mtime_len) { const char *date_format = "%b %d %H:%M"; struct timeval c_time; struct tm *tm = NULL; if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { if (time > c_time.tv_sec || (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { date_format = "%b %d %Y"; } tm = localtime(&time); strftime(mtime, mtime_len - 1, date_format, tm); return 1; } return 0; } int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l) { char mtime[20] = {'\0'}; char perm[11] = {'\0'}; int ret = -1; if (!short_l) { /* Permissions */ (void) get_perm(st->st_mode, perm); /* time of last modification */ (void) get_mtime(st->st_mtime, mtime, sizeof(mtime)); /* build the line */ ret = snprintf(line, l_size - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", perm, (unsigned int) st->st_nlink, MAX_UID_LEN, st->st_uid, MAX_GID_LEN, st->st_gid, 10, st->st_size, mtime, name); } else { ret = snprintf(line, l_size - 1, "%s\r\n", name); } return ret; } char * get_file_list_chunk(DIR *dir, int nfiles, int short_list) { struct dirent *d; char line[400] = {'\0'}; char *chunk; int len = 0; if (nfiles > 0) { chunk = (char *)calloc(nfiles * sizeof(line), sizeof(char)); if (chunk == NULL) FATAL_ERROR("error: %s\n", strerror(errno)); } for (int i = 0; i < nfiles && nfiles > 0; i++) { d = get_dirent_entry(dir); if (d != NULL) { struct stat st; int ret; ret = get_file_attr(dir, d->d_name, &st); if (ret) { if (short_list == 0) { len += build_list_line(d->d_name, &st, line, sizeof(line), 0); } else { len += build_list_line(d->d_name, &st, line, sizeof(line), 1); } /* attach to the chunk */ (void) strcat(chunk, line); } } } if (len > 0) return chunk; free(chunk); return NULL; } - diff --git a/server/src/sftpd.c b/server/src/sftpd.c index 9d823af..7e5ae05 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,722 +1,731 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_hash_table = hash_create(100); if (sftpd->cmd_hash_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } - closedir(t->target_dir); + if (t->l_opt.target_dir) + closedir(t->l_opt.target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); else BUG(); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void list_folder(struct connection *c) { struct transport *t; + int is_nlst; char *list; - FUNC_ENTRY(); - t = c->transport; + is_nlst = FLAG_QUERY(t->l_opt.l_flags, L_NLST); + + if (FLAG_QUERY(t->l_opt.l_flags, L_FOLD)) { + if (t->l_opt.target_dir == NULL) { + t->l_opt.target_dir = opendir(t->l_opt.path); + if (t->l_opt.target_dir == NULL) + goto leave; + } + } - list = get_file_list_chunk(t->target_dir, 300, 0); + list = get_file_list_chunk(t->l_opt.target_dir, 300, is_nlst); if (list) { send_data(t->socket, list, strlen(list), 0); free(list); - } else { - send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); - FLAG_APPEND(t->t_flags, T_KILL); + return; } - FUNC_EXIT_VOID(); +leave: + send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); + FLAG_APPEND(t->t_flags, T_KILL); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE, KILL, PORT or PASV */ if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd) && !FD_ISSET(t->listen_socket, r_fd)) continue; if (FLAG_QUERY(t->t_flags, T_LIST)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); list_folder(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { if (FD_ISSET(t->listen_socket, r_fd)) { t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); if (t->socket != -1) { /* we are in PASV mode */ activate_nonblock(t->socket); FD_CLR(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_PASV); close_socket(t->listen_socket); } else { /* * listen_socket will be cleaned and closed * by the 'destroy_transport' routine, don't * use FD_CLR here. */ send_cmd(c->sock_fd, 500, "%s", strerror(errno)); PRINT_DEBUG("%s\n", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } c->c_atime = time(NULL); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_RETR)) { if (FD_ISSET(t->socket, w_fd)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } } else if (FLAG_QUERY(t->t_flags, T_STOR)) { if (FD_ISSET(t->socket, r_fd)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_connection(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
36d1ce97ac4b20e168dd467972d7f6a959acb530
@MAINT: playing with cmd_list function, not finished yet.
diff --git a/server/include/ls.h b/server/include/ls.h index b376981..ca8072e 100644 --- a/server/include/ls.h +++ b/server/include/ls.h @@ -1,10 +1,19 @@ #ifndef __LS_H__ #define __LS_H__ -// File: ls.h -// Headers file -// Created: Mon Sep 25 17:27:02 UTC 2006 +/* flags for LIST cmd */ +#define L_CURR 0x00000001 /* list current folder */ +#define L_ABSL 0x00000002 /* list absolute folder */ +#define L_FILE 0x00000004 /* list one file */ +#define L_SHRT 0x00000008 /* list without ext. info */ + +struct list_opt { + int l_flags; + void *dir; + int fd; +}; extern char *get_file_list_chunk(DIR *, int, int); +extern int build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l); #endif /* __LS_H__ */ diff --git a/server/include/sftpd.h b/server/include/sftpd.h index 442239d..39d1051 100644 --- a/server/include/sftpd.h +++ b/server/include/sftpd.h @@ -1,85 +1,81 @@ #ifndef __FTPD_H__ #define __FTPD_H__ #define DATA_PORT 20 #define RECV_BUF_SIZE 4096 /* connection specific flags */ #define C_AUTH 0x00000001 #define C_KILL 0x00000002 /* states of the transport */ #define T_FREE 0x00000001 #define T_PORT 0x00000002 #define T_PASV 0x00000004 #define T_LIST 0x00000008 #define T_RETR 0x00000010 #define T_STOR 0x00000020 #define T_ACPT 0x00000040 /* accepting */ #define T_KILL 0x00000080 -/* flags for LIST cmd */ -#define L_CURR 0x00000001 /* list current folder */ -#define L_ABSL 0x00000002 /* list absolute folder */ -#define L_FILE 0x00000004 /* list one file */ - #define FLAG_SET(X,Y) (X = (X^X) | Y) #define FLAG_APPEND(X,Y) (X = (X | Y)) #define FLAG_QUERY(X,Y) (X & Y) #define FLAG_CLEAR(X,Y) (X &= ~Y) struct connection { char recv_buf[RECV_BUF_SIZE]; int recv_buf_len; char user_name[256]; char user_pass[256]; char root_dir[256]; char curr_dir[256]; int sock_fd; uid_t uid; gid_t gid; time_t c_atime; /* last access time*/ int c_flags; struct transport *transport; TAILQ_ENTRY(connection) entries; }; struct transport { struct sockaddr_in r_info; struct stat st; int listen_socket; int socket; int data_port; int local_fd; off_t offset; /* state */ int t_flags; /* * for LIST/NLST cmd */ + struct list_opt l_opt; DIR *target_dir; }; struct ftpd { struct hash *cmd_hash_table; unsigned int client_count; fd_set write_ready; fd_set read_ready; int srv_socket; }; typedef struct connection connection; typedef struct transport transport; typedef struct ftpd ftpd; extern struct ftpd *srv; #endif /* __FTPD_H__ */ diff --git a/server/src/cmds.c b/server/src/cmds.c index f750a91..4353206 100644 --- a/server/src/cmds.c +++ b/server/src/cmds.c @@ -1,889 +1,1035 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> +#include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> -#include <ls.h> static int translate_path(const char *root, const char *cur, char *dst) { char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL || dst == NULL) return -1; if (*dst == '/' || *dst == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", root, *(dst + 1) == '/' ? dst + 2 : dst + 1); } else { /* 1) cd foo/ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); } /* /home/urezki/../ftp/.. */ if ((dot = strrchr(absolute_path, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(absolute_path, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(dst, PATH_MAX, "%s", absolute_path); return 0; } +static void +get_abs_path(const char *root, const char *cur, const char *path, char *abs_path) +{ + char absolute_path[PATH_MAX] = {'\0'}; + char tmp_path[PATH_MAX] = {'\0'}; + char *dot; + int n; + + if (root == NULL || cur == NULL || path == NULL || abs_path == NULL) + return; + + if (*path == '/' || *path == '~') { + /* 1) cd / 2) cd ~/ 3) cd ~ */ + n = snprintf(absolute_path, PATH_MAX, "%s%s", root, + *(path + 1) == '/' ? path + 2 : path + 1); + } else { + /* 1) cd foo/ */ + n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, path); + } + + /* /home/urezki/../ftp/.. */ + if ((dot = strrchr(absolute_path, '.'))) + if (*(dot - 1) == '.' && *(dot + 1) == '\0') + strcat(absolute_path, "/"); + + /* + * Here we can have following combinations: + * 1) /home/urezki/../ftp/../ + * 2) /home/urezki/ + */ + while ((dot = strstr(absolute_path, "/../"))) { + char *s_pp = NULL; + + if (dot == absolute_path) + s_pp = dot; + else + s_pp = (dot - 1); + + while (s_pp != absolute_path && *s_pp != '/') + s_pp--; + + *(s_pp + 1) = '\0'; + + snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); + snprintf(absolute_path, PATH_MAX, "%s", tmp_path); + } + + snprintf(abs_path, PATH_MAX, "%s", absolute_path); +} + static char * get_cmd_arg(struct connection *c, int pos) { char *cmd_arg; if (pos == 0) cmd_arg = strchr(c->recv_buf, ' '); /* first */ else cmd_arg = strrchr(c->recv_buf, ' '); /* last */ /* checks whether we have any args. */ if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') return NULL; return cmd_arg + 1; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; cmd_arg = get_cmd_arg(conn, 1); if (cmd_arg == NULL) goto fail; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } +static int +check_abs_path(const char *root_dir, char *abs_path) +{ + struct stat st; + + /* check for symbolic links */ + if (stat(abs_path, &st) != -1) { + if (!S_ISLNK(st.st_mode)) { + char buf[1024] = {'\0'}; + int len; + + len = readlink(abs_path, buf, sizeof(buf) - 1); + if (len != -1) { + buf[len] = '\0'; + *abs_path = '\0'; + strcat(abs_path, buf); + } + } + } + + if (!strncmp(abs_path, root_dir, strlen(root_dir))) + return 1; + + return 0; +} + static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) FLAG_SET(conn->c_flags, C_AUTH); } } } } if (FLAG_QUERY(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int socket; int ret; int len; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { socket = get_ipv4_socket(); if (socket < 0) goto failed_with_errno; t->data_port = data_port; activate_reuseaddr(socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); ret = bind(socket, (SA *)&t->r_info, len); if (ret != 0) { close_socket(socket); goto failed_with_errno; } t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(socket, (SA *)&t->r_info, 5); if (ret != 0) { close_socket(socket); goto failed_with_errno; } /* we are in a port mode */ t->socket = socket; FLAG_SET(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *t; socklen_t len; int ret; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); if (listen_sock < 0) goto failed_with_errno; activate_reuseaddr(listen_sock); memset(&addr, 0, sizeof(addr)); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); ret = listen(listen_sock, 1); if (ret != 0) { close_socket(listen_sock); goto failed_with_errno; } /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); t->listen_socket = listen_sock; FD_SET(t->listen_socket, &srv->read_ready); FLAG_SET(t->t_flags, T_ACPT); goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); goto end; } failed_with_errno: send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); end: FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!FLAG_QUERY(t->t_flags, T_RETR)) FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } -/* - * If the pathname specifies a directory or other group of files, - * the server should transfer a list of files in the specified - * directory. If the pathname specifies a file then the server - * should send current information on the file. A null argument - * implies the user's current working or default directory. - * The data transfer is over the data connection in type ASCII - * or type EBCDIC. - * - * See RFC-959 - */ +/* /\* */ +/* * If the pathname specifies a directory or other group of files, */ +/* * the server should transfer a list of files in the specified */ +/* * directory. If the pathname specifies a file then the server */ +/* * should send current information on the file. A null argument */ +/* * implies the user's current working or default directory. */ +/* * The data transfer is over the data connection in type ASCII */ +/* * or type EBCDIC. */ +/* * */ +/* * See RFC-959 */ +/* *\/ */ +/* static void */ +/* cmd_list(struct connection *conn) */ +/* { */ +/* transport *t = conn->transport; */ +/* char *cmd_arg; */ +/* int ret; */ + +/* FUNC_ENTRY(); */ + +/* if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { */ +/* activate_nodelay(t->socket); */ +/* cmd_arg = get_cmd_arg(conn, 1); */ +/* if (cmd_arg) */ +/* /\* */ +/* * (gdb) p conn->recv_buf */ +/* * $1 = "LIST /home/ftp/-al /etc", '\0' <repeats 4072 times> */ +/* *\/ */ +/* ret = is_path_ok(conn); */ + +/* if (!cmd_arg || ret == 1) { */ +/* t->target_dir = opendir(!cmd_arg ? conn->curr_dir:cmd_arg); */ +/* if (t->target_dir) { */ +/* FD_SET(t->socket, &srv->write_ready); */ +/* FLAG_SET(t->t_flags, T_LIST); */ +/* send_cmd(conn->sock_fd, 150, "ASCII MODE"); */ +/* } */ +/* } */ + +/* if (!FLAG_QUERY(t->t_flags, T_LIST)) { */ +/* send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); */ +/* FLAG_APPEND(t->t_flags, T_KILL); */ +/* } */ +/* } else { */ +/* send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); */ +/* } */ + +/* FUNC_EXIT_VOID(); */ +/* } */ + static void cmd_list(struct connection *conn) { - transport *t = conn->transport; - char *cmd_arg; + char abs_path[PATH_MAX] = {'\0'}; + struct stat st; + transport *t; + char *arg; int ret; - FUNC_ENTRY(); + t = conn->transport; if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { - activate_nodelay(t->socket); - cmd_arg = get_cmd_arg(conn, 1); - if (cmd_arg) - /* - * (gdb) p conn->recv_buf - * $1 = "LIST /home/ftp/-al /etc", '\0' <repeats 4072 times> - */ - ret = is_path_ok(conn); + int list_curr_folder = -1; + int list_folder = -1; + int list_file = -1; + + arg = strrchr(conn->recv_buf, ' '); /* last */ + if (arg) { + if (*(arg + 1) != '-') { /* LIST -al */ + get_abs_path(conn->root_dir, conn->curr_dir, arg + 1, abs_path); + ret = check_abs_path(conn->root_dir, abs_path); + if (ret) { + ret = stat(abs_path, &st); + if (ret == 0) { + if (S_ISDIR(st.st_mode)) + list_folder = 1; + else + list_file = 1; + } + } + } else { + list_curr_folder = 1; + } + } else { + list_curr_folder = 1; + } - if (!cmd_arg || ret == 1) { - t->target_dir = opendir(!cmd_arg ? conn->curr_dir:cmd_arg); + if (list_folder == 1 || list_curr_folder == 1) { + t->target_dir = opendir(list_curr_folder == 1 ? conn->curr_dir:abs_path); if (t->target_dir) { FD_SET(t->socket, &srv->write_ready); FLAG_SET(t->t_flags, T_LIST); send_cmd(conn->sock_fd, 150, "ASCII MODE"); + } else { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + } + } else if (list_file == 1) { + char line[400] = {'\0'}; + + send_cmd(conn->sock_fd, 150, "ASCII MODE"); + ret = stat(abs_path, &st); + if (ret == 0) { + ret = build_list_line(arg + 1, &st, line, sizeof(line), 0); + if (ret > 0) + (void) write(t->socket, line, ret); } - } - if (!FLAG_QUERY(t->t_flags, T_LIST)) { + send_cmd(conn->sock_fd, ret > 0 ? 226:550, ret > 0 ? "Transfer complete.":strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + } else { + errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); FLAG_APPEND(t->t_flags, T_KILL); } } else { send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); } - - FUNC_EXIT_VOID(); } static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; /* if it's not FREE */ if (FLAG_QUERY(t->t_flags, T_FREE)) { FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } void parse_cmd(connection *conn) { const struct cmd_handler *h; struct hash_entry *entry; char key[256] = {'\0'}; int i = 0; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ i = strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[i] = '\0'; conn->recv_buf_len = i; /* get key, i.e. command name */ for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { if (i < sizeof(key)) key[i] = conn->recv_buf[i]; } entry = hash_lookup(srv->cmd_hash_table, key); if (entry) { h = (const struct cmd_handler *) entry->data; if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_VOID(); } const struct cmd_handler cmd_table[] = { { "USER", 1, cmd_user, 1, 0, 4 }, { "PASS", 1, cmd_pass, 1, 0, 4 }, { "PORT", 1, cmd_port, 1, 1, 4 }, { "PASV", 0, cmd_pasv, 0, 1, 4 }, { "LIST", 1, cmd_list, 1, 1, 4 }, { "CDUP", 0, cmd_cdup, 0, 1, 4 }, { "RETR", 1, cmd_retr, 0, 1, 4 }, { "SIZE", 1, cmd_size, 0, 1, 4 }, { "NOOP", 0, cmd_noop, 0, 1, 4 }, { "SYST", 0, cmd_syst, 0, 0, 4 }, { "TYPE", 0, cmd_type, 0, 1, 4 }, { "ABOR", 0, cmd_abor, 0, 1, 4 }, { "STRU", 0, cmd_stru, 0, 1, 4 }, { "QUIT", 0, cmd_quit, 0, 0, 4 }, { "FEAT", 0, cmd_feat, 0, 0, 4 }, { "HELP", 0, cmd_help, 0, 1, 4 }, #ifdef UPLOAD_SUPPORT { "STOR", 0, cmd_stor, 0, 1, 4 }, { "DELE", 1, cmd_dele, 0, 1, 4 }, { "RMD", 1, cmd_rmd, 0, 1, 3 }, { "MKD", 1, cmd_mkd, 0, 1, 3 }, #endif { "ALLO", 0, cmd_allo, 0, 1, 4 }, { "PWD", 0, cmd_pwd, 0, 1, 3 }, { "CWD", 1, cmd_cwd, 0, 1, 3 }, { " ", 0, NULL, 0, 0, 0 } }; diff --git a/server/src/ls.c b/server/src/ls.c index 12b1d26..82e9fc8 100644 --- a/server/src/ls.c +++ b/server/src/ls.c @@ -1,167 +1,183 @@ #define _ATFILE_SOURCE #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <dirent.h> #include <time.h> #include <errno.h> #include <debug.h> #include <mem.h> #define MAX_UID_LEN 5 #define MAX_GID_LEN 5 static char * get_perm(mode_t st_mode, char *perm) { int i; /* clean */ for (i = 0; i < 9; i++) *(perm + i) = '-'; *(perm + 0) = '?'; switch (st_mode & S_IFMT) { case S_IFDIR: *(perm + 0) = 'd'; break; case S_IFREG: *(perm + 0) = '-'; break; case S_IFLNK: *(perm + 0) = 'l'; break; case S_IFBLK: *(perm + 0) = 'b'; break; case S_IFCHR: *(perm + 0) = 'c'; break; case S_IFSOCK: *(perm + 0) = 's'; break; case S_IFIFO: *(perm + 0) = 'p'; break; } (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): (*(perm + 1) = '-'); (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): (*(perm + 2) = '-'); (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): (*(perm + 3) = '-'); (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): (*(perm + 4) = '-'); (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): (*(perm + 5) = '-'); (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): (*(perm + 6) = '-'); (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): (*(perm + 7) = '-'); (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): (*(perm + 8) = '-'); (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): (*(perm + 9) = '-'); *(perm + 10) = '\0'; return perm; } static int get_file_attr(DIR *d, const char *f_name, struct stat *st) { int dir_fd; int ret; - if (d) + if (d) { dir_fd = dirfd(d); - - if (d && dir_fd != -1) { - ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); - if (ret == 0) - return 1; - else - PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); + if (dir_fd != -1) { + ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); + if (ret == 0) + return 1; + else + PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); + } else { + PRINT_DEBUG("dirfd error: %s\n", strerror(errno)); + } } return 0; } static struct dirent * get_dirent_entry(DIR *dir_name) { struct dirent *d = NULL; if (dir_name != NULL) { d = readdir(dir_name); if (d == NULL) { return NULL; } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { d = get_dirent_entry(dir_name); } } return d; } static int get_mtime(time_t time, char *mtime, int mtime_len) { const char *date_format = "%b %d %H:%M"; struct timeval c_time; struct tm *tm = NULL; if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { if (time > c_time.tv_sec || (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { date_format = "%b %d %Y"; } tm = localtime(&time); strftime(mtime, mtime_len - 1, date_format, tm); return 1; } return 0; } +int +build_list_line(const char *name, struct stat *st, char *line, int l_size, int short_l) +{ + char mtime[20] = {'\0'}; + char perm[11] = {'\0'}; + int ret = -1; + + if (!short_l) { + /* Permissions */ + (void) get_perm(st->st_mode, perm); + /* time of last modification */ + (void) get_mtime(st->st_mtime, mtime, sizeof(mtime)); + /* build the line */ + ret = snprintf(line, l_size - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", + perm, (unsigned int) st->st_nlink, MAX_UID_LEN, st->st_uid, + MAX_GID_LEN, st->st_gid, 10, st->st_size, mtime, name); + } else { + ret = snprintf(line, l_size - 1, "%s\r\n", name); + } + + return ret; +} + char * get_file_list_chunk(DIR *dir, int nfiles, int short_list) { struct dirent *d; char line[400] = {'\0'}; char *chunk; int len = 0; if (nfiles > 0) { chunk = (char *)calloc(nfiles * sizeof(line), sizeof(char)); if (chunk == NULL) FATAL_ERROR("error: %s\n", strerror(errno)); } for (int i = 0; i < nfiles && nfiles > 0; i++) { d = get_dirent_entry(dir); if (d != NULL) { struct stat st; int ret; ret = get_file_attr(dir, d->d_name, &st); if (ret) { - char mtime[20] = {'\0'}; - char perm[11] = {'\0'}; - if (short_list == 0) { - /* Permissions */ - (void) get_perm(st.st_mode, perm); - /* time of last modification */ - (void) get_mtime(st.st_mtime, mtime, sizeof(mtime)); - /* build the line */ - len += snprintf(line, sizeof(line) - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", - perm, (unsigned int) st.st_nlink, MAX_UID_LEN, st.st_uid, - MAX_GID_LEN, st.st_gid, 10, st.st_size, mtime, d->d_name); + len += build_list_line(d->d_name, &st, line, sizeof(line), 0); } else { - len += snprintf(line, sizeof(line) - 1, "%s\r\n", d->d_name); + len += build_list_line(d->d_name, &st, line, sizeof(line), 1); } /* attach to the chunk */ (void) strcat(chunk, line); } } } if (len > 0) return chunk; free(chunk); return NULL; } + diff --git a/server/src/sftpd.c b/server/src/sftpd.c index fc324f3..9d823af 100644 --- a/server/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,538 +1,538 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> #include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> +#include <ls.h> #include <sftpd.h> #include <cmds.h> #include <hash.h> #include <mem.h> -#include <ls.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* * Create hash table with size 100, in spite of we * have approximately 29 FTP commands, by this way * we tend to avoid collisions. */ sftpd->cmd_hash_table = hash_create(100); if (sftpd->cmd_hash_table == NULL) FATAL_ERROR("error allocating memory\n"); /* adding to hash commands and their handlers */ for (int i = 0; cmd_table[i].cmd_handler; i++) { ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); if (ret == 0) FATAL_ERROR("error adding to the hash\n"); } /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!FLAG_QUERY(t->t_flags, T_FREE)) { /* listing */ if (FLAG_QUERY(t->t_flags, T_LIST)) { if (t->socket >= 0) { FD_CLR(t->socket, &srv->write_ready); } else { BUG(); } closedir(t->target_dir); } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { /* downloading or uploading */ if (t->socket >= 0) { if (FLAG_QUERY(t->t_flags, T_RETR)) FD_CLR(t->socket, &srv->write_ready); else FD_CLR(t->socket, &srv->read_ready); } else { BUG(); } if (t->local_fd >= 0) close(t->local_fd); else BUG(); } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { /* accepting */ if (t->listen_socket >= 0) { FD_CLR(t->listen_socket, &srv->read_ready); } else { BUG(); } close_socket(t->listen_socket); } if (t->socket >= 0) close_socket(t->socket); else BUG(); /* clean transport before next using */ bzero(t, sizeof(transport)); FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { FLAG_SET(c->c_flags, C_KILL); } else { if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (FLAG_QUERY(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; }
urezki/sftpd
b4bb79fb66a24870342019106c56fec162de258b
@MAINT: added debug, if fstatat fails.
diff --git a/server/src/ls.c b/server/src/ls.c index 3cebedf..12b1d26 100644 --- a/server/src/ls.c +++ b/server/src/ls.c @@ -1,165 +1,167 @@ #define _ATFILE_SOURCE #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/time.h> #include <dirent.h> #include <time.h> #include <errno.h> #include <debug.h> #include <mem.h> #define MAX_UID_LEN 5 #define MAX_GID_LEN 5 static char * get_perm(mode_t st_mode, char *perm) { int i; /* clean */ for (i = 0; i < 9; i++) *(perm + i) = '-'; *(perm + 0) = '?'; switch (st_mode & S_IFMT) { case S_IFDIR: *(perm + 0) = 'd'; break; case S_IFREG: *(perm + 0) = '-'; break; case S_IFLNK: *(perm + 0) = 'l'; break; case S_IFBLK: *(perm + 0) = 'b'; break; case S_IFCHR: *(perm + 0) = 'c'; break; case S_IFSOCK: *(perm + 0) = 's'; break; case S_IFIFO: *(perm + 0) = 'p'; break; } (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): (*(perm + 1) = '-'); (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): (*(perm + 2) = '-'); (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): (*(perm + 3) = '-'); (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): (*(perm + 4) = '-'); (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): (*(perm + 5) = '-'); (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): (*(perm + 6) = '-'); (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): (*(perm + 7) = '-'); (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): (*(perm + 8) = '-'); (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): (*(perm + 9) = '-'); *(perm + 10) = '\0'; return perm; } static int get_file_attr(DIR *d, const char *f_name, struct stat *st) { int dir_fd; int ret; if (d) dir_fd = dirfd(d); if (d && dir_fd != -1) { ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); if (ret == 0) return 1; + else + PRINT_DEBUG("fstatat error: %s\n", strerror(errno)); } return 0; } static struct dirent * get_dirent_entry(DIR *dir_name) { struct dirent *d = NULL; if (dir_name != NULL) { d = readdir(dir_name); if (d == NULL) { return NULL; } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { d = get_dirent_entry(dir_name); } } return d; } static int get_mtime(time_t time, char *mtime, int mtime_len) { const char *date_format = "%b %d %H:%M"; struct timeval c_time; struct tm *tm = NULL; if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { if (time > c_time.tv_sec || (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { date_format = "%b %d %Y"; } tm = localtime(&time); strftime(mtime, mtime_len - 1, date_format, tm); return 1; } return 0; } char * get_file_list_chunk(DIR *dir, int nfiles, int short_list) { struct dirent *d; char line[400] = {'\0'}; char *chunk; int len = 0; if (nfiles > 0) { chunk = (char *)calloc(nfiles * sizeof(line), sizeof(char)); if (chunk == NULL) FATAL_ERROR("error: %s\n", strerror(errno)); } for (int i = 0; i < nfiles && nfiles > 0; i++) { d = get_dirent_entry(dir); if (d != NULL) { struct stat st; int ret; ret = get_file_attr(dir, d->d_name, &st); if (ret) { char mtime[20] = {'\0'}; char perm[11] = {'\0'}; if (short_list == 0) { /* Permissions */ (void) get_perm(st.st_mode, perm); /* time of last modification */ (void) get_mtime(st.st_mtime, mtime, sizeof(mtime)); /* build the line */ len += snprintf(line, sizeof(line) - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", perm, (unsigned int) st.st_nlink, MAX_UID_LEN, st.st_uid, - MAX_GID_LEN, st.st_gid, 7, st.st_size, mtime, d->d_name); + MAX_GID_LEN, st.st_gid, 10, st.st_size, mtime, d->d_name); } else { len += snprintf(line, sizeof(line) - 1, "%s\r\n", d->d_name); } /* attach to the chunk */ (void) strcat(chunk, line); } } } if (len > 0) return chunk; free(chunk); return NULL; }
urezki/sftpd
e9900ebb6b3879487c0127c6c32952913c2b6943
@MAINT: uhhhh... a lot of chages. In short:
diff --git a/Makefile b/Makefile index 1a8bd01..e69de29 100644 --- a/Makefile +++ b/Makefile @@ -1,19 +0,0 @@ -# Mafifile - -CC = gcc -CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DMEMORY_DEBUG -DUPLOAD_SUPPORT -std=c99 -INCLUDE = -I./include -LIB = -lcrypt - -BINARY = sftpd -SRC = $(wildcard src/*.c) -OBJ = $(subst .c,.o, $(SRC)) - -all: $(OBJ) - $(CC) -o $(BINARY) $(OBJ) $(LIB) - -.c.o: - $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $< - -clean: - rm -rf $(OBJ) $(BINARY) diff --git a/include/cmds.h b/include/cmds.h deleted file mode 100644 index 032a159..0000000 --- a/include/cmds.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef __CMDS_H__ -#define __CMDS_H__ - -extern int parse_cmd(connection *conn); - -#endif /* __CMDS_H__ */ diff --git a/include/ls.h b/include/ls.h deleted file mode 100644 index 77659e0..0000000 --- a/include/ls.h +++ /dev/null @@ -1,19 +0,0 @@ -// File: ls.h -// Headers file -// Created: Mon Sep 25 17:27:02 UTC 2006 - -typedef struct __str_ -{ - char *f_name; /* file name */ - unsigned int f_len; /* file len */ - - uid_t uid; - gid_t gid; - unsigned int st_nlink; - off_t st_size; - time_t time; - mode_t mode; -} __str; - -/* prototip's */ -extern int do_list(connection *conn); diff --git a/server/Makefile b/server/Makefile new file mode 100644 index 0000000..1a8bd01 --- /dev/null +++ b/server/Makefile @@ -0,0 +1,19 @@ +# Mafifile + +CC = gcc +CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DMEMORY_DEBUG -DUPLOAD_SUPPORT -std=c99 +INCLUDE = -I./include +LIB = -lcrypt + +BINARY = sftpd +SRC = $(wildcard src/*.c) +OBJ = $(subst .c,.o, $(SRC)) + +all: $(OBJ) + $(CC) -o $(BINARY) $(OBJ) $(LIB) + +.c.o: + $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $< + +clean: + rm -rf $(OBJ) $(BINARY) diff --git a/server/include/cmds.h b/server/include/cmds.h new file mode 100644 index 0000000..cd2ee35 --- /dev/null +++ b/server/include/cmds.h @@ -0,0 +1,16 @@ +#ifndef __CMDS_H__ +#define __CMDS_H__ + +struct cmd_handler { + char cmd_name[10]; + char arg; + void (*cmd_handler)(struct connection *const); + char need_root; + int need_auth; + char cmd_len; +}; + +extern const struct cmd_handler cmd_table[]; +extern void parse_cmd(connection *conn); + +#endif /* __CMDS_H__ */ diff --git a/include/debug.h b/server/include/debug.h similarity index 100% rename from include/debug.h rename to server/include/debug.h diff --git a/server/include/hash.h b/server/include/hash.h new file mode 100644 index 0000000..eb6d13f --- /dev/null +++ b/server/include/hash.h @@ -0,0 +1,31 @@ +#ifndef __HASH_H__ +#define __HASH_H__ + +#define KEY_SIZE 4096 + +typedef struct hash_entry { + struct hash_entry *next; + struct hash_entry *prev; + time_t born_time; + + unsigned int index; + char key[KEY_SIZE]; + void *data; +} hash_entry; + +typedef struct hash { + struct hash_entry **hash_table; + unsigned int hash_size; +} hash; + +extern struct hash *hash_create(int); +extern void hash_destroy(struct hash *); +extern struct hash_entry *hash_lookup(struct hash *, const char *); +extern int hash_add(struct hash *, const char *, void *); +extern int hash_del(struct hash *, const char *); +extern int hash_del_entry(struct hash *, struct hash_entry *); +extern void hash_dump(struct hash *); +extern int hash_resize(struct hash *, int); +extern int hash_rehash(struct hash *); + +#endif /* __HASH_H__ */ diff --git a/include/list.h b/server/include/list.h similarity index 100% rename from include/list.h rename to server/include/list.h diff --git a/server/include/ls.h b/server/include/ls.h new file mode 100644 index 0000000..b376981 --- /dev/null +++ b/server/include/ls.h @@ -0,0 +1,10 @@ +#ifndef __LS_H__ +#define __LS_H__ + +// File: ls.h +// Headers file +// Created: Mon Sep 25 17:27:02 UTC 2006 + +extern char *get_file_list_chunk(DIR *, int, int); + +#endif /* __LS_H__ */ diff --git a/include/mem.h b/server/include/mem.h similarity index 100% rename from include/mem.h rename to server/include/mem.h diff --git a/include/sftpd.h b/server/include/sftpd.h similarity index 66% rename from include/sftpd.h rename to server/include/sftpd.h index 808f583..442239d 100644 --- a/include/sftpd.h +++ b/server/include/sftpd.h @@ -1,69 +1,85 @@ #ifndef __FTPD_H__ #define __FTPD_H__ #define DATA_PORT 20 #define RECV_BUF_SIZE 4096 /* connection specific flags */ #define C_AUTH 0x00000001 #define C_KILL 0x00000002 -/* transport specific flags */ +/* states of the transport */ #define T_FREE 0x00000001 #define T_PORT 0x00000002 #define T_PASV 0x00000004 #define T_LIST 0x00000008 #define T_RETR 0x00000010 #define T_STOR 0x00000020 -#define T_KILL 0x00000040 +#define T_ACPT 0x00000040 /* accepting */ +#define T_KILL 0x00000080 -#define SET_FLAG(X,Y) (X = (X^X) | Y) -#define QUERY_FLAG(X,Y) (X & Y) -#define CLEAR_FLAG(X,Y) (X &= ~Y) +/* flags for LIST cmd */ +#define L_CURR 0x00000001 /* list current folder */ +#define L_ABSL 0x00000002 /* list absolute folder */ +#define L_FILE 0x00000004 /* list one file */ + +#define FLAG_SET(X,Y) (X = (X^X) | Y) +#define FLAG_APPEND(X,Y) (X = (X | Y)) +#define FLAG_QUERY(X,Y) (X & Y) +#define FLAG_CLEAR(X,Y) (X &= ~Y) struct connection { char recv_buf[RECV_BUF_SIZE]; int recv_buf_len; char user_name[256]; char user_pass[256]; char root_dir[256]; char curr_dir[256]; int sock_fd; uid_t uid; gid_t gid; time_t c_atime; /* last access time*/ int c_flags; struct transport *transport; TAILQ_ENTRY(connection) entries; }; struct transport { struct sockaddr_in r_info; struct stat st; + int listen_socket; int socket; + int data_port; int local_fd; off_t offset; + /* state */ int t_flags; + + /* + * for LIST/NLST cmd + */ + DIR *target_dir; }; struct ftpd { + struct hash *cmd_hash_table; unsigned int client_count; fd_set write_ready; fd_set read_ready; int srv_socket; }; typedef struct connection connection; typedef struct transport transport; typedef struct ftpd ftpd; extern struct ftpd *srv; #endif /* __FTPD_H__ */ diff --git a/include/signal_ruling.h b/server/include/signal_ruling.h similarity index 100% rename from include/signal_ruling.h rename to server/include/signal_ruling.h diff --git a/include/sock_utils.h b/server/include/sock_utils.h similarity index 100% rename from include/sock_utils.h rename to server/include/sock_utils.h diff --git a/include/utils.h b/server/include/utils.h similarity index 100% rename from include/utils.h rename to server/include/utils.h diff --git a/src/cmds.c b/server/src/cmds.c similarity index 70% rename from src/cmds.c rename to server/src/cmds.c index 4db8b99..f750a91 100644 --- a/src/cmds.c +++ b/server/src/cmds.c @@ -1,894 +1,889 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> +#include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> +#include <hash.h> #include <mem.h> #include <ls.h> -static void cmd_user(struct connection *); -static void cmd_pass(struct connection *); -static void cmd_port(struct connection *); -static void cmd_pasv(struct connection *); -static void cmd_list(struct connection *); -static void cmd_cdup(struct connection *); -static void cmd_retr(struct connection *); -static void cmd_size(struct connection *); -static void cmd_noop(struct connection *); -static void cmd_syst(struct connection *); -static void cmd_type(struct connection *); -static void cmd_stru(struct connection *); -static void cmd_quit(struct connection *); -static void cmd_feat(struct connection *); -static void cmd_abor(struct connection *); -static void cmd_stor(struct connection *); -static void cmd_dele(struct connection *); -static void cmd_help(struct connection *); -static void cmd_allo(struct connection *); -static void cmd_pwd(struct connection *); -static void cmd_cwd(struct connection *); -static void cmd_rmd(struct connection *); -static void cmd_mkd(struct connection *); - -/* static void cmd_nlst(struct connection *); */ -/* static void cmd_mode(struct connection *); */ -/* static void cmd_mdtm(struct connection *); */ - -struct cmd_handler { - char cmd_name[10]; - char arg; - void (*cmd_handler)(struct connection *const); - char need_root; - char cmd_len; -}; - -static const struct cmd_handler cmd_table[] = -{ - { "user", 1, cmd_user, 1, 4 }, - { "pass", 1, cmd_pass, 1, 4 }, - { "port", 1, cmd_port, 1, 4 }, - { "pasv", 0, cmd_pasv, 0, 4 }, - { "list", 0, cmd_list, 1, 4 }, - { "cdup", 0, cmd_cdup, 0, 4 }, - { "retr", 1, cmd_retr, 0, 4 }, - { "size", 1, cmd_size, 0, 4 }, - { "noop", 0, cmd_noop, 0, 4 }, - { "syst", 0, cmd_syst, 0, 4 }, - { "type", 0, cmd_type, 0, 4 }, - { "abor", 0, cmd_abor, 0, 4 }, - { "stru", 0, cmd_stru, 0, 4 }, - { "quit", 0, cmd_quit, 0, 4 }, - { "feat", 0, cmd_feat, 0, 4 }, - { "help", 0, cmd_help, 0, 4 }, -// { "mdtm", 0, cmd_mdtm, 0, 4 }, /* not implemented */ -#ifdef UPLOAD_SUPPORT - { "stor", 0, cmd_stor, 0, 4 }, - { "dele", 1, cmd_dele, 0, 4 }, - { "rmd", 1, cmd_rmd, 0, 3 }, - { "mkd", 1, cmd_mkd, 0, 3 }, -#endif -// { "nlst", 0, cmd_nlst, 0, 4 }, /* not implemented */ -// { "mode", 0, cmd_mode, 0, 4 }, /* not implemented */ - { "allo", 0, cmd_allo, 0, 4 }, - { "pwd", 0, cmd_pwd, 0, 3 }, - { "cwd", 1, cmd_cwd, 0, 3 }, - { " ", 0, NULL, 0, 0 } -}; - static int translate_path(const char *root, const char *cur, char *dst) { char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL || dst == NULL) return -1; if (*dst == '/' || *dst == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", root, *(dst + 1) == '/' ? dst + 2 : dst + 1); } else { /* 1) cd foo/ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); } /* /home/urezki/../ftp/.. */ if ((dot = strrchr(absolute_path, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(absolute_path, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(dst, PATH_MAX, "%s", absolute_path); return 0; } +static char * +get_cmd_arg(struct connection *c, int pos) +{ + char *cmd_arg; + + if (pos == 0) + cmd_arg = strchr(c->recv_buf, ' '); /* first */ + else + cmd_arg = strrchr(c->recv_buf, ' '); /* last */ + + /* checks whether we have any args. */ + if (cmd_arg == NULL || *(cmd_arg + 1) == '\0') + return NULL; + + return cmd_arg + 1; +} + static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; - cmd_arg = strchr(conn->recv_buf, ' '); - if (cmd_arg == NULL || cmd_arg[1] == '\0') + cmd_arg = get_cmd_arg(conn, 1); + if (cmd_arg == NULL) goto fail; - /* get pointer to the arg */ - cmd_arg = cmd_arg + 1; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { - SET_FLAG(conn->c_flags, C_AUTH); + FLAG_SET(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { - SET_FLAG(conn->c_flags, C_AUTH); + FLAG_SET(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) - SET_FLAG(conn->c_flags, C_AUTH); + FLAG_SET(conn->c_flags, C_AUTH); } } } } - if (QUERY_FLAG(conn->c_flags, C_AUTH)) { + if (FLAG_QUERY(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; + int socket; int ret; - + int len; + FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); - if (QUERY_FLAG(t->t_flags, T_FREE)) { + if (FLAG_QUERY(t->t_flags, T_FREE) && ip_address) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); - + data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { - int len; - - t->socket = get_ipv4_socket(); + socket = get_ipv4_socket(); + if (socket < 0) + goto failed_with_errno; + t->data_port = data_port; - activate_reuseaddr(t->socket); - + activate_reuseaddr(socket); + t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; - + len = sizeof(t->r_info); - bind(t->socket, (SA *)&t->r_info, len); - + ret = bind(socket, (SA *)&t->r_info, len); + if (ret != 0) { + close_socket(socket); + goto failed_with_errno; + } + t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); - - ret = connect_timeout(t->socket, (SA *)&t->r_info, 5); - if (ret == 0) { - /* we are in a port mode */ - SET_FLAG(t->t_flags, T_PORT); - activate_nonblock(t->socket); - send_cmd(conn->sock_fd, 220, "PORT command successful"); - } else { - send_cmd(conn->sock_fd, 425, "Can't open data connection"); - PRINT_DEBUG("Can't connect to %s:%d\n", ip_address, data_port); + ret = connect_timeout(socket, (SA *)&t->r_info, 5); + if (ret != 0) { + close_socket(socket); + goto failed_with_errno; } + + /* we are in a port mode */ + t->socket = socket; + FLAG_SET(t->t_flags, T_PORT); + activate_nonblock(t->socket); + send_cmd(conn->sock_fd, 220, "PORT command successful"); + goto end; } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); + goto end; } - + +failed_with_errno: + send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); +end: FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; - transport *trans; + transport *t; socklen_t len; + int ret; FUNC_ENTRY(); - trans = conn->transport; - if (QUERY_FLAG(trans->t_flags, T_FREE)) { - memset(&addr, 0, sizeof(addr)); + t = conn->transport; + if (FLAG_QUERY(t->t_flags, T_FREE)) { listen_sock = get_ipv4_socket(); + if (listen_sock < 0) + goto failed_with_errno; + activate_reuseaddr(listen_sock); - + memset(&addr, 0, sizeof(addr)); + len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); - + addr.sin_port = 0; - bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); - + ret = bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); + if (ret != 0) { + close_socket(listen_sock); + goto failed_with_errno; + } + len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); - listen(listen_sock, 1); + ret = listen(listen_sock, 1); + if (ret != 0) { + close_socket(listen_sock); + goto failed_with_errno; + } - /* send that we are ready */ + /* we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); - /* - * listen_sock should be added to the poll, and checked by select, - * after that when socket is ready do accept. - */ - trans->socket = accept_timeout(listen_sock, (SA *)&trans->r_info, 5); - if (trans->socket != -1) { - /* we are in PASV mode */ - SET_FLAG(trans->t_flags, T_PASV); - activate_nonblock(trans->socket); - } else { - send_cmd(conn->sock_fd, 500, "Accepting error, sorry"); - PRINT_DEBUG("Accepting error. sorry\n"); - } - - /* we needn't listen further */ - close_socket(listen_sock); + t->listen_socket = listen_sock; + FD_SET(t->listen_socket, &srv->read_ready); + FLAG_SET(t->t_flags, T_ACPT); + goto end; } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); + goto end; } - + +failed_with_errno: + send_cmd(conn->sock_fd, 503, "%s", strerror(errno)); +end: FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; - if (!QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + if (!FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); - SET_FLAG(t->t_flags, T_RETR); + FLAG_SET(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } - if (!QUERY_FLAG(t->t_flags, T_RETR)) - SET_FLAG(t->t_flags, T_KILL); + if (!FLAG_QUERY(t->t_flags, T_RETR)) + FLAG_APPEND(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = remove_folder(dir_name); if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } else { + send_cmd(conn->sock_fd, 550, "sorry bad path"); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; - if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); - SET_FLAG(t->t_flags, T_STOR); + FLAG_SET(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); - SET_FLAG(t->t_flags, T_KILL); + FLAG_APPEND(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } -/* static void */ -/* cmd_mdtm(struct connection *conn) */ -/* { */ -/* FUNC_ENTRY(); */ - - - -/* FUNC_EXIT_VOID(); */ -/* } */ - +/* + * If the pathname specifies a directory or other group of files, + * the server should transfer a list of files in the specified + * directory. If the pathname specifies a file then the server + * should send current information on the file. A null argument + * implies the user's current working or default directory. + * The data transfer is over the data connection in type ASCII + * or type EBCDIC. + * + * See RFC-959 + */ static void cmd_list(struct connection *conn) { transport *t = conn->transport; + char *cmd_arg; + int ret; FUNC_ENTRY(); - - if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + + if (FLAG_QUERY(t->t_flags, (T_PORT | T_PASV))) { activate_nodelay(t->socket); - do_list(conn); - SET_FLAG(t->t_flags, T_KILL); + cmd_arg = get_cmd_arg(conn, 1); + if (cmd_arg) + /* + * (gdb) p conn->recv_buf + * $1 = "LIST /home/ftp/-al /etc", '\0' <repeats 4072 times> + */ + ret = is_path_ok(conn); + + if (!cmd_arg || ret == 1) { + t->target_dir = opendir(!cmd_arg ? conn->curr_dir:cmd_arg); + if (t->target_dir) { + FD_SET(t->socket, &srv->write_ready); + FLAG_SET(t->t_flags, T_LIST); + send_cmd(conn->sock_fd, 150, "ASCII MODE"); + } + } + + if (!FLAG_QUERY(t->t_flags, T_LIST)) { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + } + } else { + send_cmd(conn->sock_fd, 550, "sorry, use PORT or PASV first"); } - + FUNC_EXIT_VOID(); } -/* static void */ -/* cmd_nlst(struct connection *conn) */ -/* { */ -/* FUNC_ENTRY(); */ - - - -/* FUNC_EXIT_VOID(); */ -/* } */ - static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); - + send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); - + FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; - if (!QUERY_FLAG(t->t_flags, T_FREE)) { - SET_FLAG(t->t_flags, T_KILL); + + /* if it's not FREE */ + if (FLAG_QUERY(t->t_flags, T_FREE)) { + FLAG_APPEND(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } -/* static void */ -/* cmd_mode(struct connection *conn) */ -/* { */ -/* FUNC_ENTRY(); */ - - - -/* FUNC_EXIT_VOID(); */ -/* } */ - static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); - SET_FLAG(conn->c_flags, C_KILL); + FLAG_SET(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } -int +void parse_cmd(connection *conn) { const struct cmd_handler *h; - int processed = 0; - int buf_len; + struct hash_entry *entry; + char key[256] = {'\0'}; + int i = 0; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ - buf_len = strcspn(conn->recv_buf, "\r\n"); - conn->recv_buf[buf_len] = '\0'; - conn->recv_buf_len = buf_len; - - h = cmd_table; - - do { - if (!strncasecmp(conn->recv_buf, h->cmd_name, h->cmd_len)) { - if (QUERY_FLAG(conn->c_flags, C_AUTH) || - !strncasecmp(conn->recv_buf, "USER", h->cmd_len) || - !strncasecmp(conn->recv_buf, "PASS", h->cmd_len) || - !strncasecmp(conn->recv_buf, "FEAT", h->cmd_len) || - !strncasecmp(conn->recv_buf, "QUIT", h->cmd_len)) - { - /* - * At first, we must set root UID and root GUID, - * and than we will set what we really need on demand. - */ - reset_euid(); - reset_egid(); - - /* - * If a client has already logged in and root permission - * really doesn't need we must change euid and egid. - */ - if (QUERY_FLAG(conn->c_flags, C_AUTH) && !h->need_root) { - set_egid(conn->uid); - set_euid(conn->gid); - } + i = strcspn(conn->recv_buf, "\r\n"); + conn->recv_buf[i] = '\0'; + conn->recv_buf_len = i; + + /* get key, i.e. command name */ + for (i = 0; conn->recv_buf[i] != ' ' && conn->recv_buf[i] != '\0'; i++) { + if (i < sizeof(key)) + key[i] = conn->recv_buf[i]; + } - h->cmd_handler(conn); - } else { - send_cmd(conn->sock_fd, 503, "You must login, at first."); + entry = hash_lookup(srv->cmd_hash_table, key); + if (entry) { + h = (const struct cmd_handler *) entry->data; + if (FLAG_QUERY(conn->c_flags, C_AUTH) || !h->need_auth) { + /* + * At first, we must set root UID and root GUID, + * and than we will set what we really need on demand. + */ + reset_euid(); + reset_egid(); + + /* + * If a client has already logged in and root permission + * really doesn't need we must change euid and egid. + */ + if (FLAG_QUERY(conn->c_flags, C_AUTH) && !h->need_root) { + set_egid(conn->uid); + set_euid(conn->gid); } - processed++; - break; + h->cmd_handler(conn); + } else { + send_cmd(conn->sock_fd, 503, "You must login, at first."); } - } while ((++h)->cmd_handler != NULL); - - /* if a client sends bad cmd, we let him know. */ - if (processed == 0) { + } else { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } - FUNC_EXIT_INT(processed); - return processed; + FUNC_EXIT_VOID(); } + +const struct cmd_handler cmd_table[] = +{ + { "USER", 1, cmd_user, 1, 0, 4 }, + { "PASS", 1, cmd_pass, 1, 0, 4 }, + { "PORT", 1, cmd_port, 1, 1, 4 }, + { "PASV", 0, cmd_pasv, 0, 1, 4 }, + { "LIST", 1, cmd_list, 1, 1, 4 }, + { "CDUP", 0, cmd_cdup, 0, 1, 4 }, + { "RETR", 1, cmd_retr, 0, 1, 4 }, + { "SIZE", 1, cmd_size, 0, 1, 4 }, + { "NOOP", 0, cmd_noop, 0, 1, 4 }, + { "SYST", 0, cmd_syst, 0, 0, 4 }, + { "TYPE", 0, cmd_type, 0, 1, 4 }, + { "ABOR", 0, cmd_abor, 0, 1, 4 }, + { "STRU", 0, cmd_stru, 0, 1, 4 }, + { "QUIT", 0, cmd_quit, 0, 0, 4 }, + { "FEAT", 0, cmd_feat, 0, 0, 4 }, + { "HELP", 0, cmd_help, 0, 1, 4 }, +#ifdef UPLOAD_SUPPORT + { "STOR", 0, cmd_stor, 0, 1, 4 }, + { "DELE", 1, cmd_dele, 0, 1, 4 }, + { "RMD", 1, cmd_rmd, 0, 1, 3 }, + { "MKD", 1, cmd_mkd, 0, 1, 3 }, +#endif + { "ALLO", 0, cmd_allo, 0, 1, 4 }, + { "PWD", 0, cmd_pwd, 0, 1, 3 }, + { "CWD", 1, cmd_cwd, 0, 1, 3 }, + { " ", 0, NULL, 0, 0, 0 } +}; diff --git a/server/src/hash.c b/server/src/hash.c new file mode 100644 index 0000000..f720bc0 --- /dev/null +++ b/server/src/hash.c @@ -0,0 +1,284 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> + +/* local */ +#include <hash.h> + +/* +-----+-----+-----+ */ +/* | 0 | a | - | */ +/* +-----+-----+-----+ */ +/* | 1 | - | - | */ +/* +-----+-----+-----+ */ +/* | 2 | a | b | */ +/* +-----+-----+-----+ */ +/* | 3 | a | - | */ +/* +-----+-----+-----+ */ +/* | 4 | a | - | */ +/* +-----+-----+-----+ */ +/* | 5 | a | b | */ +/* +-----+-----+-----+ */ +/* | 6 | a | - | */ +/* +-----+-----+-----+ */ +/* | 7 | - | - | */ +/* +-----+-----+-----+ */ +/* | 8 | a | b | */ +/* +-----+-----+-----+ */ +/* | 9 | - | - | */ +/* +-----+-----+-----+ */ + +#define POISONED ((void *) 0x00100100) /* hit poisoned address */ + +static inline unsigned int +hash_function(const char *key, int table_size) +{ + unsigned int h = 0; + unsigned int g = 0; + + while (*key) { + h = (h << 4U) + *key++; + if ((g = h & 0xf0000000)) + h ^= g >> 24U; + + h &= ~g; + } + + return h % table_size; +} + +int +hash_del(struct hash *h, const char *key) +{ + struct hash_entry *tmp; + unsigned int index; + + if (h && key) { + index = hash_function(key, h->hash_size); + tmp = h->hash_table[index]; + if (tmp == NULL) + goto out; + + /* go through the list of collision */ + for (; tmp; tmp = tmp->next) { + if (!strcmp(tmp->key, key)) { + int ret = hash_del_entry(h, tmp); + + if (ret) + return 1; + else + goto out; + } + } + } + +out: + return 0; +} + +int +hash_del_entry(struct hash *h, struct hash_entry *entry) +{ + if (h && entry) { + if (entry->prev) + entry->prev->next = entry->next; + if (entry->next) + entry->next->prev = entry->prev; + + /* if it's first, shift head */ + if (entry->prev == NULL) + h->hash_table[entry->index] = entry->next; + + free(entry); + return 1; + } + + return 0; +} + +void +hash_destroy(struct hash *h) +{ + struct hash_entry *tmp; + int i; + + if (h) { + for (i = 0; h->hash_table[i] != POISONED; i++) { + tmp = h->hash_table[i]; + while (tmp) { + (void) hash_del(h, tmp->key); + tmp = h->hash_table[i]; + } + + h->hash_table[i] = NULL; + } + + free(h->hash_table); + free(h); + } +} + +int +hash_add(struct hash *h, const char *key, void *data) +{ + struct hash_entry *node; + struct hash_entry *tmp; + unsigned int index; + + if (h == NULL || key == NULL) + goto out; + + index = hash_function(key, h->hash_size); + node = (hash_entry *) calloc(1, sizeof(hash_entry)); + + if (node) { + /* fill out the node */ + (void) strncpy(node->key, key, sizeof(node->key)); + node->born_time = time(NULL); + node->index = index; + node->data = data; + node->next = NULL; + node->prev = NULL; + + if (h->hash_table[index] == NULL) { + h->hash_table[index] = node; + } else { + tmp = h->hash_table[index]; + while (1) { + if (!strcmp(tmp->key, key)) + goto out_and_free; + + if (tmp->next) + /* the latest */ + tmp = tmp->next; + else + break; + } + + /* add to queue */ + tmp->next = node; + node->next = NULL; + node->prev = tmp; + } + + /* success */ + return 1; + } + +out_and_free: + free(node); +out: + return 0; +} + +struct hash_entry * +hash_lookup(struct hash *h, const char *key) +{ + struct hash_entry *tmp; + unsigned int index; + + if (h && key) { + index = hash_function(key, h->hash_size); + tmp = h->hash_table[index]; + if (tmp == NULL) + goto out; + + while (tmp) { + if (!strcmp(tmp->key, key)) + return tmp; + + tmp = tmp->next; + } + } + +out: + return NULL; +} + +struct hash * +hash_create(int table_size) +{ + struct hash *h; + int i; + + if (table_size > 0) { + h = (struct hash *) calloc(1, sizeof(struct hash)); + if (h) { + h->hash_table = (hash_entry **) calloc(table_size + 1, sizeof(hash_entry *)); + if (h->hash_table) { + for (i = 0; i < table_size; i++) + h->hash_table[i] = NULL; + + h->hash_table[i] = (hash_entry *) POISONED; + h->hash_size = table_size; + return h; + } + } + } + + return NULL; +} + +int +hash_resize(struct hash *h, int size) +{ + /* TODO: implement it */ + return 0; +} + +int +hash_rehash(struct hash *h) +{ + /* + * Algorithm of rehashing is quite simple. This routine does + * following things: + * + * 1) picks up all entries, except for marked as NULL; + * 2) generates new index according to the key; + * 3) if new index is not equal to old one then make replacing. + */ + if (h) { + for (int i = 0; h->hash_table[i] != (hash_entry *) POISONED && h->hash_table[i]; i++) { + struct hash_entry *tmp = h->hash_table[i]; + unsigned int index = hash_function(tmp->key, h->hash_size); + + /* rehash everyone who is in queue */ + do { + if (tmp->index != index) { + int ret; + + ret = hash_add(h, tmp->key, tmp->data); + if (ret) { + ret = hash_del_entry(h, tmp); + } + } + + } while (tmp->next); + } + } + + return 0; +} + +void +hash_dump(struct hash *h) +{ + struct hash_entry *n; + int i; + + if (h) { + for (i = 0; h->hash_table[i] != (hash_entry *) POISONED; i++) { + n = h->hash_table[i]; + if (n) { + fprintf(stdout, "%d ", i); + do { + fprintf(stdout, "+"); + } while ((n = n->next)); + + fprintf(stdout, "\n"); + } else { + fprintf(stdout, "%d -\n", i); + } + } + } +} diff --git a/server/src/ls.c b/server/src/ls.c new file mode 100644 index 0000000..3cebedf --- /dev/null +++ b/server/src/ls.c @@ -0,0 +1,165 @@ +#define _ATFILE_SOURCE +#include <fcntl.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <sys/time.h> +#include <dirent.h> +#include <time.h> +#include <errno.h> + +#include <debug.h> +#include <mem.h> + +#define MAX_UID_LEN 5 +#define MAX_GID_LEN 5 + +static char * +get_perm(mode_t st_mode, char *perm) +{ + int i; + + /* clean */ + for (i = 0; i < 9; i++) + *(perm + i) = '-'; + + *(perm + 0) = '?'; + switch (st_mode & S_IFMT) { + case S_IFDIR: *(perm + 0) = 'd'; break; + case S_IFREG: *(perm + 0) = '-'; break; + case S_IFLNK: *(perm + 0) = 'l'; break; + case S_IFBLK: *(perm + 0) = 'b'; break; + case S_IFCHR: *(perm + 0) = 'c'; break; + case S_IFSOCK: *(perm + 0) = 's'; break; + case S_IFIFO: *(perm + 0) = 'p'; break; + } + + (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): + (*(perm + 1) = '-'); + (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): + (*(perm + 2) = '-'); + (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): + (*(perm + 3) = '-'); + (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): + (*(perm + 4) = '-'); + (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): + (*(perm + 5) = '-'); + (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): + (*(perm + 6) = '-'); + (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): + (*(perm + 7) = '-'); + (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): + (*(perm + 8) = '-'); + (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): + (*(perm + 9) = '-'); + + *(perm + 10) = '\0'; + return perm; +} + +static int +get_file_attr(DIR *d, const char *f_name, struct stat *st) +{ + int dir_fd; + int ret; + + if (d) + dir_fd = dirfd(d); + + if (d && dir_fd != -1) { + ret = fstatat(dir_fd, f_name, st, AT_SYMLINK_NOFOLLOW); + if (ret == 0) + return 1; + } + + return 0; +} + +static struct dirent * +get_dirent_entry(DIR *dir_name) +{ + struct dirent *d = NULL; + + if (dir_name != NULL) { + d = readdir(dir_name); + if (d == NULL) { + return NULL; + } else if (d->d_name[0] == '.' && d->d_name[1] == '\0') { + d = get_dirent_entry(dir_name); + } + } + + return d; +} + +static int +get_mtime(time_t time, char *mtime, int mtime_len) +{ + const char *date_format = "%b %d %H:%M"; + struct timeval c_time; + struct tm *tm = NULL; + + if (gettimeofday(&c_time, NULL) != -1 && mtime_len > 0) { + if (time > c_time.tv_sec || + (c_time.tv_sec - time) > 60 * 60 * 24 * 182) { + date_format = "%b %d %Y"; + } + + tm = localtime(&time); + strftime(mtime, mtime_len - 1, date_format, tm); + return 1; + } + + return 0; +} + +char * +get_file_list_chunk(DIR *dir, int nfiles, int short_list) +{ + struct dirent *d; + char line[400] = {'\0'}; + char *chunk; + int len = 0; + + if (nfiles > 0) { + chunk = (char *)calloc(nfiles * sizeof(line), sizeof(char)); + if (chunk == NULL) + FATAL_ERROR("error: %s\n", strerror(errno)); + } + + for (int i = 0; i < nfiles && nfiles > 0; i++) { + d = get_dirent_entry(dir); + if (d != NULL) { + struct stat st; + int ret; + + ret = get_file_attr(dir, d->d_name, &st); + if (ret) { + char mtime[20] = {'\0'}; + char perm[11] = {'\0'}; + + if (short_list == 0) { + /* Permissions */ + (void) get_perm(st.st_mode, perm); + /* time of last modification */ + (void) get_mtime(st.st_mtime, mtime, sizeof(mtime)); + /* build the line */ + len += snprintf(line, sizeof(line) - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", + perm, (unsigned int) st.st_nlink, MAX_UID_LEN, st.st_uid, + MAX_GID_LEN, st.st_gid, 7, st.st_size, mtime, d->d_name); + } else { + len += snprintf(line, sizeof(line) - 1, "%s\r\n", d->d_name); + } + + /* attach to the chunk */ + (void) strcat(chunk, line); + } + } + } + + if (len > 0) + return chunk; + + free(chunk); + return NULL; +} diff --git a/src/mem.c b/server/src/mem.c similarity index 100% rename from src/mem.c rename to server/src/mem.c diff --git a/src/sftpd.c b/server/src/sftpd.c similarity index 73% rename from src/sftpd.c rename to server/src/sftpd.c index 131e615..fc324f3 100644 --- a/src/sftpd.c +++ b/server/src/sftpd.c @@ -1,619 +1,722 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> +#include <dirent.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> +#include <hash.h> #include <mem.h> +#include <ls.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; + int ret; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); + /* + * Create hash table with size 100, in spite of we + * have approximately 29 FTP commands, by this way + * we tend to avoid collisions. + */ + sftpd->cmd_hash_table = hash_create(100); + if (sftpd->cmd_hash_table == NULL) + FATAL_ERROR("error allocating memory\n"); + + /* adding to hash commands and their handlers */ + for (int i = 0; cmd_table[i].cmd_handler; i++) { + ret = hash_add(sftpd->cmd_hash_table, cmd_table[i].cmd_name, (void *)&cmd_table[i]); + if (ret == 0) + FATAL_ERROR("error adding to the hash\n"); + } + /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ - SET_FLAG(tr->t_flags, T_FREE); + FLAG_SET(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; - if (!QUERY_FLAG(t->t_flags, T_FREE)) { - if (FD_ISSET(t->socket, &srv->write_ready)) { - /* in case of downloading */ - FD_CLR(t->socket, &srv->write_ready); - close(t->local_fd); - } + if (!FLAG_QUERY(t->t_flags, T_FREE)) { + /* listing */ + if (FLAG_QUERY(t->t_flags, T_LIST)) { + if (t->socket >= 0) { + FD_CLR(t->socket, &srv->write_ready); + } else { + BUG(); + } - if (FD_ISSET(t->socket, &srv->read_ready)) { - /* in case of uploading */ - FD_CLR(t->socket, &srv->read_ready); - close(t->local_fd); + closedir(t->target_dir); + } else if (FLAG_QUERY(t->t_flags, (T_RETR | T_STOR))) { + /* downloading or uploading */ + if (t->socket >= 0) { + if (FLAG_QUERY(t->t_flags, T_RETR)) + FD_CLR(t->socket, &srv->write_ready); + else + FD_CLR(t->socket, &srv->read_ready); + } else { + BUG(); + } + + if (t->local_fd >= 0) + close(t->local_fd); + else + BUG(); + } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { + /* accepting */ + if (t->listen_socket >= 0) { + FD_CLR(t->listen_socket, &srv->read_ready); + } else { + BUG(); + } + + close_socket(t->listen_socket); } - close_socket(t->socket); + if (t->socket >= 0) + close_socket(t->socket); + else + BUG(); /* clean transport before next using */ bzero(t, sizeof(transport)); - SET_FLAG(t->t_flags, T_FREE); + FLAG_SET(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void -accept_client(int socket, fd_set *r_fd, int *n_ready) +accept_connection(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); + hash_destroy(srv->cmd_hash_table); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { - SET_FLAG(c->c_flags, C_KILL); + FLAG_SET(c->c_flags, C_KILL); } else { - if (!QUERY_FLAG(t->t_flags, T_FREE)) { + if (!FLAG_QUERY(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { - SET_FLAG(t->t_flags, T_KILL); + FLAG_APPEND(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { - if (!QUERY_FLAG(c->c_flags, C_KILL)) { + if (!FLAG_QUERY(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); - SET_FLAG(c->c_flags, C_KILL); + FLAG_SET(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ - if (QUERY_FLAG(c->c_flags, C_KILL)) + if (FLAG_QUERY(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } - SET_FLAG(c->c_flags, C_KILL); + FLAG_SET(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; - if (QUERY_FLAG(c->c_flags, C_KILL)) { + if (FLAG_QUERY(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; - } else if (QUERY_FLAG(t->t_flags, T_KILL)) { + } else if (FLAG_QUERY(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); - SET_FLAG(t->t_flags, T_KILL); + FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); - SET_FLAG(t->t_flags, T_KILL); + FLAG_APPEND(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } +static void +list_folder(struct connection *c) +{ + struct transport *t; + char *list; + + FUNC_ENTRY(); + + t = c->transport; + + list = get_file_list_chunk(t->target_dir, 300, 0); + if (list) { + send_data(t->socket, list, strlen(list), 0); + free(list); + } else { + send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); + FLAG_APPEND(t->t_flags, T_KILL); + } + + FUNC_EXIT_VOID(); +} + static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; - /* skip who is FREE or KILL */ - if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) + /* skip who is FREE, KILL, PORT or PASV */ + if (FLAG_QUERY(t->t_flags, (T_FREE | T_KILL | T_PORT | T_PASV))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && - !FD_ISSET(t->socket, r_fd)) + !FD_ISSET(t->socket, r_fd) && + !FD_ISSET(t->listen_socket, r_fd)) continue; - if (QUERY_FLAG(t->t_flags, T_RETR)) { - c->c_atime = time(NULL); - download_file(c); - (*n_ready)--; - processed++; - } else if (QUERY_FLAG(t->t_flags, T_STOR)) { - c->c_atime = time(NULL); - upload_file(c); - (*n_ready)--; - } else { - BUG(); + if (FLAG_QUERY(t->t_flags, T_LIST)) { + if (FD_ISSET(t->socket, w_fd)) { + c->c_atime = time(NULL); + list_folder(c); + (*n_ready)--; + processed++; + } + } else if (FLAG_QUERY(t->t_flags, T_ACPT)) { + if (FD_ISSET(t->listen_socket, r_fd)) { + t->socket = accept_timeout(t->listen_socket, (SA *)&t->r_info, 5); + if (t->socket != -1) { + /* we are in PASV mode */ + activate_nonblock(t->socket); + FD_CLR(t->listen_socket, &srv->read_ready); + FLAG_SET(t->t_flags, T_PASV); + close_socket(t->listen_socket); + } else { + /* + * listen_socket will be cleaned and closed + * by the 'destroy_transport' routine, don't + * use FD_CLR here. + */ + send_cmd(c->sock_fd, 500, "%s", strerror(errno)); + PRINT_DEBUG("%s\n", strerror(errno)); + FLAG_APPEND(t->t_flags, T_KILL); + } + + c->c_atime = time(NULL); + (*n_ready)--; + processed++; + } + } else if (FLAG_QUERY(t->t_flags, T_RETR)) { + if (FD_ISSET(t->socket, w_fd)) { + c->c_atime = time(NULL); + download_file(c); + (*n_ready)--; + processed++; + } + } else if (FLAG_QUERY(t->t_flags, T_STOR)) { + if (FD_ISSET(t->socket, r_fd)) { + c->c_atime = time(NULL); + upload_file(c); + (*n_ready)--; + } } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ - accept_client(srv->srv_socket, &r_fd, &n_ready); + accept_connection(srv->srv_socket, &r_fd, &n_ready); } return 0; } diff --git a/src/signal_ruling.c b/server/src/signal_ruling.c similarity index 100% rename from src/signal_ruling.c rename to server/src/signal_ruling.c diff --git a/src/sock_utils.c b/server/src/sock_utils.c similarity index 98% rename from src/sock_utils.c rename to server/src/sock_utils.c index 2dc26a6..07701aa 100644 --- a/src/sock_utils.c +++ b/server/src/sock_utils.c @@ -1,478 +1,478 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <errno.h> /* local headers */ #include <debug.h> #include <sock_utils.h> #include <list.h> #include <mem.h> /** * send_data - sending a message to a socket, * return the number of characters sent, otherwise -1. * * @s: socket; * @buf: buffer where the message should be stored; * @len: length of the message; * @flags: flags which we passing to send. */ int send_data(int s, const void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { - n = send(s, buf + total, len - total, flags); + n = send(s, buf + total, len - total, MSG_NOSIGNAL); if (n < 0) { PRINT_DEBUG("Write to socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * recv_data - receive a message from a socket, * return the number of bytes received, or -1 * if an error obtained, also 0 will be recived * when the peer has performed an orderly shutdown. * * @s: socket; * @buf: buffer where the message will be stored; * @len: length of the message; * @flags: flags which we passing to recv. */ int recv_data(int s, void *buf, int len, int flags) { int total = 0; int ret = 0; int n = 0; FUNC_ENTRY(); for (total = 0; total < len; total += n) { - n = recv(s, buf + total, len - total, flags); + n = recv(s, buf + total, len - total, MSG_NOSIGNAL); if (n <= 0) { PRINT_DEBUG("Read from socket failed with errno %d: %s\n", errno, strerror(errno)); break; } } ret = ((n == 0) ? 0 : (n < 0) ? -1 : total); FUNC_EXIT_INT(ret); return ret; } /** * send_cmd - send a message to socket, but * also it is able to build format string * like printf. * * @s: socket; * @cmd: codes which ftp protocol uses; * @format: string that specifies how subsequent arguments are converted. */ void send_cmd(int s, const int cmd, const char *const format, ...) { char buf[256] = {'\0'}; char fmt[256] = {'\0'}; va_list args; int err; int i; FUNC_ENTRY(); snprintf(fmt, sizeof(fmt), "%03u %s\r\n", cmd, format); va_start(args, format); i = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); err = send_data(s, buf, i, 0); FUNC_EXIT_VOID(); } /** * get_remote_info - get name of connected peer socket. * On success, zero is returned, otherwise -1. * * @s: socket; * @name: pointer which will contain some information. */ int get_remote_info(int s, struct sockaddr *name) { unsigned int sock_len = 0; int ret = 0; FUNC_ENTRY(); sock_len = sizeof(struct sockaddr); ret = getpeername(s, name, &sock_len); if (ret == -1) PRINT_DEBUG("getpeername failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ret); return ret; } /** * start_tcp_listen - starts listen a port number. * On success, listen socket is returned, otherwise -1. * * @port_number: port number which be listened; * @ip_ver: IPv4 or IPv6; * @backlog: maximum length the queue of pending, * connections may grow to. */ int start_tcp_listen(int port_number, int ip_ver, int backlog) { struct sockaddr_in serv_addr; int listenfd = 0; int retval = 0; int len = 0; FUNC_ENTRY(); if (ip_ver == 4) listenfd = get_ipv4_socket(); else if (ip_ver == 6) listenfd = get_ipv6_socket(); bzero(&serv_addr, sizeof(serv_addr)); if (listenfd != -1) { serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = (backlog) ? htons(port_number):0; if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET) len = sizeof(struct sockaddr_in); else if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET6) len = sizeof(struct sockaddr_in6); activate_reuseaddr(listenfd); retval = bind(listenfd, (struct sockaddr *)&serv_addr, len); if (retval != -1) { retval = listen(listenfd, backlog); if (retval < 0) { PRINT_DEBUG("listen failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } else { PRINT_DEBUG("bind failed with errno %d: %s\n", errno, strerror(errno)); listenfd = -1; } } FUNC_EXIT_INT(listenfd); return listenfd; } /** * accept_timeout - accepting connection from the client. * On successful connected socked is returned, otherwise -1. * * @s: socket; * @r_addr: will contain info about remote host; * @sec: wait time. */ int accept_timeout(int s, struct sockaddr *r_addr, unsigned int sec) { int connect_fd = 0; int retval = 0; fd_set r_fd; fd_set w_fd; FUNC_ENTRY(); do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; if (sec > 0) { struct timeval time; time.tv_sec = sec; time.tv_usec = 0; retval = select(s + 1, &r_fd, &w_fd, NULL, &time); } else { retval = select(s + 1, &r_fd, &w_fd, NULL, NULL); } } while (retval < 0 && errno == EINTR); if (retval > 0) { socklen_t len = sizeof(*r_addr); connect_fd = accept(s, r_addr, &len); retval = (connect_fd > 0) ? connect_fd : -1; } else if (retval == 0) { PRINT_DEBUG("warning: accept timeout!\n"); retval = -1; } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } FUNC_EXIT_INT(retval); return retval; } /** * connect_timeout - connect to the client. * On success 0 is returned, otherwise -1. * * @s: socket; * @r_addr: information about remote client; * @sec: how much time we should wait. */ int connect_timeout(int s, struct sockaddr *r_addr, int sec) { struct sockaddr remote_addr; socklen_t sock_len = 0; int retval; FUNC_ENTRY(); if (sec > 0) activate_nonblock(s); sock_len = sizeof(remote_addr); retval = connect(s, r_addr, sock_len); if (retval < 0 && errno == EINPROGRESS) { struct timeval timeout; fd_set r_fd; fd_set w_fd; int n; do { FD_ZERO(&r_fd); FD_SET(s, &r_fd); w_fd = r_fd; timeout.tv_sec = sec; timeout.tv_usec = 0; n = select(s + 1, &r_fd, &w_fd, NULL, &timeout); } while (n < 0 && errno == EINTR); if (n > 0) { /* We have to check the socket for error */ if (FD_ISSET(s, &r_fd) || (FD_ISSET(s, &w_fd))) retval = check_socket(s); } else if (n == 0) { PRINT_DEBUG("No data within %d seconds\n", sec); } else { PRINT_DEBUG("select failed with errno %d: %s\n", errno, strerror(errno)); } } if (sec > 0) deactivate_nonblock(s); FUNC_EXIT_INT(retval); return retval; } /** * check_socket - checking a socket on error. * * @s: socket; */ int check_socket(int s) { socklen_t err_len = 0; int retval = 0; int error = 0; FUNC_ENTRY(); err_len = sizeof(error); retval = getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &err_len); if (retval < 0 || error != 0) PRINT_DEBUG("getsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(retval); return retval; } void close_socket(int s) { int ret; FUNC_ENTRY(); ret = shutdown(s, SHUT_RDWR); if (ret) PRINT_DEBUG("shutdown failed with errno %d: %s\n", errno, strerror(errno)); close(s); FUNC_EXIT_VOID(); } void activate_nodelay(int s) { int ret = 0; int nodelay = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_cork(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, IPPROTO_TCP, TCP_CORK, &on, sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void activate_reuseaddr(int s) { int ret = 0; int on = 1; FUNC_ENTRY(); ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (ret != 0) PRINT_DEBUG("setsockopt failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } int get_ipv4_socket(void) { int ipv4_sock; FUNC_ENTRY(); ipv4_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (ipv4_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv4_sock); return ipv4_sock; } int get_ipv6_socket(void) { int ipv6_sock; FUNC_ENTRY(); ipv6_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); if (ipv6_sock < 0) PRINT_DEBUG("socket failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_INT(ipv6_sock); return ipv6_sock; } void activate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags |= O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void deactivate_nonblock(int s) { int retval = -1; int flags = 0; FUNC_ENTRY(); flags = fcntl(s, F_GETFL); if (flags > 0) { flags &= ~O_NONBLOCK; retval = fcntl(s, F_SETFL, flags); } if (retval < 0) PRINT_DEBUG("fcntl failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } diff --git a/src/utils.c b/server/src/utils.c similarity index 100% rename from src/utils.c rename to server/src/utils.c diff --git a/src/ls.c b/src/ls.c deleted file mode 100644 index db9b563..0000000 --- a/src/ls.c +++ /dev/null @@ -1,381 +0,0 @@ -#include <sys/stat.h> -#include <string.h> -#include <stdlib.h> -#include <stdio.h> -#include <dirent.h> -#include <langinfo.h> -#include <sys/time.h> -#include <sys/socket.h> -#include <netinet/in.h> - -#include <grp.h> -#include <pwd.h> -#include <time.h> - -#include <list.h> -#include <sock_utils.h> -#include <debug.h> -#include <sftpd.h> -#include <ls.h> -#include <mem.h> - -#define MAX_UID_LEN 5 -#define MAX_GID_LEN 5 - -#define R 000000001 /* read */ -#define W 000000010 /* write */ -#define X 000000100 /* execute */ - -static char * -get_perm(mode_t st_mode, char *perm) -{ - int i; - - for (i = 0; i < 9; i++) - *(perm + i) = '-'; - - *(perm + 0) = '?'; - switch (st_mode & S_IFMT) - { - case S_IFDIR: *(perm + 0) = 'd'; - break; - case S_IFREG: *(perm + 0) = '-'; - break; - case S_IFLNK: *(perm + 0) = 'l'; - break; - case S_IFBLK: *(perm + 0) = 'b'; - break; - case S_IFCHR: *(perm + 0) = 'c'; - break; - case S_IFSOCK: *(perm + 0) = 's'; - break; - case S_IFIFO: *(perm + 0) = 'p'; - break; - } - - (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): - (*(perm + 1) = '-'); - (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): - (*(perm + 2) = '-'); - (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): - (*(perm + 3) = '-'); - (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): - (*(perm + 4) = '-'); - (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): - (*(perm + 5) = '-'); - (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): - (*(perm + 6) = '-'); - (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): - (*(perm + 7) = '-'); - (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): - (*(perm + 8) = '-'); - (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): - (*(perm + 9) = '-'); - - *(perm + 10) = '\0'; - return perm; -} - -static int -get_file_attr(char *file_name, char *dir_name, struct stat *st) -{ - size_t file_len = 0; - size_t dir_len = 0; - char *file_path; - int retval = -1; - - file_len = strlen(file_name); - dir_len = strlen(dir_name); - - if (file_name > 0 && dir_name > 0) { - file_path = (char *) malloc(file_len + dir_len + 2); - if (file_path != NULL) { - snprintf(file_path, dir_len + file_len + 2, "%s/%s%c", - dir_name, file_name, '\0'); - - retval = stat(file_path, st); - if (retval < 0) - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - free(file_path); - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - } - - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - } - - return retval; -} - -static int -feel_node(__str *str_node, char *dir_name, char *f_name, - unsigned int f_len, off_t *max_size_len) -{ - struct stat st; - int retval = 0; - - /* calloc (f_len + 1) for '\0' !!! */ - str_node->f_name = calloc(f_len + 1, sizeof(char)); - if (!str_node->f_name) - FATAL_ERROR("error allocating memory\n"); - - strncpy(str_node->f_name, f_name, f_len); - str_node->f_name[f_len] = '\0'; - str_node->f_len = f_len; - - retval = get_file_attr(f_name, dir_name, &st); - if (retval != -1) { - str_node->uid = st.st_uid; - str_node->gid = st.st_gid; - str_node->st_nlink = st.st_nlink; - str_node->st_size = st.st_size; - str_node->time = st.st_mtime; - str_node->mode = st.st_mode; - if (st.st_size > *max_size_len) - *max_size_len = st.st_size; - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - free(str_node->f_name); - str_node->f_name = NULL; - } - - return retval; -} - -static struct dirent * -next_entry(DIR *dir_name) -{ - struct dirent *next_dnt; - - if (dir_name != NULL) { - next_dnt = readdir(dir_name); - if (next_dnt == NULL) - return NULL; - else if (next_dnt->d_name[0] == '.' && next_dnt->d_name[1] == '\0') - { - next_dnt = next_entry(dir_name); - } - } - - return next_dnt; -} - -static __str ** -do_readdir(char *dir_name, off_t *max_size_len, int *file_count) -{ - struct dirent *pp = NULL; - DIR *open_dir = NULL; - struct stat st; - __str **list = NULL; - - int guess_size = 0; - int retval = 0; - - *file_count = 0; - retval = stat(dir_name, &st); - open_dir = opendir(dir_name); - - if (retval < 0 || opendir == NULL || !S_ISDIR(st.st_mode)) { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - goto out; - } - - /* magic number */ - guess_size = st.st_size / 20; - if (guess_size == 0) - guess_size = 50; - - list = (__str **) calloc(guess_size, sizeof(__str *)); - if (list == NULL) { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - goto out; - } - - while (1) { - if (guess_size == *file_count) { - __str **new_pp; - - new_pp = (__str **) realloc(list, 2 * guess_size * sizeof(__str *)); - if (new_pp == NULL && !(list = NULL)) { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - goto out; - } - - list = new_pp; - guess_size *= 2; - } - - if ((pp = next_entry(open_dir)) == NULL) - break; - - list[*file_count] = (__str *) calloc(1, sizeof(__str)); - if (list[*file_count] != NULL) { - retval = feel_node(list[*file_count], dir_name, pp->d_name, - pp->d_reclen, max_size_len); - if (retval == -1) { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - free(list[*file_count]); - continue; - } - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - list = NULL; - goto out; - } - - (*file_count)++; - } /* while (1) */ - - /* last element */ - list[*file_count] = NULL; -out: - if (closedir(open_dir) < 0) - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - - return list; -} - -static size_t -calculate_of_byte(__str **str_list, int m_size) -{ - size_t count_of_byte = 0; - register int i = 0; - - if (str_list != NULL) { - /* size of build_data */ - while (*(str_list + i) != NULL) { - count_of_byte += 35 + 10 + MAX_UID_LEN + MAX_GID_LEN + m_size; - count_of_byte += str_list[i]->f_len; - i++; - } - } - - return count_of_byte; -} - -static char * -get_file_date(time_t time) -{ - static char date_buf[20] = { '\0' }; - char *date_format = "%b %d %H:%M"; - struct timeval c_time; - struct tm *tm = NULL; - - if (gettimeofday(&c_time, NULL) != -1) { - if (time > c_time.tv_sec || - (c_time.tv_sec - time) > 60*60*24*182) { - date_format = "%b %d %Y"; - } - - tm = localtime(&time); - strftime(date_buf, sizeof(date_buf) - 1, date_format, tm); - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - return NULL; - } - - return date_buf; -} - -static char * -build_data(__str **str_list, int *len, off_t *max_size_len) -{ - size_t alloc_size = 0; - char tmp[20] = { '\0' }; - char *file_list = NULL; - int m_size = 0; - - m_size = snprintf(tmp, 20, "%ld", *max_size_len); - alloc_size = calculate_of_byte(str_list, m_size); - - if (alloc_size > 0) { - file_list = (char *) calloc(alloc_size, sizeof(char)); - if (file_list != NULL) { - char tmp_buf[400] = { '\0' }; - char perm[11] = { '\0' }; - char *date = NULL; - int i = 0; - int j = 0; - - *len = 0; - while (*(str_list + i) != NULL) { - date = get_file_date(str_list[i]->time); - (void) snprintf(tmp_buf, sizeof(tmp_buf) - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", - get_perm(str_list[i]->mode, perm), (unsigned int) str_list[i]->st_nlink, - MAX_UID_LEN, str_list[i]->uid, MAX_GID_LEN, - str_list[i]->gid, m_size + 1, - str_list[i]->st_size, date, - str_list[i]->f_name ? str_list[i]->f_name:"NULL" - ); - - j = 0; - while (tmp_buf[j] != '\0') { - *(file_list + (*len)) = tmp_buf[j]; - (*len)++; - j++; - } - - i++; - } - - *(file_list + (*len)) = '\0'; - - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - } - } - - return file_list; -} - -static void -free_list(__str **list, int count_l) -{ - int i = 0; - - while (*(list + i) != NULL) { - if (list[i]->f_name) - free(list[i]->f_name); - - free(list[i]); - i++; - } - - free(list); -} - -int -do_list(struct connection *c) -{ - off_t max_size_len = 0; - __str **pp = NULL; - int file_count = 0; - - pp = do_readdir(c->curr_dir, &max_size_len, &file_count); - if (pp != NULL) { - char *file_list = NULL; - int len = 0; - - /* build tree of file's */ - file_list = build_data(pp, &len, &max_size_len); - if (file_list != NULL) { - send_cmd(c->sock_fd, 150, "ASCII MODE"); - send_data(c->transport->socket, file_list, len, 0); - send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - goto error; - } - - free(file_list); - free_list(pp, file_count); - } else { - PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); - goto error; - } - - return 0; -error: - return -1; -} diff --git a/tests/cmd_test.c b/tests/cmd_test.c new file mode 100644 index 0000000..91abd57 --- /dev/null +++ b/tests/cmd_test.c @@ -0,0 +1,86 @@ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <unistd.h> +#include <time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <arpa/inet.h> +#include <errno.h> +#include <err.h> + +static const char *const cmd_table[] = +{ + "USER", "PASS", "PORT", "PASV", + "LIST", "CDUP", "RETR", "SIZE", + "NOOP", "SYST", "TYPE", "ABOR", + "STRU", "FEAT", "HELP", "STOR", + "DELE", "RMD", "MKD", "ALLO", + "PWD", "CWD", NULL +}; + +int main(int argc, char **argv) +{ + struct sockaddr_in r_addr; + socklen_t sock_len; + char tmp_buf[4096]; + int ipv4_sock; + int cmd_count; + int ret; + int i = 0; + + if (argv[1] == NULL || argv[2] == NULL) + err(-1, "use host port"); + + ipv4_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); + if (ipv4_sock < 0) + err(-1, "socket failed with errno %d: %s\n", + errno, strerror(errno)); + + sock_len = sizeof(struct sockaddr); + r_addr.sin_family = AF_INET; + r_addr.sin_addr.s_addr = inet_addr(argv[1]); + r_addr.sin_port = htons(atoi(argv[2])); + + ret = connect(ipv4_sock, (struct sockaddr *)&r_addr, sock_len); + if (ret != 0) + err(-1, "connect failed with errno %d: %s\n", + errno, strerror(errno)); + + (void) write(ipv4_sock, "USER anonymous\r\n", 16); + (void) read(ipv4_sock, tmp_buf, sizeof(tmp_buf)); + (void) write(ipv4_sock, "PASS [email protected]\r\n", 20); + (void) read(ipv4_sock, tmp_buf, sizeof(tmp_buf)); + + for (cmd_count = 0; cmd_table[cmd_count]; cmd_count++) + ; + + srand(time(NULL)); + + while (1) { + int r_index = rand() % cmd_count; + ret = snprintf(tmp_buf, sizeof(tmp_buf) - 1, "%s\r\n", cmd_table[r_index]); + if (ret > 0) + tmp_buf[ret] = '\0'; + + ret = write(ipv4_sock, tmp_buf, ret); + if (ret > 0) { + ret = read(ipv4_sock, tmp_buf, sizeof(tmp_buf)); + if (ret > 0) { + tmp_buf[ret] = '\0'; + fprintf(stdout, "got --> %s", tmp_buf); + } + } else { + err(-1, "write failed with errno %d: %s\n", + errno, strerror(errno)); + } + + if (i++ > 100) { + srand(time(NULL)); + i = 0; + } + } + + return 0; +}
urezki/sftpd
957e168caa0b1ca7bb8820f9b4177ac8fe79e7ad
@MAINT: implemented recursive removing of the folder.
diff --git a/include/utils.h b/include/utils.h index b0dad45..b8c11ef 100644 --- a/include/utils.h +++ b/include/utils.h @@ -1,10 +1,11 @@ #ifndef __UTILS_H__ #define __UTILS_H__ extern void set_euid(uid_t); extern void reset_euid(void); extern void set_egid(gid_t); extern void reset_egid(void); +extern int remove_folder(const char *); #endif /* __UTILS_H__ */ diff --git a/src/cmds.c b/src/cmds.c index 587ba03..4db8b99 100644 --- a/src/cmds.c +++ b/src/cmds.c @@ -1,894 +1,894 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #include <ls.h> static void cmd_user(struct connection *); static void cmd_pass(struct connection *); static void cmd_port(struct connection *); static void cmd_pasv(struct connection *); static void cmd_list(struct connection *); static void cmd_cdup(struct connection *); static void cmd_retr(struct connection *); static void cmd_size(struct connection *); static void cmd_noop(struct connection *); static void cmd_syst(struct connection *); static void cmd_type(struct connection *); static void cmd_stru(struct connection *); static void cmd_quit(struct connection *); static void cmd_feat(struct connection *); static void cmd_abor(struct connection *); static void cmd_stor(struct connection *); static void cmd_dele(struct connection *); static void cmd_help(struct connection *); static void cmd_allo(struct connection *); static void cmd_pwd(struct connection *); static void cmd_cwd(struct connection *); static void cmd_rmd(struct connection *); static void cmd_mkd(struct connection *); /* static void cmd_nlst(struct connection *); */ /* static void cmd_mode(struct connection *); */ /* static void cmd_mdtm(struct connection *); */ struct cmd_handler { char cmd_name[10]; char arg; void (*cmd_handler)(struct connection *const); char need_root; char cmd_len; }; static const struct cmd_handler cmd_table[] = { { "user", 1, cmd_user, 1, 4 }, { "pass", 1, cmd_pass, 1, 4 }, { "port", 1, cmd_port, 1, 4 }, { "pasv", 0, cmd_pasv, 0, 4 }, { "list", 0, cmd_list, 1, 4 }, { "cdup", 0, cmd_cdup, 0, 4 }, { "retr", 1, cmd_retr, 0, 4 }, { "size", 1, cmd_size, 0, 4 }, { "noop", 0, cmd_noop, 0, 4 }, { "syst", 0, cmd_syst, 0, 4 }, { "type", 0, cmd_type, 0, 4 }, { "abor", 0, cmd_abor, 0, 4 }, { "stru", 0, cmd_stru, 0, 4 }, { "quit", 0, cmd_quit, 0, 4 }, { "feat", 0, cmd_feat, 0, 4 }, { "help", 0, cmd_help, 0, 4 }, // { "mdtm", 0, cmd_mdtm, 0, 4 }, /* not implemented */ #ifdef UPLOAD_SUPPORT { "stor", 0, cmd_stor, 0, 4 }, { "dele", 1, cmd_dele, 0, 4 }, { "rmd", 1, cmd_rmd, 0, 3 }, { "mkd", 1, cmd_mkd, 0, 3 }, #endif // { "nlst", 0, cmd_nlst, 0, 4 }, /* not implemented */ // { "mode", 0, cmd_mode, 0, 4 }, /* not implemented */ { "allo", 0, cmd_allo, 0, 4 }, { "pwd", 0, cmd_pwd, 0, 3 }, { "cwd", 1, cmd_cwd, 0, 3 }, { " ", 0, NULL, 0, 0 } }; static int translate_path(const char *root, const char *cur, char *dst) { char absolute_path[PATH_MAX] = {'\0'}; char tmp_path[PATH_MAX] = {'\0'}; char *dot; int n; if (root == NULL || cur == NULL || dst == NULL) return -1; if (*dst == '/' || *dst == '~') { /* 1) cd / 2) cd ~/ 3) cd ~ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", root, *(dst + 1) == '/' ? dst + 2 : dst + 1); } else { /* 1) cd foo/ */ n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); } /* /home/urezki/../ftp/.. */ if ((dot = strrchr(absolute_path, '.'))) if (*(dot - 1) == '.' && *(dot + 1) == '\0') strcat(absolute_path, "/"); /* * Here we can have following combinations: * 1) /home/urezki/../ftp/../ * 2) /home/urezki/ */ while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } snprintf(dst, PATH_MAX, "%s", absolute_path); return 0; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; int ret; cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg == NULL || cmd_arg[1] == '\0') goto fail; /* get pointer to the arg */ cmd_arg = cmd_arg + 1; ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); if (ret < 0) goto fail; /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; fail: return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { SET_FLAG(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { SET_FLAG(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) SET_FLAG(conn->c_flags, C_AUTH); } } } } if (QUERY_FLAG(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int ret; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (QUERY_FLAG(t->t_flags, T_FREE)) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { int len; t->socket = get_ipv4_socket(); t->data_port = data_port; activate_reuseaddr(t->socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); bind(t->socket, (SA *)&t->r_info, len); t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(t->socket, (SA *)&t->r_info, 5); if (ret == 0) { /* we are in a port mode */ SET_FLAG(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); } else { send_cmd(conn->sock_fd, 425, "Can't open data connection"); PRINT_DEBUG("Can't connect to %s:%d\n", ip_address, data_port); } } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); } FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *trans; socklen_t len; FUNC_ENTRY(); trans = conn->transport; if (QUERY_FLAG(trans->t_flags, T_FREE)) { memset(&addr, 0, sizeof(addr)); listen_sock = get_ipv4_socket(); activate_reuseaddr(listen_sock); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); listen(listen_sock, 1); /* send that we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); /* * listen_sock should be added to the poll, and checked by select, * after that when socket is ready do accept. */ trans->socket = accept_timeout(listen_sock, (SA *)&trans->r_info, 5); if (trans->socket != -1) { /* we are in PASV mode */ SET_FLAG(trans->t_flags, T_PASV); activate_nonblock(trans->socket); } else { send_cmd(conn->sock_fd, 500, "Accepting error, sorry"); PRINT_DEBUG("Accepting error. sorry\n"); } /* we needn't listen further */ close_socket(listen_sock); } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); } FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); SET_FLAG(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!QUERY_FLAG(t->t_flags, T_RETR)) SET_FLAG(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; - + FUNC_ENTRY(); - + if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; - ret = rmdir(dir_name); - if (ret != -1) + ret = remove_folder(dir_name); + if (ret == 0) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } - + FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); SET_FLAG(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); SET_FLAG(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /* static void */ /* cmd_mdtm(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ static void cmd_list(struct connection *conn) { transport *t = conn->transport; FUNC_ENTRY(); if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { activate_nodelay(t->socket); do_list(conn); SET_FLAG(t->t_flags, T_KILL); } FUNC_EXIT_VOID(); } /* static void */ /* cmd_nlst(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { SET_FLAG(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } /* static void */ /* cmd_mode(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ static void cmd_help(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); FUNC_EXIT_VOID(); } static void cmd_stru(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); FUNC_EXIT_VOID(); } static void cmd_quit(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 221, "Goodbay."); SET_FLAG(conn->c_flags, C_KILL); FUNC_EXIT_VOID(); } /** * cmd_pwd - returning the current working dirrectory * of the user. */ static void cmd_pwd(struct connection *conn) { int root_len; FUNC_ENTRY(); root_len = strlen(conn->root_dir); send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", conn->curr_dir + (root_len - 1)); FUNC_EXIT_VOID(); } static void cmd_cdup(struct connection *conn) { char path[PATH_MAX]; int retval; FUNC_ENTRY(); retval = chdir(".."); if (retval != -1) { int root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); if (strncmp(path, conn->root_dir, root_len)) { /* * if we are going to visit outside * we don't have to change current * directory. */ /* What does RFC say in such situations ??? */ send_cmd(conn->sock_fd, 550, "CDUP was undone."); /* go back home */ chdir(conn->curr_dir); } else { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CDUP successfull."); } } FUNC_EXIT_VOID(); } /** * cmd_cwd - changing the current working dirrectory * of the user. */ static void cmd_cwd(struct connection *conn) { char path[PATH_MAX]; int root_len; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { ret = chdir(strchr(conn->recv_buf, ' ') + 1); if (ret == -1) { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); goto exit; } root_len = strlen(conn->root_dir); /* get absolute path */ (void) getcwd(path, sizeof(path)); if (path[strlen(path) - 1] != '/') strcat(path, "/"); /* * We must check path, because of symlinks, * and if everything is OK, we can change curr_dir. */ if (!strncmp(conn->root_dir, path, root_len)) { strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); send_cmd(conn->sock_fd, 250, "CWD successfull."); goto exit; } else { /* go back to the current dir */ chdir(conn->curr_dir); } } send_cmd(conn->sock_fd, 550, "No such File or Directory."); exit: FUNC_EXIT_VOID(); } int parse_cmd(connection *conn) { const struct cmd_handler *h; int processed = 0; int buf_len; FUNC_ENTRY(); /* * remove '\r' and '\n' from the recv_buf. */ buf_len = strcspn(conn->recv_buf, "\r\n"); conn->recv_buf[buf_len] = '\0'; conn->recv_buf_len = buf_len; h = cmd_table; do { if (!strncasecmp(conn->recv_buf, h->cmd_name, h->cmd_len)) { if (QUERY_FLAG(conn->c_flags, C_AUTH) || !strncasecmp(conn->recv_buf, "USER", h->cmd_len) || !strncasecmp(conn->recv_buf, "PASS", h->cmd_len) || !strncasecmp(conn->recv_buf, "FEAT", h->cmd_len) || !strncasecmp(conn->recv_buf, "QUIT", h->cmd_len)) { /* * At first, we must set root UID and root GUID, * and than we will set what we really need on demand. */ reset_euid(); reset_egid(); /* * If a client has already logged in and root permission * really doesn't need we must change euid and egid. */ if (QUERY_FLAG(conn->c_flags, C_AUTH) && !h->need_root) { set_egid(conn->uid); set_euid(conn->gid); } h->cmd_handler(conn); } else { send_cmd(conn->sock_fd, 503, "You must login, at first."); } processed++; break; } } while ((++h)->cmd_handler != NULL); /* if a client sends bad cmd, we let him know. */ if (processed == 0) { send_cmd(conn->sock_fd, 500, "Bad cmd."); PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); } FUNC_EXIT_INT(processed); return processed; } diff --git a/src/utils.c b/src/utils.c index 453bf95..cc1d4c0 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,58 +1,101 @@ +#define _ATFILE_SOURCE #include <stdio.h> +#include <fcntl.h> +#include <sys/stat.h> #include <sys/types.h> +#include <dirent.h> #include <unistd.h> #include <errno.h> #include <string.h> -#include <debug.h> /* local headers */ #include <list.h> #include <mem.h> +#include <debug.h> void set_euid(uid_t euid) { FUNC_ENTRY(); if (seteuid(euid) < 0) PRINT_DEBUG("seteuid [%d] failed with errno %u: %s\n", euid, errno, strerror(errno)); FUNC_EXIT_VOID(); } void reset_euid(void) { FUNC_ENTRY(); if (seteuid(0) < 0) PRINT_DEBUG("seteuid failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } void set_egid(gid_t egid) { FUNC_ENTRY(); if (setegid(egid) < 0) PRINT_DEBUG("setegid [%d] failed with errno %u: %s\n", egid, errno, strerror(errno)); FUNC_EXIT_VOID(); } void reset_egid(void) { FUNC_ENTRY(); if (setegid(0) < 0) PRINT_DEBUG("setegid failed with errno %d: %s\n", errno, strerror(errno)); FUNC_EXIT_VOID(); } + +/* + * return zero if success like rmdir + */ +int +remove_folder(const char *dir) +{ + struct dirent *drnt; + char path[4096] = {'\0'}; + struct stat st; + int ret = -1; + int dir_fd; + DIR *d; + + d = opendir(dir); + if (d) { + dir_fd = dirfd(d); + while ((drnt = readdir(d))) { + if ((drnt->d_name[0] == '.' && drnt->d_name[1] == '\0') || + ((drnt->d_name[0] == '.' && drnt->d_name[1] == '.') && drnt->d_name[2] == '\0')) + continue; + + ret = fstatat(dir_fd, drnt->d_name, &st, AT_SYMLINK_NOFOLLOW); + if (ret == 0) { + if (S_ISDIR(st.st_mode)) { + snprintf(path, sizeof(path) - 1, "%s/%s", dir, drnt->d_name); + remove_folder(path); + } else { + unlinkat(dir_fd, drnt->d_name, 0); + } + } + } + + ret = rmdir(dir); + closedir(d); + } + + return ret; +}
urezki/sftpd
9181eebc177156ac3f0a8ccb6e6ed129eaf6144f
@MAINT: do closing just when it's needed.
diff --git a/src/sftpd.c b/src/sftpd.c index 242a3a8..131e615 100644 --- a/src/sftpd.c +++ b/src/sftpd.c @@ -1,616 +1,619 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ SET_FLAG(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { - if (FD_ISSET(t->socket, &srv->write_ready)) + if (FD_ISSET(t->socket, &srv->write_ready)) { /* in case of downloading */ FD_CLR(t->socket, &srv->write_ready); + close(t->local_fd); + } - if (FD_ISSET(t->socket, &srv->read_ready)) + if (FD_ISSET(t->socket, &srv->read_ready)) { /* in case of uploading */ FD_CLR(t->socket, &srv->read_ready); + close(t->local_fd); + } - close(t->local_fd); close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); SET_FLAG(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) FD_CLR(conn->sock_fd, &(srv->read_ready)); else BUG(); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_client(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { PRINT_DEBUG("'select()' failed with error: %s\n", strerror(errno)); if (errno == EBADF) { struct connection *c; struct transport *t; int ret; /* * if we get EBADF, it means that there is(are) * bad descriptor(s) in the sets. So, find them * and kill. */ TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret < 0) { SET_FLAG(c->c_flags, C_KILL); } else { if (!QUERY_FLAG(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret < 0) { SET_FLAG(t->t_flags, T_KILL); } } } } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!QUERY_FLAG(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); PRINT_DEBUG("Timeout! Closing connection.\n"); SET_FLAG(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (QUERY_FLAG(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); } else { /* it can happen when a client close a socket */ PRINT_DEBUG("There is no data, connection will be killed.\n"); } SET_FLAG(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (QUERY_FLAG(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (QUERY_FLAG(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); SET_FLAG(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); SET_FLAG(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE or KILL */ if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd)) continue; if (QUERY_FLAG(t->t_flags, T_RETR)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } else if (QUERY_FLAG(t->t_flags, T_STOR)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } else { BUG(); } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_client(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
1e680ea5e1f14d4d81eadd578c4bb1e3f5b682ad
@MAINT: some code clean up.
diff --git a/src/sftpd.c b/src/sftpd.c index db40204..242a3a8 100644 --- a/src/sftpd.c +++ b/src/sftpd.c @@ -1,622 +1,616 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ SET_FLAG(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { - close_socket(t->socket); - - /* - * It doesn't matter whether a local file - * is opened or not, just try to close; - */ - close(t->local_fd); + if (FD_ISSET(t->socket, &srv->write_ready)) + /* in case of downloading */ + FD_CLR(t->socket, &srv->write_ready); - /* in case of downloading */ - FD_CLR(t->socket, &srv->write_ready); + if (FD_ISSET(t->socket, &srv->read_ready)) + /* in case of uploading */ + FD_CLR(t->socket, &srv->read_ready); - /* in case of uploading */ - FD_CLR(t->socket, &srv->read_ready); + close(t->local_fd); + close_socket(t->socket); /* clean transport before next using */ bzero(t, sizeof(transport)); SET_FLAG(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { - FD_CLR(conn->sock_fd, &(srv->read_ready)); + if (FD_ISSET(conn->sock_fd, &(srv->read_ready))) + FD_CLR(conn->sock_fd, &(srv->read_ready)); + else + BUG(); + close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_client(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void -check_received_signals(void) +check_received_signals() { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } -static int -clear_bad_fd(void) -{ - struct connection *c; - struct transport *t; - - int processed = 0; - int ret; - - FUNC_ENTRY(); - - TAILQ_FOREACH(c, &conn_list, entries) { - t = c->transport; - - ret = check_socket(c->sock_fd); - if (ret == -1) { - SET_FLAG(c->c_flags, C_KILL); - processed++; - } else { - if (!QUERY_FLAG(t->t_flags, T_FREE)) { - ret = check_socket(t->socket); - if (ret == -1) { - SET_FLAG(t->t_flags, T_KILL); - processed++; - } - } - } - } - - FUNC_EXIT_INT(processed); - return processed; -} - static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { + PRINT_DEBUG("'select()' failed with error: %s\n", + strerror(errno)); + if (errno == EBADF) { - PRINT_DEBUG("'select()' failed with errno %d: %s\n", - errno, strerror(errno)); + struct connection *c; + struct transport *t; + int ret; /* - * It marks connections with bad descriptors. + * if we get EBADF, it means that there is(are) + * bad descriptor(s) in the sets. So, find them + * and kill. */ - clear_bad_fd(); + TAILQ_FOREACH(c, &conn_list, entries) { + t = c->transport; + + ret = check_socket(c->sock_fd); + if (ret < 0) { + SET_FLAG(c->c_flags, C_KILL); + } else { + if (!QUERY_FLAG(t->t_flags, T_FREE)) { + ret = check_socket(t->socket); + if (ret < 0) { + SET_FLAG(t->t_flags, T_KILL); + } + } + } + } } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!QUERY_FLAG(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); + PRINT_DEBUG("Timeout! Closing connection.\n"); SET_FLAG(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (QUERY_FLAG(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ - if (avail_b > RECV_BUF_SIZE) + if (avail_b > RECV_BUF_SIZE) { send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); + PRINT_DEBUG("Buffer is overflowed, connection will be killed.\n"); + } else { + /* it can happen when a client close a socket */ + PRINT_DEBUG("There is no data, connection will be killed.\n"); + } SET_FLAG(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (QUERY_FLAG(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (QUERY_FLAG(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); SET_FLAG(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); SET_FLAG(t->t_flags, T_KILL); again: FUNC_EXIT_VOID(); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE or KILL */ if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd)) continue; if (QUERY_FLAG(t->t_flags, T_RETR)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } else if (QUERY_FLAG(t->t_flags, T_STOR)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } else { BUG(); } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_client(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
6f878384fe225026b754edddd3f4ba5536ffaa1f
@MAINT: while an unallocated free, use BUG() macro instead of syslog.
diff --git a/src/mem.c b/src/mem.c index 035c434..b620a02 100644 --- a/src/mem.c +++ b/src/mem.c @@ -1,179 +1,179 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <syslog.h> /* local headers */ #include <debug.h> #include <list.h> /* * Head of the memory list, uses for memory debugging. */ static TAILQ_HEAD(mem_list, __mnode) mem_head = TAILQ_HEAD_INITIALIZER(mem_head); static u_long bytes_allocated; static u_long bytes_freed; struct __mnode { void *addr; size_t size; const char *file; const char *func; int line; /* * This holds the pointers to the next and * previous entries in the tail queue. */ TAILQ_ENTRY(__mnode) entries; }; /** * __calloc - allocates memory for an array of * nmemb elements of size bytes each and returns * a pointer to the allocated memory. * * @nmemb: number of elements; * @size: size of each element; * @file: name of the file where __calloc is called; * @func: name of the function where __calloc is called; * @line: the line number where __calloc is called. */ void * __calloc(size_t nmemb, size_t size, const char *file, const char *func, int line) { struct __mnode *m = calloc(1, sizeof(*m)); void *ptr = calloc(nmemb, size); m->size = size * nmemb; m->addr = ptr; m->file = file; m->func = func; m->line = line; bytes_allocated += m->size; TAILQ_INSERT_TAIL(&mem_head, m, entries); return ptr; } /** * __malloc - allocates size bytes and returns a * pointer to the allocated memory, and adds __mnode * to the memory list. * * @size: size of memory; * @file: name of the file where __malloc is called; * @func: name of the function where __malloc is called; * @line: the line number where __malloc is called. */ void * __malloc(size_t size, const char *file, const char *func, int line) { struct __mnode *m = calloc(1, sizeof(*m)); void *ptr = malloc(size); m->size = size; m->addr = ptr; m->file = file; m->func = func; m->line = line; bytes_allocated += size; TAILQ_INSERT_TAIL(&mem_head, m, entries); return ptr; } /** * __free - frees the memory space pointed to by ptr, * and removes __mndoe from the mem list, if ptr is NULL, * no operation is performed. * * @ptr: pointer to the allocated memory; * @file: name of the file where __free is called; * @func: name of the function where __free is called; * @line: the line number where __free is called. */ void __free(void *ptr, const char *file, const char *func, int line) { struct __mnode *item; int found = 0; TAILQ_FOREACH(item, &mem_head, entries) { if (item->addr == ptr) { bytes_allocated -= item->size; bytes_freed += item->size; TAILQ_REMOVE(&mem_head, item, entries); free(item->addr); free(item); found++; break; } } - - if (!found) - syslog(LOG_ERR, "unallocated free of %p by %s in %s at line %d\n", - ptr, func, file, line); + + if (!found) { + PRINT_DEBUG("unallocated free of %p by %s in %s at line %d\n", ptr, func, file, line); + BUG(); + } } /** * __realloc - changes the size of the memory * block pointed to by ptr to size bytes. * * @old_addr: block of memory pointed to by old_addr; * @size: size of memory; * @file: name of the file where __realloc is called; * @func: name of the function where __realloc is called; * @line: the line number where __realloc is called. */ void * __realloc(void *old_addr, size_t size, const char *file, const char *func, int line) { void *new_addr = __malloc(size, file, func, line); if (new_addr && old_addr) { memcpy(new_addr, old_addr, size); __free(old_addr, file, func, line); } return new_addr; } /** * __strdup - returns a pointer to a new string which * is a duplicate of the string s. * * @str: string that will duplicate; * @file: name of the file where __strdup is called; * @func: name of the function where __strdup is called; * @line: the line number where __strdup is called. */ char * __strdup(const char *str, const char *file, const char *func, int line) { size_t len; char *new_str; len = strlen(str) + 1; /* +1 for '\0' */ new_str = __malloc(len, file, func, line); if (str && new_str) strncpy(new_str, str, len); return new_str; } /** * Returns information about how much * memory we are using at present. */ u_long __get_mem_status(void) { return bytes_allocated; }
urezki/sftpd
930a9af2c7f332e83df6b7e44f11ebd23a679384
@MAINT: use "SET_FLAG" instead "destroy_transport" routine in order to destroy transport.
diff --git a/src/sftpd.c b/src/sftpd.c index 9eabea3..db40204 100644 --- a/src/sftpd.c +++ b/src/sftpd.c @@ -1,622 +1,622 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static void print_usage(char **argv) { fprintf(stderr, "\n" "Usage: %s [OPTION]\n" " -d run server as daemon (background mode)\n" " -h show this help message\n" , argv[0]); exit(1); } static int unlink_pid_file(const char *full_path) { int ret; ret = unlink(full_path); if (ret < 0) PRINT_DEBUG("unlink error: %s\n", strerror(errno)); return ret; } static int create_pid_file(const char *full_path) { FILE *pidfile; int pidfd; int pid; int ret; pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (pidfd != -1) { pidfile = fdopen(pidfd, "w"); if (pidfile) { fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { close(pidfd); PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); pidfd = -1; } } else { if (errno == EEXIST) { pidfile = fopen(full_path, "r+"); if (pidfile) { (void) fscanf(pidfile, "%d", &pid); (void) fclose(pidfile); ret = kill(pid, 0); if (ret < 0 && errno == ESRCH) { PRINT_DEBUG("pid file %s exists, but the process is not alive", full_path); ret = unlink_pid_file(full_path); if (ret == 0) return create_pid_file(full_path); } } } PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } return pidfd; } static void init_daemon(void) { int i = 0; FUNC_ENTRY(); if (fork() != 0) /* quit first parent */ exit(0); if (setsid() < 0) perror("setsid"); if (fork() != 0) /* quit second parent */ exit(0); chdir("/"); umask(0); for (i = 0; i < 64; i++) close(i); i = open(DEV_NULL, O_RDWR); /* stdin */ dup(i); /* stdout */ dup(i); /* stderr */ i = create_pid_file(PID_FILE); if (i < 0) exit(-1); FUNC_EXIT_VOID(); } static ftpd * init_sftpd(int argc, char **argv) { ftpd *sftpd = NULL; int fork_flag = 0; int ch; FUNC_ENTRY(); while ((ch = getopt(argc, argv, "dh")) != -1) { switch (ch) { case 'd': fork_flag = 1; break; case 'h': print_usage(argv); break; default: ; } } if (fork_flag) init_daemon(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ SET_FLAG(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { close_socket(t->socket); - /* - * If t_flags is RETR or STOR, it means that we have already - * opened local file, that is why we have to close it, - * otherwise we don't have to do it. - */ - if (QUERY_FLAG(t->t_flags, T_RETR)) { - close(t->local_fd); - FD_CLR(t->socket, &srv->write_ready); - } else if (QUERY_FLAG(t->t_flags, T_STOR)) { - close(t->local_fd); - FD_CLR(t->socket, &srv->read_ready); - } /* - * We have to clean transport before next using !!! + * It doesn't matter whether a local file + * is opened or not, just try to close; */ + close(t->local_fd); + + /* in case of downloading */ + FD_CLR(t->socket, &srv->write_ready); + + /* in case of uploading */ + FD_CLR(t->socket, &srv->read_ready); + + /* clean transport before next using */ bzero(t, sizeof(transport)); SET_FLAG(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { FD_CLR(conn->sock_fd, &(srv->read_ready)); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void accept_client(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals(void) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } unlink_pid_file(PID_FILE); close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int clear_bad_fd(void) { struct connection *c; struct transport *t; int processed = 0; int ret; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret == -1) { SET_FLAG(c->c_flags, C_KILL); processed++; } else { if (!QUERY_FLAG(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret == -1) { SET_FLAG(t->t_flags, T_KILL); processed++; } } } } FUNC_EXIT_INT(processed); return processed; } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { if (errno == EBADF) { PRINT_DEBUG("'select()' failed with errno %d: %s\n", errno, strerror(errno)); /* * It marks connections with bad descriptors. */ clear_bad_fd(); } sleep(1); } return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!QUERY_FLAG(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); SET_FLAG(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (QUERY_FLAG(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); SET_FLAG(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (QUERY_FLAG(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (QUERY_FLAG(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); - destroy_transport(c); + SET_FLAG(t->t_flags, T_KILL); + again: FUNC_EXIT_VOID(); } static void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); - destroy_transport(c); + SET_FLAG(t->t_flags, T_KILL); + again: FUNC_EXIT_VOID(); } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE or KILL */ if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd)) continue; if (QUERY_FLAG(t->t_flags, T_RETR)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } else if (QUERY_FLAG(t->t_flags, T_STOR)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } else { BUG(); } } FUNC_EXIT_VOID(); } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(argc, argv); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_client(srv->srv_socket, &r_fd, &n_ready); } return 0; }
urezki/sftpd
50f2371b3af4da4f20c48ff8911b3878c68a1739
@MAINT: changed BUG macro, because of ARM arch. It doesn't have "ud2"instruction as it has x86. So, the simplest way to do following: #define BUG() (*(int *)0 = 0)
diff --git a/include/debug.h b/include/debug.h index 5faa0f0..0aeece2 100644 --- a/include/debug.h +++ b/include/debug.h @@ -1,56 +1,56 @@ #ifndef __DEBUG_H__ #define __DEBUG_H__ -/* Raise invalid opcode exception */ -#define BUG() __asm__ __volatile__("ud2\n") +/* just causes a Segmentation Fault */ +#define BUG() (*(int *)0 = 0) #define __DEBUG_MSG__ //#define __DEBUG_FUNC__ #ifdef __DEBUG_MSG__ /* DEBUG MSG */ #define PRINT_DEBUG(fmt,arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); } while (0) #else #define PRINT_DEBUG(fmt,arg...) \ do { } while(0) #endif /* __DEBUG_MSG__ */ #define FATAL_ERROR(fmt, arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); \ exit(-1); } while (0) #ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ #define FUNC_ENTRY() do { \ fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_VOID() do { \ fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_INT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ __FUNCTION__, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_UINT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ __FUNCTION__, value, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_PTR(ptr) do { \ fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ __FUNCTION__, ptr); \ fflush(stdout); } while (0) #else #define FUNC_ENTRY() do { } while(0) #define FUNC_EXIT_VOID() do { } while(0) #define FUNC_EXIT_INT(value) do { } while(0) #define FUNC_EXIT_UINT(value) do { } while(0) #define FUNC_EXIT_PTR(ptr) do { } while(0) #endif /* __DEBUG_FUNC__ */ #endif /* __DEBUG_H__ */
urezki/sftpd
dcf05be3251f71126d3bc5e3a5acb998e8b032e9
@MAINT: expand_to_abs is renamed to translate_path, a few messages/comments were added as well.
diff --git a/src/cmds.c b/src/cmds.c index 99ee780..587ba03 100644 --- a/src/cmds.c +++ b/src/cmds.c @@ -1,695 +1,695 @@ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <strings.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <shadow.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <utils.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #include <ls.h> static void cmd_user(struct connection *); static void cmd_pass(struct connection *); static void cmd_port(struct connection *); static void cmd_pasv(struct connection *); static void cmd_list(struct connection *); static void cmd_cdup(struct connection *); static void cmd_retr(struct connection *); static void cmd_size(struct connection *); static void cmd_noop(struct connection *); static void cmd_syst(struct connection *); static void cmd_type(struct connection *); static void cmd_stru(struct connection *); static void cmd_quit(struct connection *); static void cmd_feat(struct connection *); static void cmd_abor(struct connection *); static void cmd_stor(struct connection *); static void cmd_dele(struct connection *); static void cmd_help(struct connection *); static void cmd_allo(struct connection *); static void cmd_pwd(struct connection *); static void cmd_cwd(struct connection *); static void cmd_rmd(struct connection *); static void cmd_mkd(struct connection *); /* static void cmd_nlst(struct connection *); */ /* static void cmd_mode(struct connection *); */ /* static void cmd_mdtm(struct connection *); */ struct cmd_handler { char cmd_name[10]; char arg; void (*cmd_handler)(struct connection *const); char need_root; char cmd_len; }; static const struct cmd_handler cmd_table[] = { { "user", 1, cmd_user, 1, 4 }, { "pass", 1, cmd_pass, 1, 4 }, { "port", 1, cmd_port, 1, 4 }, { "pasv", 0, cmd_pasv, 0, 4 }, { "list", 0, cmd_list, 1, 4 }, { "cdup", 0, cmd_cdup, 0, 4 }, { "retr", 1, cmd_retr, 0, 4 }, { "size", 1, cmd_size, 0, 4 }, { "noop", 0, cmd_noop, 0, 4 }, { "syst", 0, cmd_syst, 0, 4 }, { "type", 0, cmd_type, 0, 4 }, { "abor", 0, cmd_abor, 0, 4 }, { "stru", 0, cmd_stru, 0, 4 }, { "quit", 0, cmd_quit, 0, 4 }, { "feat", 0, cmd_feat, 0, 4 }, { "help", 0, cmd_help, 0, 4 }, // { "mdtm", 0, cmd_mdtm, 0, 4 }, /* not implemented */ #ifdef UPLOAD_SUPPORT { "stor", 0, cmd_stor, 0, 4 }, { "dele", 1, cmd_dele, 0, 4 }, { "rmd", 1, cmd_rmd, 0, 3 }, { "mkd", 1, cmd_mkd, 0, 3 }, #endif // { "nlst", 0, cmd_nlst, 0, 4 }, /* not implemented */ // { "mode", 0, cmd_mode, 0, 4 }, /* not implemented */ { "allo", 0, cmd_allo, 0, 4 }, { "pwd", 0, cmd_pwd, 0, 3 }, { "cwd", 1, cmd_cwd, 0, 3 }, { " ", 0, NULL, 0, 0 } }; -static void -expand_to_abs(struct connection *conn) +static int +translate_path(const char *root, const char *cur, char *dst) { - char *abs_path; - char *tmp_path; - char *cmd_arg; + char absolute_path[PATH_MAX] = {'\0'}; + char tmp_path[PATH_MAX] = {'\0'}; char *dot; - - abs_path = calloc(PATH_MAX, sizeof(char)); - tmp_path = calloc(PATH_MAX, sizeof(char)); + int n; - cmd_arg = strchr(conn->recv_buf, ' '); - if (cmd_arg == NULL || cmd_arg[1] == '\0') - goto end; + if (root == NULL || cur == NULL || dst == NULL) + return -1; + + if (*dst == '/' || *dst == '~') { + /* 1) cd / 2) cd ~/ 3) cd ~ */ + n = snprintf(absolute_path, PATH_MAX, "%s%s", root, + *(dst + 1) == '/' ? dst + 2 : dst + 1); + } else { + /* 1) cd foo/ */ + n = snprintf(absolute_path, PATH_MAX, "%s%s", cur, dst); + } + + /* /home/urezki/../ftp/.. */ + if ((dot = strrchr(absolute_path, '.'))) + if (*(dot - 1) == '.' && *(dot + 1) == '\0') + strcat(absolute_path, "/"); - cmd_arg = cmd_arg + 1; - if (*cmd_arg == '/' || *cmd_arg == '~') - snprintf(abs_path, PATH_MAX, "%s%s", conn->root_dir, - *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); - else - snprintf(abs_path, PATH_MAX, "%s%s", conn->curr_dir, cmd_arg); /* - * If we have such situation: /home/demon/../ftp/.. - * we should add '/' to the end of the string. + * Here we can have following combinations: + * 1) /home/urezki/../ftp/../ + * 2) /home/urezki/ */ - if ((dot = strrchr(abs_path, '.'))) - if (*(dot - 1) == '.' && *(dot + 1) == '\0' ) - strcat(abs_path, "/"); - - while ((dot = strstr(abs_path, "/../"))) { + while ((dot = strstr(absolute_path, "/../"))) { char *s_pp = NULL; - if (dot == abs_path) + if (dot == absolute_path) s_pp = dot; else s_pp = (dot - 1); - - while (s_pp != abs_path && *s_pp != '/') + + while (s_pp != absolute_path && *s_pp != '/') s_pp--; *(s_pp + 1) = '\0'; - snprintf(tmp_path, PATH_MAX, "%s%s", abs_path, dot + 4); - strncpy(abs_path, tmp_path, PATH_MAX); + snprintf(tmp_path, PATH_MAX, "%s%s", absolute_path, dot + 4); + snprintf(absolute_path, PATH_MAX, "%s", tmp_path); } - *cmd_arg = '\0'; - strcat(cmd_arg, abs_path); -end: - free(abs_path); - free(tmp_path); + snprintf(dst, PATH_MAX, "%s", absolute_path); + return 0; } static int is_path_ok(struct connection *conn) { char *cmd_arg; struct stat st; - - /* build abs path */ - expand_to_abs(conn); + int ret; cmd_arg = strchr(conn->recv_buf, ' '); if (cmd_arg == NULL || cmd_arg[1] == '\0') goto fail; /* get pointer to the arg */ cmd_arg = cmd_arg + 1; + ret = translate_path(conn->root_dir, conn->curr_dir, cmd_arg); + if (ret < 0) + goto fail; - /* checking sysmlyks ... */ + /* check symbolic links */ if (stat(cmd_arg, &st) != -1) { if (!S_ISLNK(st.st_mode)) { char buf[1024] = {'\0'}; int len; len = readlink(cmd_arg, buf, sizeof(buf) - 1); if (len != -1) { buf[len] = '\0'; *cmd_arg = '\0'; strcat(cmd_arg, buf); } } } - + if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) return 1; + fail: return 0; } static void cmd_feat(struct connection *conn) { const char *const feat = "211-Features:\r\n" " SIZE\r\n" "211 End\r\n"; FUNC_ENTRY(); /* sending informations about features. */ send_data(conn->sock_fd, feat, strlen(feat), 0); FUNC_EXIT_VOID(); } /** * recv_buf looks like: "USER anonymous'\0'" * recv_buf_len is 14, in this case. */ static void cmd_user(struct connection *conn) { char tmp_buf[120] = {'\0'}; int rejected = 0; FUNC_ENTRY(); if (strstr(conn->recv_buf, "anonymous") || strstr(conn->recv_buf, "ftp")) { (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " "login ok, send your complete email address " "as your password"); (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); } else { char *user_name; /* skipping "USER " */ user_name = strchr(conn->recv_buf, ' '); if (user_name != NULL && conn->recv_buf_len > 4) { (void) strncpy(conn->user_name, user_name + 1, sizeof(conn->user_name)); (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " "required for", conn->user_name); } else { (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); rejected = 1; /* mark as was rejected */ } } send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); FUNC_EXIT_VOID(); } static void cmd_pass(struct connection *conn) { struct spwd *p_shadow; struct passwd *p; FUNC_ENTRY(); p = getpwnam(conn->user_name); if (p != NULL) { char *user_pass; conn->uid = p->pw_uid; conn->gid = p->pw_gid; (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') (void) strcat(conn->root_dir, "/"); (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') (void) strcat(conn->curr_dir, "/"); user_pass = strchr(conn->recv_buf, ' '); /* in case of anonymous access */ if (!strncmp(conn->user_name, "ftp", 3)) { SET_FLAG(conn->c_flags, C_AUTH); } else if (user_pass != NULL && conn->recv_buf_len > 4) { char *p_crypt; p_crypt = crypt(user_pass + 1, p->pw_passwd); if (p_crypt != NULL) { if (!strcmp(p_crypt, p->pw_passwd)) { SET_FLAG(conn->c_flags, C_AUTH); } else { /* checking shadow pass */ p_shadow = getspnam(conn->user_name); if (p_shadow != NULL) p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); if (p_crypt != NULL) if (!strcmp(p_crypt, p_shadow->sp_pwdp)) SET_FLAG(conn->c_flags, C_AUTH); } } } } if (QUERY_FLAG(conn->c_flags, C_AUTH)) { send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); PRINT_DEBUG("%s user logged in\n", conn->user_name); chdir(conn->root_dir); } else { send_cmd(conn->sock_fd, 530, "Login incorrect"); PRINT_DEBUG("%s Login incorrect\n", conn->user_name); } FUNC_EXIT_VOID(); } /** * cmd_port - this function find out the * port number, which should be used afterwards, * and than connect to the client. * * for instance: PORT 192,168,5,12,4,1 */ static void cmd_port(struct connection *conn) { char *ip_address = NULL; int data_port = 0; transport *t; int ret; FUNC_ENTRY(); t = conn->transport; ip_address = strchr(conn->recv_buf, ' '); if (QUERY_FLAG(t->t_flags, T_FREE)) { short int a0, a1, a2, a3, p0, p1; ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1); data_port = p0 * 256 + p1; if (data_port > 1024 && ret == 6) { int len; t->socket = get_ipv4_socket(); t->data_port = data_port; activate_reuseaddr(t->socket); t->r_info.sin_port = htons(DATA_PORT); t->r_info.sin_family = AF_INET; len = sizeof(t->r_info); bind(t->socket, (SA *)&t->r_info, len); t->r_info.sin_family = AF_INET; t->r_info.sin_port = htons(t->data_port); t->r_info.sin_addr.s_addr = htonl( ((unsigned char)(a0) << 24) + ((unsigned char)(a1) << 16) + ((unsigned char)(a2) << 8) + ((unsigned char)(a3))); ret = connect_timeout(t->socket, (SA *)&t->r_info, 5); if (ret == 0) { /* we are in a port mode */ SET_FLAG(t->t_flags, T_PORT); activate_nonblock(t->socket); send_cmd(conn->sock_fd, 220, "PORT command successful"); } else { send_cmd(conn->sock_fd, 425, "Can't open data connection"); PRINT_DEBUG("Can't connect to %s:%d\n", ip_address, data_port); } } } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); } FUNC_EXIT_VOID(); } static void cmd_pasv(struct connection *conn) { struct sockaddr_in addr; int listen_sock; transport *trans; socklen_t len; FUNC_ENTRY(); trans = conn->transport; if (QUERY_FLAG(trans->t_flags, T_FREE)) { memset(&addr, 0, sizeof(addr)); listen_sock = get_ipv4_socket(); activate_reuseaddr(listen_sock); len = sizeof(addr); getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); addr.sin_port = 0; bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); len = sizeof(addr); getsockname(listen_sock, (struct sockaddr *)&addr, &len); listen(listen_sock, 1); /* send that we are ready */ send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, (htonl(addr.sin_addr.s_addr) & 0x000000ff), (htons(addr.sin_port) & 0xff00) >> 8, (htons(addr.sin_port) & 0x00ff)); /* * listen_sock should be added to the poll, and checked by select, * after that when socket is ready do accept. */ trans->socket = accept_timeout(listen_sock, (SA *)&trans->r_info, 5); if (trans->socket != -1) { /* we are in PASV mode */ SET_FLAG(trans->t_flags, T_PASV); activate_nonblock(trans->socket); } else { send_cmd(conn->sock_fd, 500, "Accepting error, sorry"); PRINT_DEBUG("Accepting error. sorry\n"); } /* we needn't listen further */ close_socket(listen_sock); } else { send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); PRINT_DEBUG("Sorry, only one transfer at once\n"); } FUNC_EXIT_VOID(); } static void cmd_retr(struct connection *conn) { transport *t; char *l_file; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); goto leave; } if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); t->local_fd = open(l_file + 1, O_RDONLY); if (t->local_fd != -1) { fstat(t->local_fd, &t->st); FD_SET(t->socket, &srv->write_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); SET_FLAG(t->t_flags, T_RETR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } if (!QUERY_FLAG(t->t_flags, T_RETR)) SET_FLAG(t->t_flags, T_KILL); leave: FUNC_EXIT_VOID(); } static void cmd_allo(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); FUNC_EXIT_VOID(); } /** * cmd_rmd - remove directory * * @conn: */ static void cmd_rmd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' ') + 1; ret = rmdir(dir_name); if (ret != -1) send_cmd(conn->sock_fd, 250, "Directory deleted."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /** * cmd_mkd - make directory RFC ??? * * @conn: data struct that describes one connection. */ static void cmd_mkd(struct connection *conn) { char *dir_name; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { dir_name = strchr(conn->recv_buf, ' '); ret = mkdir(dir_name + 1, 0755); if (ret != -1) send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { send_cmd(conn->sock_fd, 550, "Bad path."); } FUNC_EXIT_VOID(); } static void cmd_stor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { if (is_path_ok(conn)) { char *l_file = strchr(conn->recv_buf, ' ') + 1; t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (t->local_fd != -1) { FD_SET(t->socket, &srv->read_ready); send_cmd(conn->sock_fd, 150, "Binary mode."); SET_FLAG(t->t_flags, T_STOR); } else { send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); SET_FLAG(t->t_flags, T_KILL); } } } else { send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); } FUNC_EXIT_VOID(); } static void cmd_size(struct connection *conn) { transport *tr; char *l_file; int ret; FUNC_ENTRY(); tr = conn->transport; if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' '); ret = lstat(l_file + 1, &tr->st); if (ret != -1) send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } /* static void */ /* cmd_mdtm(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ static void cmd_list(struct connection *conn) { transport *t = conn->transport; FUNC_ENTRY(); if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { activate_nodelay(t->socket); do_list(conn); SET_FLAG(t->t_flags, T_KILL); } FUNC_EXIT_VOID(); } /* static void */ /* cmd_nlst(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */ /* FUNC_EXIT_VOID(); */ /* } */ static void cmd_dele(struct connection *conn) { char *l_file; int ret; FUNC_ENTRY(); if (is_path_ok(conn)) { l_file = strchr(conn->recv_buf, ' ') + 1; ret = unlink(l_file); if (ret != -1) send_cmd(conn->sock_fd, 250, "File deleted OK."); else send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } else { errno = ENOENT; send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); } FUNC_EXIT_VOID(); } static void cmd_noop(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "NOOP command successful."); FUNC_EXIT_VOID(); } static void cmd_syst(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); FUNC_EXIT_VOID(); } static void cmd_type(struct connection *conn) { FUNC_ENTRY(); send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); FUNC_EXIT_VOID(); } static void cmd_abor(struct connection *conn) { transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { SET_FLAG(t->t_flags, T_KILL); send_cmd(conn->sock_fd, 426, "Transport aborted."); } send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); FUNC_EXIT_VOID(); } /* static void */ /* cmd_mode(struct connection *conn) */ /* { */ /* FUNC_ENTRY(); */
urezki/sftpd
30af67a13e7f722ad7c79f845bb857681c7603db
@MAINT: 1) Added print usage function; 2) The server can go to the background mode on demand; 3) Create pid file while starting, and remove it while stopping.
diff --git a/src/sftpd.c b/src/sftpd.c index d8029d6..9eabea3 100644 --- a/src/sftpd.c +++ b/src/sftpd.c @@ -1,542 +1,622 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> +#define PID_FILE "/var/run/sftpd.pid" #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; -static ftpd *init_sftpd(void); -/* static void init_daemon(void); */ -static int process_timeouted_sockets(int); -static void process_commands(fd_set *, int *); -static void process_transfers(fd_set *, fd_set *, int *); -static int process_clients_marked_as_destroy(void); +static void +print_usage(char **argv) +{ + fprintf(stderr, "\n" + "Usage: %s [OPTION]\n" + " -d run server as daemon (background mode)\n" + " -h show this help message\n" + , argv[0]); -static connection *add_connection(int); -static void destroy_connection(connection *); -static void destroy_transport(connection *); -static int clear_bad_fd(); + exit(1); +} -static inline void download_file(struct connection *); -static inline void upload_file(struct connection *); +static int +unlink_pid_file(const char *full_path) +{ + int ret; -static void -accept_client(int socket, fd_set *r_fd, int *n_ready) + ret = unlink(full_path); + if (ret < 0) + PRINT_DEBUG("unlink error: %s\n", strerror(errno)); + + return ret; +} + +static int +create_pid_file(const char *full_path) { - struct sockaddr_in r_addr; - connection *conn = NULL; - socklen_t cli_len; - int conn_fd; + FILE *pidfile; + int pidfd; + int pid; + int ret; - /* - * We have to process situation when clients - * send RST packet, but we are waiting for a connection - * from other side ... - */ - if (FD_ISSET(socket, r_fd) && *n_ready > 0) { - cli_len = sizeof(r_addr); - conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); - if (conn_fd != -1) { - activate_nodelay(conn_fd); - conn = add_connection(conn_fd); - if (conn != NULL) - send_cmd(conn->sock_fd, 220, "I'm ready"); + pidfd = open(full_path, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); + if (pidfd != -1) { + pidfile = fdopen(pidfd, "w"); + if (pidfile) { + fchmod(pidfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); + fprintf(pidfile, "%d\n", getpid()); + fclose(pidfile); } else { - PRINT_DEBUG("accept() error: %s\n", strerror(errno)); + close(pidfd); + PRINT_DEBUG("fdopen error: %s\n", strerror(errno)); + pidfd = -1; + } + } else { + if (errno == EEXIST) { + pidfile = fopen(full_path, "r+"); + if (pidfile) { + (void) fscanf(pidfile, "%d", &pid); + (void) fclose(pidfile); + + ret = kill(pid, 0); + if (ret < 0 && errno == ESRCH) { + PRINT_DEBUG("pid file %s exists, but the process is not alive", + full_path); + + ret = unlink_pid_file(full_path); + if (ret == 0) + return create_pid_file(full_path); + } + } } - (*n_ready)--; + PRINT_DEBUG("open %s error: %s\n", full_path, strerror(errno)); } + + return pidfd; } static void -check_received_signals(void) +init_daemon(void) { - if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { - struct connection *c; + int i = 0; - TAILQ_FOREACH(c, &conn_list, entries) { - destroy_connection(c); - } + FUNC_ENTRY(); - close(srv->srv_socket); - free(srv); - exit(1); /* finish up */ - } -} + if (fork() != 0) /* quit first parent */ + exit(0); + if (setsid() < 0) + perror("setsid"); -static int -wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) -{ - struct timeval time; - int n_ready; + if (fork() != 0) /* quit second parent */ + exit(0); - *r_fd = sftpd->read_ready; - *w_fd = sftpd->write_ready; + chdir("/"); + umask(0); - time.tv_sec = sec; - time.tv_usec = 0; + for (i = 0; i < 64; i++) + close(i); - n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); - if (n_ready < 0) { - if (errno == EBADF) { - PRINT_DEBUG("'select()' failed with errno %d: %s\n", - errno, strerror(errno)); - /* - * We mark bad descriptors, and below - * will clean it up. - */ - clear_bad_fd(); - } + i = open(DEV_NULL, O_RDWR); /* stdin */ + dup(i); /* stdout */ + dup(i); /* stderr */ - sleep(1); - } + i = create_pid_file(PID_FILE); + if (i < 0) + exit(-1); - return n_ready; + FUNC_EXIT_VOID(); } -int main(int argc, char **argv) +static ftpd * +init_sftpd(int argc, char **argv) { - fd_set r_fd; - fd_set w_fd; - int n_ready; + ftpd *sftpd = NULL; + int fork_flag = 0; + int ch; - /* srv is global */ - srv = init_sftpd(); + FUNC_ENTRY(); - while (1) { - /* wait for any events, max is 1 min. */ - n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); + while ((ch = getopt(argc, argv, "dh")) != -1) { + switch (ch) { + case 'd': + fork_flag = 1; + break; - /* check signals */ - check_received_signals(); + case 'h': + print_usage(argv); + break; - /* deal with exist transfers */ - process_transfers(&r_fd, &w_fd, &n_ready); + default: + ; + } + } - /* process FTP's commands */ - process_commands(&r_fd, &n_ready); + if (fork_flag) + init_daemon(); - /* - * We allow 10 minutes to users, for to do - * something, after that clients are dropped. - */ - process_timeouted_sockets(10); - process_clients_marked_as_destroy(); + signal_handle(SIGHUP); + signal_handle(SIGTERM); + signal_ignore(SIGPIPE); - /* accept new clients, if they are */ - accept_client(srv->srv_socket, &r_fd, &n_ready); - } + /* allocate memory for our new ftp server */ + sftpd = (ftpd *) calloc(1, sizeof(ftpd)); + if (sftpd == NULL) + FATAL_ERROR("error allocating memory\n"); - return 0; + /* init some stuff */ + sftpd->client_count = 0; + sftpd->srv_socket = -1; + + sftpd->srv_socket = start_tcp_listen(21, 4, 30); + if (sftpd->srv_socket == -1) + FATAL_ERROR("error starting tcp listen\n"); + + FD_ZERO(&(sftpd->read_ready)); + FD_ZERO(&(sftpd->write_ready)); + FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); + + /* initialize list */ + TAILQ_INIT(&conn_list); + + FUNC_EXIT_PTR(sftpd); + return sftpd; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ SET_FLAG(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } -static void -destroy_connection(connection *conn) -{ - struct connection *c; - - FUNC_ENTRY(); - - TAILQ_FOREACH(c, &conn_list, entries) { - if (c == conn) { - FD_CLR(conn->sock_fd, &(srv->read_ready)); - close_socket(conn->sock_fd); - srv->client_count--; - TAILQ_REMOVE(&conn_list, c, entries); - destroy_transport(conn); - free(conn->transport); - free(conn); - break; /* !!! */ - } - } - - FUNC_EXIT_VOID(); -} - static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { close_socket(t->socket); /* * If t_flags is RETR or STOR, it means that we have already * opened local file, that is why we have to close it, * otherwise we don't have to do it. */ if (QUERY_FLAG(t->t_flags, T_RETR)) { close(t->local_fd); FD_CLR(t->socket, &srv->write_ready); } else if (QUERY_FLAG(t->t_flags, T_STOR)) { close(t->local_fd); FD_CLR(t->socket, &srv->read_ready); } /* * We have to clean transport before next using !!! */ bzero(t, sizeof(transport)); SET_FLAG(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } -/* static void */ -/* init_daemon(void) */ -/* { */ -/* int i = 0; */ +static void +destroy_connection(connection *conn) +{ + struct connection *c; -/* FUNC_ENTRY(); */ - -/* if (fork() != 0) /\* quit first parent *\/ */ -/* exit(0); */ -/* if (setsid() < 0) */ -/* perror("setsid"); */ + FUNC_ENTRY(); -/* if (fork() != 0) /\* quit second parent *\/ */ -/* exit(0); */ - -/* chdir("/"); */ -/* umask(0); */ + TAILQ_FOREACH(c, &conn_list, entries) { + if (c == conn) { + FD_CLR(conn->sock_fd, &(srv->read_ready)); + close_socket(conn->sock_fd); + srv->client_count--; + TAILQ_REMOVE(&conn_list, c, entries); + destroy_transport(conn); + free(conn->transport); + free(conn); + break; /* !!! */ + } + } -/* for (i = 0; i < 64; i++) */ -/* close(i); */ + FUNC_EXIT_VOID(); +} + +static void +accept_client(int socket, fd_set *r_fd, int *n_ready) +{ + struct sockaddr_in r_addr; + connection *conn = NULL; + socklen_t cli_len; + int conn_fd; -/* i = open(DEV_NULL, O_RDWR); /\* stdin *\/ */ -/* dup(i); /\* stdout *\/ */ -/* dup(i); /\* stderr *\/ */ + /* + * We have to process situation when clients + * send RST packet, but we are waiting for a connection + * from other side ... + */ + if (FD_ISSET(socket, r_fd) && *n_ready > 0) { + cli_len = sizeof(r_addr); + conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); + if (conn_fd != -1) { + activate_nodelay(conn_fd); + conn = add_connection(conn_fd); + if (conn != NULL) + send_cmd(conn->sock_fd, 220, "I'm ready"); + } else { + PRINT_DEBUG("accept() error: %s\n", strerror(errno)); + } -/* FUNC_EXIT_VOID(); */ -/* } */ + (*n_ready)--; + } +} -static ftpd * -init_sftpd(void) +static void +check_received_signals(void) { - ftpd *sftpd = NULL; - + if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { + struct connection *c; + + TAILQ_FOREACH(c, &conn_list, entries) { + destroy_connection(c); + } + + unlink_pid_file(PID_FILE); + close(srv->srv_socket); + free(srv); + exit(1); /* finish up */ + } +} + +static int +clear_bad_fd(void) +{ + struct connection *c; + struct transport *t; + + int processed = 0; + int ret; + FUNC_ENTRY(); - signal_handle(SIGHUP); - signal_handle(SIGTERM); - signal_ignore(SIGPIPE); + TAILQ_FOREACH(c, &conn_list, entries) { + t = c->transport; - /* allocate memory for our new ftp server */ - sftpd = (ftpd *) calloc(1, sizeof(ftpd)); - if (sftpd == NULL) - FATAL_ERROR("error allocating memory\n"); - - /* init some stuff */ - sftpd->client_count = 0; - sftpd->srv_socket = -1; + ret = check_socket(c->sock_fd); + if (ret == -1) { + SET_FLAG(c->c_flags, C_KILL); + processed++; + } else { + if (!QUERY_FLAG(t->t_flags, T_FREE)) { + ret = check_socket(t->socket); + if (ret == -1) { + SET_FLAG(t->t_flags, T_KILL); + processed++; + } + } + } + } - sftpd->srv_socket = start_tcp_listen(21, 4, 30); - if (sftpd->srv_socket == -1) - FATAL_ERROR("error starting tcp listen\n"); + FUNC_EXIT_INT(processed); + return processed; +} - FD_ZERO(&(sftpd->read_ready)); - FD_ZERO(&(sftpd->write_ready)); - FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); +static int +wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) +{ + struct timeval time; + int n_ready; - /* initialize list */ - TAILQ_INIT(&conn_list); + *r_fd = sftpd->read_ready; + *w_fd = sftpd->write_ready; - FUNC_EXIT_PTR(sftpd); - return sftpd; + time.tv_sec = sec; + time.tv_usec = 0; + + n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); + if (n_ready < 0) { + if (errno == EBADF) { + PRINT_DEBUG("'select()' failed with errno %d: %s\n", + errno, strerror(errno)); + + /* + * It marks connections with bad descriptors. + */ + clear_bad_fd(); + } + + sleep(1); + } + + return n_ready; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!QUERY_FLAG(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); SET_FLAG(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (QUERY_FLAG(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); SET_FLAG(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (QUERY_FLAG(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (QUERY_FLAG(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } +static void +download_file(struct connection *c) +{ + struct transport *t; + int n; + + FUNC_ENTRY(); + + t = c->transport; + n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); + if (n > 0) + goto again; + + send_cmd(c->sock_fd, 226, "Transfer complete."); + destroy_transport(c); +again: + FUNC_EXIT_VOID(); +} + +static void +upload_file(struct connection *c) +{ + struct transport *t; + char buf[65536]; + int avail; + int size; + + FUNC_ENTRY(); + + t = c->transport; + ioctl(t->socket, FIONREAD, &avail); + avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; + + size = recv_data(t->socket, buf, avail, 0); + if (size > 0) { + int n = write(t->local_fd, buf, size); + if (n == size) + goto again; + else if (n < 0) { + /* ??? */ + } + } + + send_cmd(c->sock_fd, 226, "Transfer complete."); + destroy_transport(c); +again: + FUNC_EXIT_VOID(); +} + static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE or KILL */ if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd)) continue; if (QUERY_FLAG(t->t_flags, T_RETR)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } else if (QUERY_FLAG(t->t_flags, T_STOR)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } else { BUG(); } } FUNC_EXIT_VOID(); } -static int -clear_bad_fd(void) -{ - struct connection *c; - struct transport *t; - - int processed = 0; - int ret; - - FUNC_ENTRY(); - - TAILQ_FOREACH(c, &conn_list, entries) { - t = c->transport; - - ret = check_socket(c->sock_fd); - if (ret == -1) { - SET_FLAG(c->c_flags, C_KILL); - processed++; - } else { - if (!QUERY_FLAG(t->t_flags, T_FREE)) { - ret = check_socket(t->socket); - if (ret == -1) { - SET_FLAG(t->t_flags, T_KILL); - processed++; - } - } - } - } - - FUNC_EXIT_INT(processed); - return processed; -} - -static inline void -download_file(struct connection *c) +int main(int argc, char **argv) { - struct transport *t; - int n; + fd_set r_fd; + fd_set w_fd; + int n_ready; - FUNC_ENTRY(); + /* srv is global */ + srv = init_sftpd(argc, argv); - t = c->transport; - n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); - if (n > 0) - goto again; + while (1) { + /* wait for any events, max is 1 min. */ + n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); - send_cmd(c->sock_fd, 226, "Transfer complete."); - destroy_transport(c); -again: - FUNC_EXIT_VOID(); -} + /* check signals */ + check_received_signals(); -static inline void -upload_file(struct connection *c) -{ - struct transport *t; - char buf[65536]; - int avail; - int size; + /* deal with exist transfers */ + process_transfers(&r_fd, &w_fd, &n_ready); - FUNC_ENTRY(); + /* process FTP's commands */ + process_commands(&r_fd, &n_ready); - t = c->transport; - ioctl(t->socket, FIONREAD, &avail); - avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; + /* + * We allow 10 minutes to users, for to do + * something, after that clients are dropped. + */ + process_timeouted_sockets(10); + process_clients_marked_as_destroy(); - size = recv_data(t->socket, buf, avail, 0); - if (size > 0) { - int n = write(t->local_fd, buf, size); - if (n == size) - goto again; - else if (n < 0) { - /* ??? */ - } + /* accept new clients, if they are */ + accept_client(srv->srv_socket, &r_fd, &n_ready); } - send_cmd(c->sock_fd, 226, "Transfer complete."); - destroy_transport(c); -again: - FUNC_EXIT_VOID(); + return 0; }
urezki/sftpd
869b869c6c8f9f8ced486985db16068d3317ce85
@MAINT: A README file is filled out.
diff --git a/README b/README index e69de29..a4ca92f 100644 --- a/README +++ b/README @@ -0,0 +1,21 @@ + ====== sftpd ====== + +This is a single thread ftp server. Actually, it's an attempt to develop new +kind of client processing mechanism just using one single thread for set of +users, we don't use any pre-forking or other kind of such stuff for connection +handle. + +How to build it: + In order to play with it, just type 'make' within tree folder, and then + run 'sftpd' binary file using root user. If you want to have an anonymous + access ftp user must be added. + +TODO list: + 1) to rewrite "LIST" cmd, because it's full of crap right now; + 2) to implement following commands: NLST, MODE, MDTM; + 3) to implement more or less logging functionality; + 4) to buckle down to test it. + +Contacts: + email: [email protected] + skype: uladzislau_rezki
urezki/sftpd
695873deb8694d617d50c78863e848a712f395a2
@MAINT added BUG macro, it generates an invalid opcode exception.
diff --git a/include/debug.h b/include/debug.h index e6c5a0f..5faa0f0 100644 --- a/include/debug.h +++ b/include/debug.h @@ -1,53 +1,56 @@ #ifndef __DEBUG_H__ #define __DEBUG_H__ +/* Raise invalid opcode exception */ +#define BUG() __asm__ __volatile__("ud2\n") + #define __DEBUG_MSG__ //#define __DEBUG_FUNC__ #ifdef __DEBUG_MSG__ /* DEBUG MSG */ #define PRINT_DEBUG(fmt,arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); } while (0) #else #define PRINT_DEBUG(fmt,arg...) \ do { } while(0) #endif /* __DEBUG_MSG__ */ #define FATAL_ERROR(fmt, arg...) do { \ fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ fflush(stdout); \ exit(-1); } while (0) #ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ #define FUNC_ENTRY() do { \ fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_VOID() do { \ fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ fflush(stdout); } while (0) #define FUNC_EXIT_INT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ __FUNCTION__, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_UINT(value) do { \ fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ __FUNCTION__, value, value); \ fflush(stdout); } while (0) #define FUNC_EXIT_PTR(ptr) do { \ fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ __FUNCTION__, ptr); \ fflush(stdout); } while (0) #else #define FUNC_ENTRY() do { } while(0) #define FUNC_EXIT_VOID() do { } while(0) #define FUNC_EXIT_INT(value) do { } while(0) #define FUNC_EXIT_UINT(value) do { } while(0) #define FUNC_EXIT_PTR(ptr) do { } while(0) #endif /* __DEBUG_FUNC__ */ #endif /* __DEBUG_H__ */ diff --git a/src/sftpd.c b/src/sftpd.c index 072c380..d8029d6 100644 --- a/src/sftpd.c +++ b/src/sftpd.c @@ -1,542 +1,542 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include <signal.h> #include <sys/sendfile.h> /* local headers */ #include <list.h> #include <sock_utils.h> #include <signal_ruling.h> #include <debug.h> #include <sftpd.h> #include <cmds.h> #include <mem.h> #define DEV_NULL "/dev/null" /* * Head of the client list */ static TAILQ_HEAD(cli_list, connection) conn_list; /* global variable */ struct ftpd *srv = NULL; static ftpd *init_sftpd(void); /* static void init_daemon(void); */ static int process_timeouted_sockets(int); static void process_commands(fd_set *, int *); static void process_transfers(fd_set *, fd_set *, int *); static int process_clients_marked_as_destroy(void); static connection *add_connection(int); static void destroy_connection(connection *); static void destroy_transport(connection *); static int clear_bad_fd(); static inline void download_file(struct connection *); static inline void upload_file(struct connection *); static void accept_client(int socket, fd_set *r_fd, int *n_ready) { struct sockaddr_in r_addr; connection *conn = NULL; socklen_t cli_len; int conn_fd; /* * We have to process situation when clients * send RST packet, but we are waiting for a connection * from other side ... */ if (FD_ISSET(socket, r_fd) && *n_ready > 0) { cli_len = sizeof(r_addr); conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); if (conn_fd != -1) { activate_nodelay(conn_fd); conn = add_connection(conn_fd); if (conn != NULL) send_cmd(conn->sock_fd, 220, "I'm ready"); } else { PRINT_DEBUG("accept() error: %s\n", strerror(errno)); } (*n_ready)--; } } static void check_received_signals(void) { if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { struct connection *c; TAILQ_FOREACH(c, &conn_list, entries) { destroy_connection(c); } close(srv->srv_socket); free(srv); exit(1); /* finish up */ } } static int wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) { struct timeval time; int n_ready; *r_fd = sftpd->read_ready; *w_fd = sftpd->write_ready; time.tv_sec = sec; time.tv_usec = 0; n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); if (n_ready < 0) { if (errno == EBADF) { PRINT_DEBUG("'select()' failed with errno %d: %s\n", errno, strerror(errno)); /* * We mark bad descriptors, and below * will clean it up. */ clear_bad_fd(); } sleep(1); } return n_ready; } int main(int argc, char **argv) { fd_set r_fd; fd_set w_fd; int n_ready; /* srv is global */ srv = init_sftpd(); while (1) { /* wait for any events, max is 1 min. */ n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); /* check signals */ check_received_signals(); /* deal with exist transfers */ process_transfers(&r_fd, &w_fd, &n_ready); /* process FTP's commands */ process_commands(&r_fd, &n_ready); /* * We allow 10 minutes to users, for to do * something, after that clients are dropped. */ process_timeouted_sockets(10); process_clients_marked_as_destroy(); /* accept new clients, if they are */ accept_client(srv->srv_socket, &r_fd, &n_ready); } return 0; } static connection * add_connection(int s) { struct connection *new_conn = NULL; struct transport *tr = NULL; FUNC_ENTRY(); if (srv->client_count < FD_SETSIZE) { /* adding new client's socket */ FD_SET(s, &(srv->read_ready)); new_conn = (connection *) calloc(1, sizeof(connection)); tr = (transport *) calloc(1, sizeof(transport)); if (new_conn == NULL || tr == NULL) FATAL_ERROR("error allocating memory\n"); new_conn->c_atime = time(NULL); new_conn->sock_fd = s; new_conn->c_flags = 0; /* reset flag */ SET_FLAG(tr->t_flags, T_FREE); new_conn->transport = tr; TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); srv->client_count++; } else { PRINT_DEBUG("There are %d connections, it's too much\n", srv->client_count); send_cmd(s, 230, "Too many connections."); close_socket(s); } FUNC_EXIT_PTR(new_conn); return new_conn; } static void destroy_connection(connection *conn) { struct connection *c; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { if (c == conn) { FD_CLR(conn->sock_fd, &(srv->read_ready)); close_socket(conn->sock_fd); srv->client_count--; TAILQ_REMOVE(&conn_list, c, entries); destroy_transport(conn); free(conn->transport); free(conn); break; /* !!! */ } } FUNC_EXIT_VOID(); } static void destroy_transport(connection *conn) { struct transport *t; FUNC_ENTRY(); t = conn->transport; if (!QUERY_FLAG(t->t_flags, T_FREE)) { close_socket(t->socket); /* * If t_flags is RETR or STOR, it means that we have already * opened local file, that is why we have to close it, * otherwise we don't have to do it. */ if (QUERY_FLAG(t->t_flags, T_RETR)) { close(t->local_fd); FD_CLR(t->socket, &srv->write_ready); } else if (QUERY_FLAG(t->t_flags, T_STOR)) { close(t->local_fd); FD_CLR(t->socket, &srv->read_ready); } /* * We have to clean transport before next using !!! */ bzero(t, sizeof(transport)); SET_FLAG(t->t_flags, T_FREE); } FUNC_EXIT_VOID(); } /* static void */ /* init_daemon(void) */ /* { */ /* int i = 0; */ /* FUNC_ENTRY(); */ /* if (fork() != 0) /\* quit first parent *\/ */ /* exit(0); */ /* if (setsid() < 0) */ /* perror("setsid"); */ /* if (fork() != 0) /\* quit second parent *\/ */ /* exit(0); */ /* chdir("/"); */ /* umask(0); */ /* for (i = 0; i < 64; i++) */ /* close(i); */ /* i = open(DEV_NULL, O_RDWR); /\* stdin *\/ */ /* dup(i); /\* stdout *\/ */ /* dup(i); /\* stderr *\/ */ /* FUNC_EXIT_VOID(); */ /* } */ static ftpd * init_sftpd(void) { ftpd *sftpd = NULL; FUNC_ENTRY(); signal_handle(SIGHUP); signal_handle(SIGTERM); signal_ignore(SIGPIPE); /* allocate memory for our new ftp server */ sftpd = (ftpd *) calloc(1, sizeof(ftpd)); if (sftpd == NULL) FATAL_ERROR("error allocating memory\n"); /* init some stuff */ sftpd->client_count = 0; sftpd->srv_socket = -1; sftpd->srv_socket = start_tcp_listen(21, 4, 30); if (sftpd->srv_socket == -1) FATAL_ERROR("error starting tcp listen\n"); FD_ZERO(&(sftpd->read_ready)); FD_ZERO(&(sftpd->write_ready)); FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); /* initialize list */ TAILQ_INIT(&conn_list); FUNC_EXIT_PTR(sftpd); return sftpd; } static int process_timeouted_sockets(int time_m) { struct connection *c; int processed = 0; int allow_time; time_t now; FUNC_ENTRY(); now = time(NULL); allow_time = time_m * 60; TAILQ_FOREACH(c, &conn_list, entries) { if (difftime(now, c->c_atime) > allow_time) { if (!QUERY_FLAG(c->c_flags, C_KILL)) { send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); SET_FLAG(c->c_flags, C_KILL); processed++; } } } FUNC_EXIT_INT(processed); return processed; } static void process_commands(fd_set *r_fd, int *n_ready) { struct connection *c; int processed = 0; int avail_b; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { /* skip sockets which are not ready */ if (!FD_ISSET(c->sock_fd, r_fd)) continue; /* * If we want to remove connection from the list * and free memory which was allocated, we must * set C_KILL flag. */ if (QUERY_FLAG(c->c_flags, C_KILL)) continue; ioctl(c->sock_fd, FIONREAD, &avail_b); if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { int read_count; read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); /* modify last access */ c->c_atime = time(NULL); parse_cmd(c); } else { /* * Here we process two sitations: when buffer is * more than RECV_BUF_SIZE bytes; and when there * is no data. */ if (avail_b > RECV_BUF_SIZE) send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); SET_FLAG(c->c_flags, C_KILL); } if (++processed == *n_ready) { (*n_ready)--; break; } } FUNC_EXIT_VOID(); } static int process_clients_marked_as_destroy(void) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); restart: TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; if (QUERY_FLAG(c->c_flags, C_KILL)) { destroy_connection(c); processed++; goto restart; } else if (QUERY_FLAG(t->t_flags, T_KILL)) { destroy_transport(c); processed++; } } FUNC_EXIT_INT(processed); return processed; } static void process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) { struct connection *c; struct transport *t; int processed = 0; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; /* skip who is FREE or KILL */ if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) continue; if (processed == *n_ready) break; /* skip transfers which are not ready */ if (!FD_ISSET(t->socket, w_fd) && !FD_ISSET(t->socket, r_fd)) continue; if (QUERY_FLAG(t->t_flags, T_RETR)) { c->c_atime = time(NULL); download_file(c); (*n_ready)--; processed++; } else if (QUERY_FLAG(t->t_flags, T_STOR)) { c->c_atime = time(NULL); upload_file(c); (*n_ready)--; } else { - /* BUG */ + BUG(); } } FUNC_EXIT_VOID(); } static int clear_bad_fd(void) { struct connection *c; struct transport *t; int processed = 0; int ret; FUNC_ENTRY(); TAILQ_FOREACH(c, &conn_list, entries) { t = c->transport; ret = check_socket(c->sock_fd); if (ret == -1) { SET_FLAG(c->c_flags, C_KILL); processed++; } else { if (!QUERY_FLAG(t->t_flags, T_FREE)) { ret = check_socket(t->socket); if (ret == -1) { SET_FLAG(t->t_flags, T_KILL); processed++; } } } } FUNC_EXIT_INT(processed); return processed; } static inline void download_file(struct connection *c) { struct transport *t; int n; FUNC_ENTRY(); t = c->transport; n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); if (n > 0) goto again; send_cmd(c->sock_fd, 226, "Transfer complete."); destroy_transport(c); again: FUNC_EXIT_VOID(); } static inline void upload_file(struct connection *c) { struct transport *t; char buf[65536]; int avail; int size; FUNC_ENTRY(); t = c->transport; ioctl(t->socket, FIONREAD, &avail); avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; size = recv_data(t->socket, buf, avail, 0); if (size > 0) { int n = write(t->local_fd, buf, size); if (n == size) goto again; else if (n < 0) { /* ??? */ } } send_cmd(c->sock_fd, 226, "Transfer complete."); destroy_transport(c); again: FUNC_EXIT_VOID(); }
urezki/sftpd
1378d02ac0fcfc812983217ac3b15b70e5b86416
added sftpd sources.
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1a8bd01 --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ +# Mafifile + +CC = gcc +CFLAGS = -g -O0 -Wall -Werror -D_GNU_SOURCE -DMEMORY_DEBUG -DUPLOAD_SUPPORT -std=c99 +INCLUDE = -I./include +LIB = -lcrypt + +BINARY = sftpd +SRC = $(wildcard src/*.c) +OBJ = $(subst .c,.o, $(SRC)) + +all: $(OBJ) + $(CC) -o $(BINARY) $(OBJ) $(LIB) + +.c.o: + $(CC) $(CFLAGS) $(INCLUDE) -o $@ -c $< + +clean: + rm -rf $(OBJ) $(BINARY) diff --git a/README b/README new file mode 100644 index 0000000..e69de29 diff --git a/include/cmds.h b/include/cmds.h new file mode 100644 index 0000000..032a159 --- /dev/null +++ b/include/cmds.h @@ -0,0 +1,6 @@ +#ifndef __CMDS_H__ +#define __CMDS_H__ + +extern int parse_cmd(connection *conn); + +#endif /* __CMDS_H__ */ diff --git a/include/debug.h b/include/debug.h new file mode 100644 index 0000000..e6c5a0f --- /dev/null +++ b/include/debug.h @@ -0,0 +1,53 @@ +#ifndef __DEBUG_H__ +#define __DEBUG_H__ + +#define __DEBUG_MSG__ +//#define __DEBUG_FUNC__ + +#ifdef __DEBUG_MSG__ /* DEBUG MSG */ +#define PRINT_DEBUG(fmt,arg...) do { \ + fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ + fflush(stdout); } while (0) +#else +#define PRINT_DEBUG(fmt,arg...) \ + do { } while(0) +#endif /* __DEBUG_MSG__ */ + +#define FATAL_ERROR(fmt, arg...) do { \ + fprintf(stdout, "%s:%d: " fmt, __FILE__, __LINE__, ##arg); \ + fflush(stdout); \ + exit(-1); } while (0) + +#ifdef __DEBUG_FUNC__ /* DEBUG FUNCTIONS */ +#define FUNC_ENTRY() do { \ + fprintf(stdout, "%s: Enter.\n", __FUNCTION__); \ + fflush(stdout); } while (0) + +#define FUNC_EXIT_VOID() do { \ + fprintf(stdout, "%s: Exit.\n", __FUNCTION__); \ + fflush(stdout); } while (0) + +#define FUNC_EXIT_INT(value) do { \ + fprintf(stdout, "%s: Exit. Return value is: %d.\n", \ + __FUNCTION__, value); \ + fflush(stdout); } while (0) + +#define FUNC_EXIT_UINT(value) do { \ + fprintf(stdout, "%s: Exit. Return value is: %u (0x%08x).\n", \ + __FUNCTION__, value, value); \ + fflush(stdout); } while (0) + +#define FUNC_EXIT_PTR(ptr) do { \ + fprintf(stdout, "%s: Exit. Returned pointer is: %p.\n", \ + __FUNCTION__, ptr); \ + fflush(stdout); } while (0) +#else + +#define FUNC_ENTRY() do { } while(0) +#define FUNC_EXIT_VOID() do { } while(0) +#define FUNC_EXIT_INT(value) do { } while(0) +#define FUNC_EXIT_UINT(value) do { } while(0) +#define FUNC_EXIT_PTR(ptr) do { } while(0) + +#endif /* __DEBUG_FUNC__ */ +#endif /* __DEBUG_H__ */ diff --git a/include/list.h b/include/list.h new file mode 100644 index 0000000..6a44470 --- /dev/null +++ b/include/list.h @@ -0,0 +1,94 @@ +#ifndef __LIST_H__ +#define __LIST_H__ + +/* + * Tail queue declarations. + */ +#define TAILQ_HEAD(name, type) \ + struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ + } + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first } + +#define TAILQ_ENTRY(type) \ + struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ + } + +/* + * Tail queue functions. + */ +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) + +#define TAILQ_FIRST(head) ((head)->tqh_first) +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = TAILQ_FIRST((head)); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_INIT(head) do { \ + TAILQ_FIRST((head)) = NULL; \ + (head)->tqh_last = &TAILQ_FIRST((head)); \ + } while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ + } while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + TAILQ_NEXT((elm), field) = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + } while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ + } while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + TAILQ_NEXT((elm), field) = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + } while (0) + +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) + +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) + +#define TAILQ_REMOVE(head, elm, field) do { \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ + } while (0) + +#endif /* __LIST_H__ */ diff --git a/include/ls.h b/include/ls.h new file mode 100644 index 0000000..77659e0 --- /dev/null +++ b/include/ls.h @@ -0,0 +1,19 @@ +// File: ls.h +// Headers file +// Created: Mon Sep 25 17:27:02 UTC 2006 + +typedef struct __str_ +{ + char *f_name; /* file name */ + unsigned int f_len; /* file len */ + + uid_t uid; + gid_t gid; + unsigned int st_nlink; + off_t st_size; + time_t time; + mode_t mode; +} __str; + +/* prototip's */ +extern int do_list(connection *conn); diff --git a/include/mem.h b/include/mem.h new file mode 100644 index 0000000..7db4ccc --- /dev/null +++ b/include/mem.h @@ -0,0 +1,20 @@ +#ifndef __MEM_H__ +#define __MEM_H__ + +#ifdef MEMORY_DEBUG + +extern void *__calloc(size_t, size_t, const char *, const char *, int); +extern void *__realloc(void *, size_t, const char *, const char *, int); +extern void *__malloc(size_t, const char *, const char *, int); +extern char *__strdup (const char *, const char *, const char *, int); +extern void __free(void *, const char *, const char *, int); +extern u_long __get_mem_status(void); + +#define malloc(A) __malloc(A, __FILE__, __FUNCTION__, __LINE__) +#define calloc(A, B) __calloc(A, B, __FILE__, __FUNCTION__, __LINE__) +#define realloc(A, B) __realloc(A, B, __FILE__, __FUNCTION__, __LINE__) +#define strdup(A) __strdup(A, __FILE__, __FUNCTION__, __LINE__) +#define free(A) __free(A, __FILE__, __FUNCTION__, __LINE__) + +#endif /* MEMORY_DEBUG */ +#endif /* __MEM_H__ */ diff --git a/include/sftpd.h b/include/sftpd.h new file mode 100644 index 0000000..808f583 --- /dev/null +++ b/include/sftpd.h @@ -0,0 +1,69 @@ +#ifndef __FTPD_H__ +#define __FTPD_H__ + +#define DATA_PORT 20 +#define RECV_BUF_SIZE 4096 + +/* connection specific flags */ +#define C_AUTH 0x00000001 +#define C_KILL 0x00000002 + +/* transport specific flags */ +#define T_FREE 0x00000001 +#define T_PORT 0x00000002 +#define T_PASV 0x00000004 +#define T_LIST 0x00000008 +#define T_RETR 0x00000010 +#define T_STOR 0x00000020 +#define T_KILL 0x00000040 + +#define SET_FLAG(X,Y) (X = (X^X) | Y) +#define QUERY_FLAG(X,Y) (X & Y) +#define CLEAR_FLAG(X,Y) (X &= ~Y) + +struct connection { + char recv_buf[RECV_BUF_SIZE]; + int recv_buf_len; + char user_name[256]; + char user_pass[256]; + char root_dir[256]; + char curr_dir[256]; + int sock_fd; + + uid_t uid; + gid_t gid; + + time_t c_atime; /* last access time*/ + int c_flags; + + struct transport *transport; + TAILQ_ENTRY(connection) entries; +}; + +struct transport { + struct sockaddr_in r_info; + struct stat st; + + int socket; + int data_port; + + int local_fd; + off_t offset; + + int t_flags; +}; + +struct ftpd { + unsigned int client_count; + fd_set write_ready; + fd_set read_ready; + int srv_socket; +}; + +typedef struct connection connection; +typedef struct transport transport; +typedef struct ftpd ftpd; + +extern struct ftpd *srv; + +#endif /* __FTPD_H__ */ diff --git a/include/signal_ruling.h b/include/signal_ruling.h new file mode 100644 index 0000000..9ef2e20 --- /dev/null +++ b/include/signal_ruling.h @@ -0,0 +1,10 @@ +#ifndef __SIGNAL_RULING_H__ +#define __SIGNAL_RULING_H__ + +extern void signal_handle(int sig); +extern void signal_unhandle(int sig); +extern int signal_is_pending(int sig); +extern void signal_clear(int sig); +extern void signal_ignore(int sig); + +#endif /* __SIGNAL_RULING_H__ */ diff --git a/include/sock_utils.h b/include/sock_utils.h new file mode 100644 index 0000000..0403922 --- /dev/null +++ b/include/sock_utils.h @@ -0,0 +1,23 @@ +#ifndef __SOCK_UTILS_H__ +#define __SOCK_UTILS_H__ + +typedef struct sockaddr SA; + +extern int send_data(int, const void *, int, int); +extern int recv_data(int, void *, int, int); +extern void send_cmd(int, const int, const char *const, ...); +extern int get_remote_info(int, struct sockaddr *); +extern int start_tcp_listen(int, int, int); +extern int connect_timeout(int, struct sockaddr *, int); +extern int accept_timeout(int, struct sockaddr *, unsigned int); +extern void activate_nonblock(int); +extern void deactivate_nonblock(int); +extern void activate_nodelay(int); +extern void activate_cork(int); +extern void activate_reuseaddr(int); +extern int get_ipv4_socket(void); +extern int get_ipv6_socket(void); +extern void close_socket(int); +extern int check_socket(int); + +#endif diff --git a/include/utils.h b/include/utils.h new file mode 100644 index 0000000..b0dad45 --- /dev/null +++ b/include/utils.h @@ -0,0 +1,10 @@ +#ifndef __UTILS_H__ +#define __UTILS_H__ + +extern void set_euid(uid_t); +extern void reset_euid(void); + +extern void set_egid(gid_t); +extern void reset_egid(void); + +#endif /* __UTILS_H__ */ diff --git a/src/cmds.c b/src/cmds.c new file mode 100644 index 0000000..99ee780 --- /dev/null +++ b/src/cmds.c @@ -0,0 +1,894 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/select.h> +#include <strings.h> +#include <string.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <errno.h> +#include <shadow.h> +#include <pwd.h> + +#include <sys/stat.h> +#include <sys/types.h> +#include <fcntl.h> +#include <time.h> +#include <sys/ioctl.h> + +/* local headers */ +#include <list.h> +#include <sock_utils.h> +#include <utils.h> +#include <debug.h> +#include <sftpd.h> +#include <cmds.h> +#include <mem.h> +#include <ls.h> + +static void cmd_user(struct connection *); +static void cmd_pass(struct connection *); +static void cmd_port(struct connection *); +static void cmd_pasv(struct connection *); +static void cmd_list(struct connection *); +static void cmd_cdup(struct connection *); +static void cmd_retr(struct connection *); +static void cmd_size(struct connection *); +static void cmd_noop(struct connection *); +static void cmd_syst(struct connection *); +static void cmd_type(struct connection *); +static void cmd_stru(struct connection *); +static void cmd_quit(struct connection *); +static void cmd_feat(struct connection *); +static void cmd_abor(struct connection *); +static void cmd_stor(struct connection *); +static void cmd_dele(struct connection *); +static void cmd_help(struct connection *); +static void cmd_allo(struct connection *); +static void cmd_pwd(struct connection *); +static void cmd_cwd(struct connection *); +static void cmd_rmd(struct connection *); +static void cmd_mkd(struct connection *); + +/* static void cmd_nlst(struct connection *); */ +/* static void cmd_mode(struct connection *); */ +/* static void cmd_mdtm(struct connection *); */ + +struct cmd_handler { + char cmd_name[10]; + char arg; + void (*cmd_handler)(struct connection *const); + char need_root; + char cmd_len; +}; + +static const struct cmd_handler cmd_table[] = +{ + { "user", 1, cmd_user, 1, 4 }, + { "pass", 1, cmd_pass, 1, 4 }, + { "port", 1, cmd_port, 1, 4 }, + { "pasv", 0, cmd_pasv, 0, 4 }, + { "list", 0, cmd_list, 1, 4 }, + { "cdup", 0, cmd_cdup, 0, 4 }, + { "retr", 1, cmd_retr, 0, 4 }, + { "size", 1, cmd_size, 0, 4 }, + { "noop", 0, cmd_noop, 0, 4 }, + { "syst", 0, cmd_syst, 0, 4 }, + { "type", 0, cmd_type, 0, 4 }, + { "abor", 0, cmd_abor, 0, 4 }, + { "stru", 0, cmd_stru, 0, 4 }, + { "quit", 0, cmd_quit, 0, 4 }, + { "feat", 0, cmd_feat, 0, 4 }, + { "help", 0, cmd_help, 0, 4 }, +// { "mdtm", 0, cmd_mdtm, 0, 4 }, /* not implemented */ +#ifdef UPLOAD_SUPPORT + { "stor", 0, cmd_stor, 0, 4 }, + { "dele", 1, cmd_dele, 0, 4 }, + { "rmd", 1, cmd_rmd, 0, 3 }, + { "mkd", 1, cmd_mkd, 0, 3 }, +#endif +// { "nlst", 0, cmd_nlst, 0, 4 }, /* not implemented */ +// { "mode", 0, cmd_mode, 0, 4 }, /* not implemented */ + { "allo", 0, cmd_allo, 0, 4 }, + { "pwd", 0, cmd_pwd, 0, 3 }, + { "cwd", 1, cmd_cwd, 0, 3 }, + { " ", 0, NULL, 0, 0 } +}; + +static void +expand_to_abs(struct connection *conn) +{ + char *abs_path; + char *tmp_path; + char *cmd_arg; + char *dot; + + abs_path = calloc(PATH_MAX, sizeof(char)); + tmp_path = calloc(PATH_MAX, sizeof(char)); + + cmd_arg = strchr(conn->recv_buf, ' '); + if (cmd_arg == NULL || cmd_arg[1] == '\0') + goto end; + + cmd_arg = cmd_arg + 1; + if (*cmd_arg == '/' || *cmd_arg == '~') + snprintf(abs_path, PATH_MAX, "%s%s", conn->root_dir, + *(cmd_arg + 1) == '/' ? cmd_arg + 2 : cmd_arg + 1); + else + snprintf(abs_path, PATH_MAX, "%s%s", conn->curr_dir, cmd_arg); + /* + * If we have such situation: /home/demon/../ftp/.. + * we should add '/' to the end of the string. + */ + if ((dot = strrchr(abs_path, '.'))) + if (*(dot - 1) == '.' && *(dot + 1) == '\0' ) + strcat(abs_path, "/"); + + while ((dot = strstr(abs_path, "/../"))) { + char *s_pp = NULL; + + if (dot == abs_path) + s_pp = dot; + else + s_pp = (dot - 1); + + while (s_pp != abs_path && *s_pp != '/') + s_pp--; + + *(s_pp + 1) = '\0'; + + snprintf(tmp_path, PATH_MAX, "%s%s", abs_path, dot + 4); + strncpy(abs_path, tmp_path, PATH_MAX); + } + + *cmd_arg = '\0'; + strcat(cmd_arg, abs_path); +end: + free(abs_path); + free(tmp_path); +} + +static int +is_path_ok(struct connection *conn) +{ + char *cmd_arg; + struct stat st; + + /* build abs path */ + expand_to_abs(conn); + + cmd_arg = strchr(conn->recv_buf, ' '); + if (cmd_arg == NULL || cmd_arg[1] == '\0') + goto fail; + + /* get pointer to the arg */ + cmd_arg = cmd_arg + 1; + + /* checking sysmlyks ... */ + if (stat(cmd_arg, &st) != -1) { + if (!S_ISLNK(st.st_mode)) { + char buf[1024] = {'\0'}; + int len; + + len = readlink(cmd_arg, buf, sizeof(buf) - 1); + if (len != -1) { + buf[len] = '\0'; + *cmd_arg = '\0'; + strcat(cmd_arg, buf); + } + } + } + + if (!strncmp(cmd_arg, conn->root_dir, strlen(conn->root_dir))) + return 1; +fail: + return 0; +} + +static void +cmd_feat(struct connection *conn) +{ + const char *const feat = + "211-Features:\r\n" + " SIZE\r\n" + "211 End\r\n"; + + FUNC_ENTRY(); + + /* sending informations about features. */ + send_data(conn->sock_fd, feat, strlen(feat), 0); + + FUNC_EXIT_VOID(); +} + +/** + * recv_buf looks like: "USER anonymous'\0'" + * recv_buf_len is 14, in this case. + */ +static void +cmd_user(struct connection *conn) +{ + char tmp_buf[120] = {'\0'}; + int rejected = 0; + + FUNC_ENTRY(); + + if (strstr(conn->recv_buf, "anonymous") || + strstr(conn->recv_buf, "ftp")) + { + (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s", "Anonymous " + "login ok, send your complete email address " + "as your password"); + (void) strncpy(conn->user_name, "ftp", sizeof(conn->user_name)); + } else { + char *user_name; + + /* skipping "USER " */ + user_name = strchr(conn->recv_buf, ' '); + if (user_name != NULL && conn->recv_buf_len > 4) { + (void) strncpy(conn->user_name, user_name + 1, + sizeof(conn->user_name)); + + (void) snprintf(tmp_buf, sizeof(tmp_buf), "%s %s", "password " + "required for", conn->user_name); + } else { + (void) snprintf(tmp_buf, sizeof(tmp_buf), "Invalid user name"); + rejected = 1; /* mark as was rejected */ + } + } + + send_cmd(conn->sock_fd, !rejected ? 331:530, "%s", tmp_buf); + FUNC_EXIT_VOID(); +} + +static void +cmd_pass(struct connection *conn) +{ + struct spwd *p_shadow; + struct passwd *p; + + FUNC_ENTRY(); + + p = getpwnam(conn->user_name); + if (p != NULL) { + char *user_pass; + + conn->uid = p->pw_uid; + conn->gid = p->pw_gid; + + (void) strncpy(conn->root_dir, p->pw_dir, sizeof(conn->root_dir)); + if (conn->root_dir[strlen(conn->root_dir) - 1] != '/') + (void) strcat(conn->root_dir, "/"); + + (void) strncpy(conn->curr_dir, p->pw_dir, sizeof(conn->curr_dir)); + if (conn->curr_dir[strlen(conn->curr_dir) - 1] != '/') + (void) strcat(conn->curr_dir, "/"); + + user_pass = strchr(conn->recv_buf, ' '); + + /* in case of anonymous access */ + if (!strncmp(conn->user_name, "ftp", 3)) { + SET_FLAG(conn->c_flags, C_AUTH); + } else if (user_pass != NULL && conn->recv_buf_len > 4) { + char *p_crypt; + + p_crypt = crypt(user_pass + 1, p->pw_passwd); + if (p_crypt != NULL) { + if (!strcmp(p_crypt, p->pw_passwd)) { + SET_FLAG(conn->c_flags, C_AUTH); + } else { + /* checking shadow pass */ + p_shadow = getspnam(conn->user_name); + if (p_shadow != NULL) + p_crypt = crypt(user_pass + 1, p_shadow->sp_pwdp); + if (p_crypt != NULL) + if (!strcmp(p_crypt, p_shadow->sp_pwdp)) + SET_FLAG(conn->c_flags, C_AUTH); + } + } + } + } + + if (QUERY_FLAG(conn->c_flags, C_AUTH)) { + send_cmd(conn->sock_fd, 230, "%s %s", conn->user_name, "logged in"); + PRINT_DEBUG("%s user logged in\n", conn->user_name); + chdir(conn->root_dir); + } else { + send_cmd(conn->sock_fd, 530, "Login incorrect"); + PRINT_DEBUG("%s Login incorrect\n", conn->user_name); + } + + FUNC_EXIT_VOID(); +} + +/** + * cmd_port - this function find out the + * port number, which should be used afterwards, + * and than connect to the client. + * + * for instance: PORT 192,168,5,12,4,1 + */ +static void +cmd_port(struct connection *conn) +{ + char *ip_address = NULL; + int data_port = 0; + transport *t; + int ret; + + FUNC_ENTRY(); + + t = conn->transport; + ip_address = strchr(conn->recv_buf, ' '); + + if (QUERY_FLAG(t->t_flags, T_FREE)) { + short int a0, a1, a2, a3, p0, p1; + + ret = sscanf(ip_address + 1, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", + &a0, &a1, &a2, &a3, &p0, &p1); + + data_port = p0 * 256 + p1; + if (data_port > 1024 && ret == 6) { + int len; + + t->socket = get_ipv4_socket(); + t->data_port = data_port; + activate_reuseaddr(t->socket); + + t->r_info.sin_port = htons(DATA_PORT); + t->r_info.sin_family = AF_INET; + + len = sizeof(t->r_info); + bind(t->socket, (SA *)&t->r_info, len); + + t->r_info.sin_family = AF_INET; + t->r_info.sin_port = htons(t->data_port); + t->r_info.sin_addr.s_addr = htonl( + ((unsigned char)(a0) << 24) + + ((unsigned char)(a1) << 16) + + ((unsigned char)(a2) << 8) + + ((unsigned char)(a3))); + + ret = connect_timeout(t->socket, (SA *)&t->r_info, 5); + if (ret == 0) { + /* we are in a port mode */ + SET_FLAG(t->t_flags, T_PORT); + activate_nonblock(t->socket); + + send_cmd(conn->sock_fd, 220, "PORT command successful"); + } else { + send_cmd(conn->sock_fd, 425, "Can't open data connection"); + PRINT_DEBUG("Can't connect to %s:%d\n", ip_address, data_port); + } + } + } else { + send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); + PRINT_DEBUG("Sorry, only one transfer at once\n"); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_pasv(struct connection *conn) +{ + struct sockaddr_in addr; + int listen_sock; + transport *trans; + socklen_t len; + + FUNC_ENTRY(); + + trans = conn->transport; + if (QUERY_FLAG(trans->t_flags, T_FREE)) { + memset(&addr, 0, sizeof(addr)); + listen_sock = get_ipv4_socket(); + activate_reuseaddr(listen_sock); + + len = sizeof(addr); + getsockname(conn->sock_fd, (struct sockaddr *)&addr, &len); + + addr.sin_port = 0; + bind(listen_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); + + len = sizeof(addr); + getsockname(listen_sock, (struct sockaddr *)&addr, &len); + listen(listen_sock, 1); + + /* send that we are ready */ + send_cmd(conn->sock_fd, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)", + (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24, + (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16, + (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8, + (htonl(addr.sin_addr.s_addr) & 0x000000ff), + (htons(addr.sin_port) & 0xff00) >> 8, + (htons(addr.sin_port) & 0x00ff)); + + /* + * listen_sock should be added to the poll, and checked by select, + * after that when socket is ready do accept. + */ + trans->socket = accept_timeout(listen_sock, (SA *)&trans->r_info, 5); + if (trans->socket != -1) { + /* we are in PASV mode */ + SET_FLAG(trans->t_flags, T_PASV); + activate_nonblock(trans->socket); + } else { + send_cmd(conn->sock_fd, 500, "Accepting error, sorry"); + PRINT_DEBUG("Accepting error. sorry\n"); + } + + /* we needn't listen further */ + close_socket(listen_sock); + } else { + send_cmd(conn->sock_fd, 503, "Sorry, only one transfer at once."); + PRINT_DEBUG("Sorry, only one transfer at once\n"); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_retr(struct connection *conn) +{ + transport *t; + char *l_file; + + FUNC_ENTRY(); + + t = conn->transport; + if (!QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); + goto leave; + } + + if (is_path_ok(conn)) { + l_file = strchr(conn->recv_buf, ' '); + t->local_fd = open(l_file + 1, O_RDONLY); + if (t->local_fd != -1) { + fstat(t->local_fd, &t->st); + + FD_SET(t->socket, &srv->write_ready); + send_cmd(conn->sock_fd, 150, "Binary mode."); + SET_FLAG(t->t_flags, T_RETR); + } else { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + } else { + errno = ENOENT; + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + + if (!QUERY_FLAG(t->t_flags, T_RETR)) + SET_FLAG(t->t_flags, T_KILL); + +leave: + FUNC_EXIT_VOID(); +} + +static void +cmd_allo(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 202, "No storage allocation necessary."); + + FUNC_EXIT_VOID(); +} + +/** + * cmd_rmd - remove directory + * + * @conn: + */ +static void +cmd_rmd(struct connection *conn) +{ + char *dir_name; + int ret; + + FUNC_ENTRY(); + + if (is_path_ok(conn)) { + dir_name = strchr(conn->recv_buf, ' ') + 1; + ret = rmdir(dir_name); + if (ret != -1) + send_cmd(conn->sock_fd, 250, "Directory deleted."); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + + FUNC_EXIT_VOID(); +} + +/** + * cmd_mkd - make directory RFC ??? + * + * @conn: data struct that describes one connection. + */ +static void +cmd_mkd(struct connection *conn) +{ + char *dir_name; + int ret; + + FUNC_ENTRY(); + + if (is_path_ok(conn)) { + dir_name = strchr(conn->recv_buf, ' '); + ret = mkdir(dir_name + 1, 0755); + if (ret != -1) + send_cmd(conn->sock_fd, 257, "%s created.", dir_name + 1); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } else { + send_cmd(conn->sock_fd, 550, "Bad path."); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_stor(struct connection *conn) +{ + transport *t; + + FUNC_ENTRY(); + + t = conn->transport; + if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + if (is_path_ok(conn)) { + char *l_file = strchr(conn->recv_buf, ' ') + 1; + + t->local_fd = open(l_file, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (t->local_fd != -1) { + FD_SET(t->socket, &srv->read_ready); + send_cmd(conn->sock_fd, 150, "Binary mode."); + SET_FLAG(t->t_flags, T_STOR); + } else { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + SET_FLAG(t->t_flags, T_KILL); + } + } + } else { + send_cmd(conn->sock_fd, 425, "You must use PASV or PORT before."); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_size(struct connection *conn) +{ + transport *tr; + char *l_file; + int ret; + + FUNC_ENTRY(); + + tr = conn->transport; + if (is_path_ok(conn)) { + l_file = strchr(conn->recv_buf, ' '); + ret = lstat(l_file + 1, &tr->st); + if (ret != -1) + send_cmd(conn->sock_fd, 213, "%u", tr->st.st_size); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } else { + errno = ENOENT; + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + + FUNC_EXIT_VOID(); +} + +/* static void */ +/* cmd_mdtm(struct connection *conn) */ +/* { */ +/* FUNC_ENTRY(); */ + + + +/* FUNC_EXIT_VOID(); */ +/* } */ + +static void +cmd_list(struct connection *conn) +{ + transport *t = conn->transport; + + FUNC_ENTRY(); + + if (QUERY_FLAG(t->t_flags, (T_PORT | T_PASV))) { + activate_nodelay(t->socket); + do_list(conn); + SET_FLAG(t->t_flags, T_KILL); + } + + FUNC_EXIT_VOID(); +} + +/* static void */ +/* cmd_nlst(struct connection *conn) */ +/* { */ +/* FUNC_ENTRY(); */ + + + +/* FUNC_EXIT_VOID(); */ +/* } */ + +static void +cmd_dele(struct connection *conn) +{ + char *l_file; + int ret; + + FUNC_ENTRY(); + + if (is_path_ok(conn)) { + l_file = strchr(conn->recv_buf, ' ') + 1; + ret = unlink(l_file); + if (ret != -1) + send_cmd(conn->sock_fd, 250, "File deleted OK."); + else + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } else { + errno = ENOENT; + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + } + + FUNC_EXIT_VOID(); +} + +static void +cmd_noop(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 200, "NOOP command successful."); + + FUNC_EXIT_VOID(); +} + +static void +cmd_syst(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 215, "UNIX Type: L8"); + + FUNC_EXIT_VOID(); +} + +static void +cmd_type(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 200, "TYPE ignored (always I)"); + + FUNC_EXIT_VOID(); +} + +static void +cmd_abor(struct connection *conn) +{ + transport *t; + + FUNC_ENTRY(); + + t = conn->transport; + if (!QUERY_FLAG(t->t_flags, T_FREE)) { + SET_FLAG(t->t_flags, T_KILL); + send_cmd(conn->sock_fd, 426, "Transport aborted."); + } + + send_cmd(conn->sock_fd, 226, "ABOR command processed OK."); + FUNC_EXIT_VOID(); +} + +/* static void */ +/* cmd_mode(struct connection *conn) */ +/* { */ +/* FUNC_ENTRY(); */ + + + +/* FUNC_EXIT_VOID(); */ +/* } */ + +static void +cmd_help(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 414, "Hi, i can't help you."); + + FUNC_EXIT_VOID(); +} + +static void +cmd_stru(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 200, "STRU ignored (always F)"); + + FUNC_EXIT_VOID(); +} + +static void +cmd_quit(struct connection *conn) +{ + FUNC_ENTRY(); + + send_cmd(conn->sock_fd, 221, "Goodbay."); + SET_FLAG(conn->c_flags, C_KILL); + + FUNC_EXIT_VOID(); +} + +/** + * cmd_pwd - returning the current working dirrectory + * of the user. + */ +static void +cmd_pwd(struct connection *conn) +{ + int root_len; + + FUNC_ENTRY(); + + root_len = strlen(conn->root_dir); + send_cmd(conn->sock_fd, 257, "Current dir is \"%s\"", + conn->curr_dir + (root_len - 1)); + + FUNC_EXIT_VOID(); +} + +static void +cmd_cdup(struct connection *conn) +{ + char path[PATH_MAX]; + int retval; + + FUNC_ENTRY(); + + retval = chdir(".."); + if (retval != -1) { + int root_len = strlen(conn->root_dir); + + /* get absolute path */ + (void) getcwd(path, sizeof(path)); + if (path[strlen(path) - 1] != '/') + strcat(path, "/"); + + if (strncmp(path, conn->root_dir, root_len)) { + /* + * if we are going to visit outside + * we don't have to change current + * directory. + */ + + /* What does RFC say in such situations ??? */ + send_cmd(conn->sock_fd, 550, "CDUP was undone."); + + /* go back home */ + chdir(conn->curr_dir); + } else { + strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); + send_cmd(conn->sock_fd, 250, "CDUP successfull."); + } + } + + FUNC_EXIT_VOID(); +} + +/** + * cmd_cwd - changing the current working dirrectory + * of the user. + */ +static void +cmd_cwd(struct connection *conn) +{ + char path[PATH_MAX]; + int root_len; + int ret; + + FUNC_ENTRY(); + + if (is_path_ok(conn)) { + ret = chdir(strchr(conn->recv_buf, ' ') + 1); + if (ret == -1) { + send_cmd(conn->sock_fd, 550, "%s", strerror(errno)); + goto exit; + } + + root_len = strlen(conn->root_dir); + + /* get absolute path */ + (void) getcwd(path, sizeof(path)); + if (path[strlen(path) - 1] != '/') + strcat(path, "/"); + /* + * We must check path, because of symlinks, + * and if everything is OK, we can change curr_dir. + */ + if (!strncmp(conn->root_dir, path, root_len)) { + strncpy(conn->curr_dir, path, sizeof(conn->curr_dir)); + send_cmd(conn->sock_fd, 250, "CWD successfull."); + goto exit; + } else { + /* go back to the current dir */ + chdir(conn->curr_dir); + } + } + + send_cmd(conn->sock_fd, 550, "No such File or Directory."); + +exit: + FUNC_EXIT_VOID(); +} + +int +parse_cmd(connection *conn) +{ + const struct cmd_handler *h; + int processed = 0; + int buf_len; + + FUNC_ENTRY(); + + /* + * remove '\r' and '\n' from the recv_buf. + */ + buf_len = strcspn(conn->recv_buf, "\r\n"); + conn->recv_buf[buf_len] = '\0'; + conn->recv_buf_len = buf_len; + + h = cmd_table; + + do { + if (!strncasecmp(conn->recv_buf, h->cmd_name, h->cmd_len)) { + if (QUERY_FLAG(conn->c_flags, C_AUTH) || + !strncasecmp(conn->recv_buf, "USER", h->cmd_len) || + !strncasecmp(conn->recv_buf, "PASS", h->cmd_len) || + !strncasecmp(conn->recv_buf, "FEAT", h->cmd_len) || + !strncasecmp(conn->recv_buf, "QUIT", h->cmd_len)) + { + /* + * At first, we must set root UID and root GUID, + * and than we will set what we really need on demand. + */ + reset_euid(); + reset_egid(); + + /* + * If a client has already logged in and root permission + * really doesn't need we must change euid and egid. + */ + if (QUERY_FLAG(conn->c_flags, C_AUTH) && !h->need_root) { + set_egid(conn->uid); + set_euid(conn->gid); + } + + h->cmd_handler(conn); + } else { + send_cmd(conn->sock_fd, 503, "You must login, at first."); + } + + processed++; + break; + } + } while ((++h)->cmd_handler != NULL); + + /* if a client sends bad cmd, we let him know. */ + if (processed == 0) { + send_cmd(conn->sock_fd, 500, "Bad cmd."); + PRINT_DEBUG("Bad command: %s\n", conn->recv_buf); + } + + FUNC_EXIT_INT(processed); + return processed; +} diff --git a/src/ls.c b/src/ls.c new file mode 100644 index 0000000..db9b563 --- /dev/null +++ b/src/ls.c @@ -0,0 +1,381 @@ +#include <sys/stat.h> +#include <string.h> +#include <stdlib.h> +#include <stdio.h> +#include <dirent.h> +#include <langinfo.h> +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> + +#include <grp.h> +#include <pwd.h> +#include <time.h> + +#include <list.h> +#include <sock_utils.h> +#include <debug.h> +#include <sftpd.h> +#include <ls.h> +#include <mem.h> + +#define MAX_UID_LEN 5 +#define MAX_GID_LEN 5 + +#define R 000000001 /* read */ +#define W 000000010 /* write */ +#define X 000000100 /* execute */ + +static char * +get_perm(mode_t st_mode, char *perm) +{ + int i; + + for (i = 0; i < 9; i++) + *(perm + i) = '-'; + + *(perm + 0) = '?'; + switch (st_mode & S_IFMT) + { + case S_IFDIR: *(perm + 0) = 'd'; + break; + case S_IFREG: *(perm + 0) = '-'; + break; + case S_IFLNK: *(perm + 0) = 'l'; + break; + case S_IFBLK: *(perm + 0) = 'b'; + break; + case S_IFCHR: *(perm + 0) = 'c'; + break; + case S_IFSOCK: *(perm + 0) = 's'; + break; + case S_IFIFO: *(perm + 0) = 'p'; + break; + } + + (st_mode & S_IRUSR) ? (*(perm + 1) = 'r'): + (*(perm + 1) = '-'); + (st_mode & S_IWUSR) ? (*(perm + 2) = 'w'): + (*(perm + 2) = '-'); + (st_mode & S_IXUSR) ? (*(perm + 3) = 'x'): + (*(perm + 3) = '-'); + (st_mode & S_IRGRP) ? (*(perm + 4) = 'r'): + (*(perm + 4) = '-'); + (st_mode & S_IWGRP) ? (*(perm + 5) = 'w'): + (*(perm + 5) = '-'); + (st_mode & S_IXGRP) ? (*(perm + 6) = 'x'): + (*(perm + 6) = '-'); + (st_mode & S_IROTH) ? (*(perm + 7) = 'r'): + (*(perm + 7) = '-'); + (st_mode & S_IWOTH) ? (*(perm + 8) = 'w'): + (*(perm + 8) = '-'); + (st_mode & S_IXOTH) ? (*(perm + 9) = 'x'): + (*(perm + 9) = '-'); + + *(perm + 10) = '\0'; + return perm; +} + +static int +get_file_attr(char *file_name, char *dir_name, struct stat *st) +{ + size_t file_len = 0; + size_t dir_len = 0; + char *file_path; + int retval = -1; + + file_len = strlen(file_name); + dir_len = strlen(dir_name); + + if (file_name > 0 && dir_name > 0) { + file_path = (char *) malloc(file_len + dir_len + 2); + if (file_path != NULL) { + snprintf(file_path, dir_len + file_len + 2, "%s/%s%c", + dir_name, file_name, '\0'); + + retval = stat(file_path, st); + if (retval < 0) + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + free(file_path); + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + } + + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + } + + return retval; +} + +static int +feel_node(__str *str_node, char *dir_name, char *f_name, + unsigned int f_len, off_t *max_size_len) +{ + struct stat st; + int retval = 0; + + /* calloc (f_len + 1) for '\0' !!! */ + str_node->f_name = calloc(f_len + 1, sizeof(char)); + if (!str_node->f_name) + FATAL_ERROR("error allocating memory\n"); + + strncpy(str_node->f_name, f_name, f_len); + str_node->f_name[f_len] = '\0'; + str_node->f_len = f_len; + + retval = get_file_attr(f_name, dir_name, &st); + if (retval != -1) { + str_node->uid = st.st_uid; + str_node->gid = st.st_gid; + str_node->st_nlink = st.st_nlink; + str_node->st_size = st.st_size; + str_node->time = st.st_mtime; + str_node->mode = st.st_mode; + if (st.st_size > *max_size_len) + *max_size_len = st.st_size; + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + free(str_node->f_name); + str_node->f_name = NULL; + } + + return retval; +} + +static struct dirent * +next_entry(DIR *dir_name) +{ + struct dirent *next_dnt; + + if (dir_name != NULL) { + next_dnt = readdir(dir_name); + if (next_dnt == NULL) + return NULL; + else if (next_dnt->d_name[0] == '.' && next_dnt->d_name[1] == '\0') + { + next_dnt = next_entry(dir_name); + } + } + + return next_dnt; +} + +static __str ** +do_readdir(char *dir_name, off_t *max_size_len, int *file_count) +{ + struct dirent *pp = NULL; + DIR *open_dir = NULL; + struct stat st; + __str **list = NULL; + + int guess_size = 0; + int retval = 0; + + *file_count = 0; + retval = stat(dir_name, &st); + open_dir = opendir(dir_name); + + if (retval < 0 || opendir == NULL || !S_ISDIR(st.st_mode)) { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + goto out; + } + + /* magic number */ + guess_size = st.st_size / 20; + if (guess_size == 0) + guess_size = 50; + + list = (__str **) calloc(guess_size, sizeof(__str *)); + if (list == NULL) { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + goto out; + } + + while (1) { + if (guess_size == *file_count) { + __str **new_pp; + + new_pp = (__str **) realloc(list, 2 * guess_size * sizeof(__str *)); + if (new_pp == NULL && !(list = NULL)) { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + goto out; + } + + list = new_pp; + guess_size *= 2; + } + + if ((pp = next_entry(open_dir)) == NULL) + break; + + list[*file_count] = (__str *) calloc(1, sizeof(__str)); + if (list[*file_count] != NULL) { + retval = feel_node(list[*file_count], dir_name, pp->d_name, + pp->d_reclen, max_size_len); + if (retval == -1) { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + free(list[*file_count]); + continue; + } + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + list = NULL; + goto out; + } + + (*file_count)++; + } /* while (1) */ + + /* last element */ + list[*file_count] = NULL; +out: + if (closedir(open_dir) < 0) + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + + return list; +} + +static size_t +calculate_of_byte(__str **str_list, int m_size) +{ + size_t count_of_byte = 0; + register int i = 0; + + if (str_list != NULL) { + /* size of build_data */ + while (*(str_list + i) != NULL) { + count_of_byte += 35 + 10 + MAX_UID_LEN + MAX_GID_LEN + m_size; + count_of_byte += str_list[i]->f_len; + i++; + } + } + + return count_of_byte; +} + +static char * +get_file_date(time_t time) +{ + static char date_buf[20] = { '\0' }; + char *date_format = "%b %d %H:%M"; + struct timeval c_time; + struct tm *tm = NULL; + + if (gettimeofday(&c_time, NULL) != -1) { + if (time > c_time.tv_sec || + (c_time.tv_sec - time) > 60*60*24*182) { + date_format = "%b %d %Y"; + } + + tm = localtime(&time); + strftime(date_buf, sizeof(date_buf) - 1, date_format, tm); + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + return NULL; + } + + return date_buf; +} + +static char * +build_data(__str **str_list, int *len, off_t *max_size_len) +{ + size_t alloc_size = 0; + char tmp[20] = { '\0' }; + char *file_list = NULL; + int m_size = 0; + + m_size = snprintf(tmp, 20, "%ld", *max_size_len); + alloc_size = calculate_of_byte(str_list, m_size); + + if (alloc_size > 0) { + file_list = (char *) calloc(alloc_size, sizeof(char)); + if (file_list != NULL) { + char tmp_buf[400] = { '\0' }; + char perm[11] = { '\0' }; + char *date = NULL; + int i = 0; + int j = 0; + + *len = 0; + while (*(str_list + i) != NULL) { + date = get_file_date(str_list[i]->time); + (void) snprintf(tmp_buf, sizeof(tmp_buf) - 1, "%s%4u %-*u %-*u %*ld %s %s\r\n", + get_perm(str_list[i]->mode, perm), (unsigned int) str_list[i]->st_nlink, + MAX_UID_LEN, str_list[i]->uid, MAX_GID_LEN, + str_list[i]->gid, m_size + 1, + str_list[i]->st_size, date, + str_list[i]->f_name ? str_list[i]->f_name:"NULL" + ); + + j = 0; + while (tmp_buf[j] != '\0') { + *(file_list + (*len)) = tmp_buf[j]; + (*len)++; + j++; + } + + i++; + } + + *(file_list + (*len)) = '\0'; + + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + } + } + + return file_list; +} + +static void +free_list(__str **list, int count_l) +{ + int i = 0; + + while (*(list + i) != NULL) { + if (list[i]->f_name) + free(list[i]->f_name); + + free(list[i]); + i++; + } + + free(list); +} + +int +do_list(struct connection *c) +{ + off_t max_size_len = 0; + __str **pp = NULL; + int file_count = 0; + + pp = do_readdir(c->curr_dir, &max_size_len, &file_count); + if (pp != NULL) { + char *file_list = NULL; + int len = 0; + + /* build tree of file's */ + file_list = build_data(pp, &len, &max_size_len); + if (file_list != NULL) { + send_cmd(c->sock_fd, 150, "ASCII MODE"); + send_data(c->transport->socket, file_list, len, 0); + send_cmd(c->sock_fd, 226, "ASCII Transfer complete"); + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + goto error; + } + + free(file_list); + free_list(pp, file_count); + } else { + PRINT_DEBUG("error: %s %d\n", __FUNCTION__, __LINE__); + goto error; + } + + return 0; +error: + return -1; +} diff --git a/src/mem.c b/src/mem.c new file mode 100644 index 0000000..035c434 --- /dev/null +++ b/src/mem.c @@ -0,0 +1,179 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <syslog.h> + +/* local headers */ +#include <debug.h> +#include <list.h> + +/* + * Head of the memory list, uses for memory debugging. + */ +static TAILQ_HEAD(mem_list, __mnode) mem_head = TAILQ_HEAD_INITIALIZER(mem_head); + +static u_long bytes_allocated; +static u_long bytes_freed; + +struct __mnode { + void *addr; + size_t size; + const char *file; + const char *func; + int line; + + /* + * This holds the pointers to the next and + * previous entries in the tail queue. + */ + TAILQ_ENTRY(__mnode) entries; +}; + +/** + * __calloc - allocates memory for an array of + * nmemb elements of size bytes each and returns + * a pointer to the allocated memory. + * + * @nmemb: number of elements; + * @size: size of each element; + * @file: name of the file where __calloc is called; + * @func: name of the function where __calloc is called; + * @line: the line number where __calloc is called. + */ +void * +__calloc(size_t nmemb, size_t size, const char *file, const char *func, int line) +{ + struct __mnode *m = calloc(1, sizeof(*m)); + void *ptr = calloc(nmemb, size); + + m->size = size * nmemb; + m->addr = ptr; + m->file = file; + m->func = func; + m->line = line; + + bytes_allocated += m->size; + TAILQ_INSERT_TAIL(&mem_head, m, entries); + + return ptr; +} + +/** + * __malloc - allocates size bytes and returns a + * pointer to the allocated memory, and adds __mnode + * to the memory list. + * + * @size: size of memory; + * @file: name of the file where __malloc is called; + * @func: name of the function where __malloc is called; + * @line: the line number where __malloc is called. + */ +void * +__malloc(size_t size, const char *file, const char *func, int line) +{ + struct __mnode *m = calloc(1, sizeof(*m)); + void *ptr = malloc(size); + + m->size = size; + m->addr = ptr; + m->file = file; + m->func = func; + m->line = line; + + bytes_allocated += size; + TAILQ_INSERT_TAIL(&mem_head, m, entries); + + return ptr; +} + +/** + * __free - frees the memory space pointed to by ptr, + * and removes __mndoe from the mem list, if ptr is NULL, + * no operation is performed. + * + * @ptr: pointer to the allocated memory; + * @file: name of the file where __free is called; + * @func: name of the function where __free is called; + * @line: the line number where __free is called. + */ +void +__free(void *ptr, const char *file, const char *func, int line) +{ + struct __mnode *item; + int found = 0; + + TAILQ_FOREACH(item, &mem_head, entries) { + if (item->addr == ptr) { + bytes_allocated -= item->size; + bytes_freed += item->size; + + TAILQ_REMOVE(&mem_head, item, entries); + + free(item->addr); + free(item); + found++; + break; + } + } + + if (!found) + syslog(LOG_ERR, "unallocated free of %p by %s in %s at line %d\n", + ptr, func, file, line); +} + +/** + * __realloc - changes the size of the memory + * block pointed to by ptr to size bytes. + * + * @old_addr: block of memory pointed to by old_addr; + * @size: size of memory; + * @file: name of the file where __realloc is called; + * @func: name of the function where __realloc is called; + * @line: the line number where __realloc is called. + */ +void * +__realloc(void *old_addr, size_t size, const char *file, const char *func, int line) +{ + void *new_addr = __malloc(size, file, func, line); + + if (new_addr && old_addr) { + memcpy(new_addr, old_addr, size); + __free(old_addr, file, func, line); + } + + return new_addr; +} + +/** + * __strdup - returns a pointer to a new string which + * is a duplicate of the string s. + * + * @str: string that will duplicate; + * @file: name of the file where __strdup is called; + * @func: name of the function where __strdup is called; + * @line: the line number where __strdup is called. + */ +char * +__strdup(const char *str, const char *file, const char *func, int line) +{ + size_t len; + char *new_str; + + len = strlen(str) + 1; /* +1 for '\0' */ + new_str = __malloc(len, file, func, line); + + if (str && new_str) + strncpy(new_str, str, len); + + return new_str; +} + +/** + * Returns information about how much + * memory we are using at present. + */ +u_long +__get_mem_status(void) +{ + return bytes_allocated; +} diff --git a/src/sftpd.c b/src/sftpd.c new file mode 100644 index 0000000..072c380 --- /dev/null +++ b/src/sftpd.c @@ -0,0 +1,542 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <sys/select.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <sys/ioctl.h> +#include <time.h> +#include <errno.h> +#include <signal.h> +#include <sys/sendfile.h> + +/* local headers */ +#include <list.h> +#include <sock_utils.h> +#include <signal_ruling.h> +#include <debug.h> +#include <sftpd.h> +#include <cmds.h> +#include <mem.h> + +#define DEV_NULL "/dev/null" + +/* + * Head of the client list + */ +static TAILQ_HEAD(cli_list, connection) conn_list; + +/* global variable */ +struct ftpd *srv = NULL; + +static ftpd *init_sftpd(void); +/* static void init_daemon(void); */ +static int process_timeouted_sockets(int); +static void process_commands(fd_set *, int *); +static void process_transfers(fd_set *, fd_set *, int *); +static int process_clients_marked_as_destroy(void); + +static connection *add_connection(int); +static void destroy_connection(connection *); +static void destroy_transport(connection *); +static int clear_bad_fd(); + +static inline void download_file(struct connection *); +static inline void upload_file(struct connection *); + +static void +accept_client(int socket, fd_set *r_fd, int *n_ready) +{ + struct sockaddr_in r_addr; + connection *conn = NULL; + socklen_t cli_len; + int conn_fd; + + /* + * We have to process situation when clients + * send RST packet, but we are waiting for a connection + * from other side ... + */ + if (FD_ISSET(socket, r_fd) && *n_ready > 0) { + cli_len = sizeof(r_addr); + conn_fd = accept(socket, (struct sockaddr *)&r_addr, &cli_len); + if (conn_fd != -1) { + activate_nodelay(conn_fd); + conn = add_connection(conn_fd); + if (conn != NULL) + send_cmd(conn->sock_fd, 220, "I'm ready"); + } else { + PRINT_DEBUG("accept() error: %s\n", strerror(errno)); + } + + (*n_ready)--; + } +} + +static void +check_received_signals(void) +{ + if (signal_is_pending(SIGTERM) || signal_is_pending(SIGHUP)) { + struct connection *c; + + TAILQ_FOREACH(c, &conn_list, entries) { + destroy_connection(c); + } + + close(srv->srv_socket); + free(srv); + exit(1); /* finish up */ + } +} + +static int +wait_for_events(ftpd *sftpd, fd_set *r_fd, fd_set *w_fd, int sec) +{ + struct timeval time; + int n_ready; + + *r_fd = sftpd->read_ready; + *w_fd = sftpd->write_ready; + + time.tv_sec = sec; + time.tv_usec = 0; + + n_ready = select(FD_SETSIZE, r_fd, w_fd, NULL, &time); + if (n_ready < 0) { + if (errno == EBADF) { + PRINT_DEBUG("'select()' failed with errno %d: %s\n", + errno, strerror(errno)); + /* + * We mark bad descriptors, and below + * will clean it up. + */ + clear_bad_fd(); + } + + sleep(1); + } + + return n_ready; +} + +int main(int argc, char **argv) +{ + fd_set r_fd; + fd_set w_fd; + int n_ready; + + /* srv is global */ + srv = init_sftpd(); + + while (1) { + /* wait for any events, max is 1 min. */ + n_ready = wait_for_events(srv, &r_fd, &w_fd, 60); + + /* check signals */ + check_received_signals(); + + /* deal with exist transfers */ + process_transfers(&r_fd, &w_fd, &n_ready); + + /* process FTP's commands */ + process_commands(&r_fd, &n_ready); + + /* + * We allow 10 minutes to users, for to do + * something, after that clients are dropped. + */ + process_timeouted_sockets(10); + process_clients_marked_as_destroy(); + + /* accept new clients, if they are */ + accept_client(srv->srv_socket, &r_fd, &n_ready); + } + + return 0; +} + +static connection * +add_connection(int s) +{ + struct connection *new_conn = NULL; + struct transport *tr = NULL; + + FUNC_ENTRY(); + + if (srv->client_count < FD_SETSIZE) { + /* adding new client's socket */ + FD_SET(s, &(srv->read_ready)); + + new_conn = (connection *) calloc(1, sizeof(connection)); + tr = (transport *) calloc(1, sizeof(transport)); + if (new_conn == NULL || tr == NULL) + FATAL_ERROR("error allocating memory\n"); + + new_conn->c_atime = time(NULL); + new_conn->sock_fd = s; + new_conn->c_flags = 0; /* reset flag */ + + SET_FLAG(tr->t_flags, T_FREE); + new_conn->transport = tr; + + TAILQ_INSERT_TAIL(&conn_list, new_conn, entries); + srv->client_count++; + } else { + PRINT_DEBUG("There are %d connections, it's too much\n", + srv->client_count); + send_cmd(s, 230, "Too many connections."); + close_socket(s); + } + + FUNC_EXIT_PTR(new_conn); + return new_conn; +} + +static void +destroy_connection(connection *conn) +{ + struct connection *c; + + FUNC_ENTRY(); + + TAILQ_FOREACH(c, &conn_list, entries) { + if (c == conn) { + FD_CLR(conn->sock_fd, &(srv->read_ready)); + close_socket(conn->sock_fd); + srv->client_count--; + TAILQ_REMOVE(&conn_list, c, entries); + destroy_transport(conn); + free(conn->transport); + free(conn); + break; /* !!! */ + } + } + + FUNC_EXIT_VOID(); +} + +static void +destroy_transport(connection *conn) +{ + struct transport *t; + + FUNC_ENTRY(); + + t = conn->transport; + if (!QUERY_FLAG(t->t_flags, T_FREE)) { + close_socket(t->socket); + /* + * If t_flags is RETR or STOR, it means that we have already + * opened local file, that is why we have to close it, + * otherwise we don't have to do it. + */ + if (QUERY_FLAG(t->t_flags, T_RETR)) { + close(t->local_fd); + FD_CLR(t->socket, &srv->write_ready); + } else if (QUERY_FLAG(t->t_flags, T_STOR)) { + close(t->local_fd); + FD_CLR(t->socket, &srv->read_ready); + } + + /* + * We have to clean transport before next using !!! + */ + bzero(t, sizeof(transport)); + SET_FLAG(t->t_flags, T_FREE); + } + + FUNC_EXIT_VOID(); +} + +/* static void */ +/* init_daemon(void) */ +/* { */ +/* int i = 0; */ + +/* FUNC_ENTRY(); */ + +/* if (fork() != 0) /\* quit first parent *\/ */ +/* exit(0); */ +/* if (setsid() < 0) */ +/* perror("setsid"); */ + +/* if (fork() != 0) /\* quit second parent *\/ */ +/* exit(0); */ + +/* chdir("/"); */ +/* umask(0); */ + +/* for (i = 0; i < 64; i++) */ +/* close(i); */ + +/* i = open(DEV_NULL, O_RDWR); /\* stdin *\/ */ +/* dup(i); /\* stdout *\/ */ +/* dup(i); /\* stderr *\/ */ + +/* FUNC_EXIT_VOID(); */ +/* } */ + +static ftpd * +init_sftpd(void) +{ + ftpd *sftpd = NULL; + + FUNC_ENTRY(); + + signal_handle(SIGHUP); + signal_handle(SIGTERM); + signal_ignore(SIGPIPE); + + /* allocate memory for our new ftp server */ + sftpd = (ftpd *) calloc(1, sizeof(ftpd)); + if (sftpd == NULL) + FATAL_ERROR("error allocating memory\n"); + + /* init some stuff */ + sftpd->client_count = 0; + sftpd->srv_socket = -1; + + sftpd->srv_socket = start_tcp_listen(21, 4, 30); + if (sftpd->srv_socket == -1) + FATAL_ERROR("error starting tcp listen\n"); + + FD_ZERO(&(sftpd->read_ready)); + FD_ZERO(&(sftpd->write_ready)); + FD_SET(sftpd->srv_socket, &(sftpd->read_ready)); + + /* initialize list */ + TAILQ_INIT(&conn_list); + + FUNC_EXIT_PTR(sftpd); + return sftpd; +} + +static int +process_timeouted_sockets(int time_m) +{ + struct connection *c; + int processed = 0; + int allow_time; + time_t now; + + FUNC_ENTRY(); + + now = time(NULL); + allow_time = time_m * 60; + + TAILQ_FOREACH(c, &conn_list, entries) { + if (difftime(now, c->c_atime) > allow_time) { + if (!QUERY_FLAG(c->c_flags, C_KILL)) { + send_cmd(c->sock_fd, 421, "Timeout! Closing connection."); + SET_FLAG(c->c_flags, C_KILL); + processed++; + } + } + } + + FUNC_EXIT_INT(processed); + return processed; +} + +static void +process_commands(fd_set *r_fd, int *n_ready) +{ + struct connection *c; + int processed = 0; + int avail_b; + + FUNC_ENTRY(); + + TAILQ_FOREACH(c, &conn_list, entries) { + /* skip sockets which are not ready */ + if (!FD_ISSET(c->sock_fd, r_fd)) + continue; + /* + * If we want to remove connection from the list + * and free memory which was allocated, we must + * set C_KILL flag. + */ + if (QUERY_FLAG(c->c_flags, C_KILL)) + continue; + + ioctl(c->sock_fd, FIONREAD, &avail_b); + if (avail_b > 0 && avail_b < RECV_BUF_SIZE) { + int read_count; + + read_count = recv_data(c->sock_fd, c->recv_buf, avail_b, 0); + /* modify last access */ + c->c_atime = time(NULL); + parse_cmd(c); + } else { + /* + * Here we process two sitations: when buffer is + * more than RECV_BUF_SIZE bytes; and when there + * is no data. + */ + if (avail_b > RECV_BUF_SIZE) + send_cmd(c->sock_fd, 503, "Buffer is overflowed, sorry."); + + SET_FLAG(c->c_flags, C_KILL); + } + + if (++processed == *n_ready) { + (*n_ready)--; + break; + } + } + + FUNC_EXIT_VOID(); +} + +static int +process_clients_marked_as_destroy(void) +{ + struct connection *c; + struct transport *t; + int processed = 0; + + FUNC_ENTRY(); + +restart: + TAILQ_FOREACH(c, &conn_list, entries) { + t = c->transport; + + if (QUERY_FLAG(c->c_flags, C_KILL)) { + destroy_connection(c); + processed++; + goto restart; + } else if (QUERY_FLAG(t->t_flags, T_KILL)) { + destroy_transport(c); + processed++; + } + } + + FUNC_EXIT_INT(processed); + return processed; +} + +static void +process_transfers(fd_set *r_fd, fd_set *w_fd, int *n_ready) +{ + struct connection *c; + struct transport *t; + int processed = 0; + + FUNC_ENTRY(); + + TAILQ_FOREACH(c, &conn_list, entries) { + t = c->transport; + + /* skip who is FREE or KILL */ + if (QUERY_FLAG(t->t_flags, (T_FREE | T_KILL))) + continue; + + if (processed == *n_ready) + break; + + /* skip transfers which are not ready */ + if (!FD_ISSET(t->socket, w_fd) && + !FD_ISSET(t->socket, r_fd)) + continue; + + if (QUERY_FLAG(t->t_flags, T_RETR)) { + c->c_atime = time(NULL); + download_file(c); + (*n_ready)--; + processed++; + } else if (QUERY_FLAG(t->t_flags, T_STOR)) { + c->c_atime = time(NULL); + upload_file(c); + (*n_ready)--; + } else { + /* BUG */ + } + } + + FUNC_EXIT_VOID(); +} + +static int +clear_bad_fd(void) +{ + struct connection *c; + struct transport *t; + + int processed = 0; + int ret; + + FUNC_ENTRY(); + + TAILQ_FOREACH(c, &conn_list, entries) { + t = c->transport; + + ret = check_socket(c->sock_fd); + if (ret == -1) { + SET_FLAG(c->c_flags, C_KILL); + processed++; + } else { + if (!QUERY_FLAG(t->t_flags, T_FREE)) { + ret = check_socket(t->socket); + if (ret == -1) { + SET_FLAG(t->t_flags, T_KILL); + processed++; + } + } + } + } + + FUNC_EXIT_INT(processed); + return processed; +} + +static inline void +download_file(struct connection *c) +{ + struct transport *t; + int n; + + FUNC_ENTRY(); + + t = c->transport; + n = sendfile(t->socket, t->local_fd, &t->offset, t->st.st_blksize); + if (n > 0) + goto again; + + send_cmd(c->sock_fd, 226, "Transfer complete."); + destroy_transport(c); +again: + FUNC_EXIT_VOID(); +} + +static inline void +upload_file(struct connection *c) +{ + struct transport *t; + char buf[65536]; + int avail; + int size; + + FUNC_ENTRY(); + + t = c->transport; + ioctl(t->socket, FIONREAD, &avail); + avail = avail > 65536 ? 65536:avail < 0 ? 0:avail; + + size = recv_data(t->socket, buf, avail, 0); + if (size > 0) { + int n = write(t->local_fd, buf, size); + if (n == size) + goto again; + else if (n < 0) { + /* ??? */ + } + } + + send_cmd(c->sock_fd, 226, "Transfer complete."); + destroy_transport(c); +again: + FUNC_EXIT_VOID(); +} diff --git a/src/signal_ruling.c b/src/signal_ruling.c new file mode 100644 index 0000000..845aca0 --- /dev/null +++ b/src/signal_ruling.c @@ -0,0 +1,57 @@ +#include <stdio.h> +#include <signal.h> +#include <errno.h> +#include <stddef.h> + +static volatile sig_atomic_t __caught_signals[NSIG]; + +static void +__signal_handler(int sig) +{ + __caught_signals[sig] = 1; +} + +static void +__set_signal_handler(int sig, void (*handler)(int)) +{ + struct sigaction act; + + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + act.sa_handler = handler; + + while (sigaction(sig, &act, NULL) && errno == EINTR) ; +} + +void +signal_handle(int sig) +{ + __set_signal_handler(sig, __signal_handler); +} + +void +signal_clear(int sig) +{ + __caught_signals[sig] = 0; +} + +void +signal_unhandle(int sig) +{ + signal_clear(sig); + __set_signal_handler(sig, SIG_DFL); +} + +void +signal_ignore(int sig) +{ + signal_clear(sig); + __set_signal_handler(sig, SIG_IGN); +} + +int +signal_is_pending(int sig) +{ + return __caught_signals[sig]; +} + diff --git a/src/sock_utils.c b/src/sock_utils.c new file mode 100644 index 0000000..2dc26a6 --- /dev/null +++ b/src/sock_utils.c @@ -0,0 +1,478 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <fcntl.h> +#include <stdarg.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <errno.h> + +/* local headers */ +#include <debug.h> +#include <sock_utils.h> +#include <list.h> +#include <mem.h> + +/** + * send_data - sending a message to a socket, + * return the number of characters sent, otherwise -1. + * + * @s: socket; + * @buf: buffer where the message should be stored; + * @len: length of the message; + * @flags: flags which we passing to send. + */ +int +send_data(int s, const void *buf, int len, int flags) +{ + int total = 0; + int ret = 0; + int n = 0; + + FUNC_ENTRY(); + + for (total = 0; total < len; total += n) { + n = send(s, buf + total, len - total, flags); + if (n < 0) { + PRINT_DEBUG("Write to socket failed with errno %d: %s\n", + errno, strerror(errno)); + break; + } + } + + ret = ((n < 0) ? -1 : total); + + FUNC_EXIT_INT(ret); + return ret; +} + +/** + * recv_data - receive a message from a socket, + * return the number of bytes received, or -1 + * if an error obtained, also 0 will be recived + * when the peer has performed an orderly shutdown. + * + * @s: socket; + * @buf: buffer where the message will be stored; + * @len: length of the message; + * @flags: flags which we passing to recv. + */ +int +recv_data(int s, void *buf, int len, int flags) +{ + int total = 0; + int ret = 0; + int n = 0; + + FUNC_ENTRY(); + + for (total = 0; total < len; total += n) { + n = recv(s, buf + total, len - total, flags); + if (n <= 0) { + PRINT_DEBUG("Read from socket failed with errno %d: %s\n", + errno, strerror(errno)); + break; + } + } + + ret = ((n == 0) ? 0 : (n < 0) ? -1 : total); + + FUNC_EXIT_INT(ret); + return ret; +} + +/** + * send_cmd - send a message to socket, but + * also it is able to build format string + * like printf. + * + * @s: socket; + * @cmd: codes which ftp protocol uses; + * @format: string that specifies how subsequent arguments are converted. + */ +void +send_cmd(int s, const int cmd, const char *const format, ...) +{ + char buf[256] = {'\0'}; + char fmt[256] = {'\0'}; + va_list args; + int err; + int i; + + FUNC_ENTRY(); + + snprintf(fmt, sizeof(fmt), "%03u %s\r\n", + cmd, format); + + va_start(args, format); + i = vsnprintf(buf, sizeof(buf), fmt, args); + va_end(args); + + err = send_data(s, buf, i, 0); + + FUNC_EXIT_VOID(); +} + +/** + * get_remote_info - get name of connected peer socket. + * On success, zero is returned, otherwise -1. + * + * @s: socket; + * @name: pointer which will contain some information. + */ +int +get_remote_info(int s, struct sockaddr *name) +{ + unsigned int sock_len = 0; + int ret = 0; + + FUNC_ENTRY(); + + sock_len = sizeof(struct sockaddr); + ret = getpeername(s, name, &sock_len); + + if (ret == -1) + PRINT_DEBUG("getpeername failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_INT(ret); + return ret; +} + +/** + * start_tcp_listen - starts listen a port number. + * On success, listen socket is returned, otherwise -1. + * + * @port_number: port number which be listened; + * @ip_ver: IPv4 or IPv6; + * @backlog: maximum length the queue of pending, + * connections may grow to. + */ +int +start_tcp_listen(int port_number, int ip_ver, int backlog) +{ + struct sockaddr_in serv_addr; + int listenfd = 0; + int retval = 0; + int len = 0; + + FUNC_ENTRY(); + + if (ip_ver == 4) + listenfd = get_ipv4_socket(); + else if (ip_ver == 6) + listenfd = get_ipv6_socket(); + + bzero(&serv_addr, sizeof(serv_addr)); + + if (listenfd != -1) { + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); + serv_addr.sin_port = (backlog) ? htons(port_number):0; + + if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET) + len = sizeof(struct sockaddr_in); + else if (((struct sockaddr *)&serv_addr)->sa_family == PF_INET6) + len = sizeof(struct sockaddr_in6); + + activate_reuseaddr(listenfd); + + retval = bind(listenfd, (struct sockaddr *)&serv_addr, len); + if (retval != -1) { + retval = listen(listenfd, backlog); + if (retval < 0) { + PRINT_DEBUG("listen failed with errno %d: %s\n", + errno, strerror(errno)); + listenfd = -1; + } + } else { + PRINT_DEBUG("bind failed with errno %d: %s\n", + errno, strerror(errno)); + listenfd = -1; + } + } + + FUNC_EXIT_INT(listenfd); + return listenfd; +} + +/** + * accept_timeout - accepting connection from the client. + * On successful connected socked is returned, otherwise -1. + * + * @s: socket; + * @r_addr: will contain info about remote host; + * @sec: wait time. + */ +int +accept_timeout(int s, struct sockaddr *r_addr, unsigned int sec) +{ + int connect_fd = 0; + int retval = 0; + fd_set r_fd; + fd_set w_fd; + + FUNC_ENTRY(); + + do { + FD_ZERO(&r_fd); + FD_SET(s, &r_fd); + + w_fd = r_fd; + + if (sec > 0) { + struct timeval time; + + time.tv_sec = sec; + time.tv_usec = 0; + + retval = select(s + 1, &r_fd, &w_fd, NULL, &time); + } else { + retval = select(s + 1, &r_fd, &w_fd, NULL, NULL); + } + + } while (retval < 0 && errno == EINTR); + + if (retval > 0) { + socklen_t len = sizeof(*r_addr); + + connect_fd = accept(s, r_addr, &len); + retval = (connect_fd > 0) ? connect_fd : -1; + } else if (retval == 0) { + PRINT_DEBUG("warning: accept timeout!\n"); + retval = -1; + } else { + PRINT_DEBUG("select failed with errno %d: %s\n", + errno, strerror(errno)); + } + + FUNC_EXIT_INT(retval); + return retval; +} + +/** + * connect_timeout - connect to the client. + * On success 0 is returned, otherwise -1. + * + * @s: socket; + * @r_addr: information about remote client; + * @sec: how much time we should wait. + */ +int +connect_timeout(int s, struct sockaddr *r_addr, int sec) +{ + struct sockaddr remote_addr; + socklen_t sock_len = 0; + int retval; + + FUNC_ENTRY(); + + if (sec > 0) + activate_nonblock(s); + + sock_len = sizeof(remote_addr); + retval = connect(s, r_addr, sock_len); + + if (retval < 0 && errno == EINPROGRESS) { + struct timeval timeout; + fd_set r_fd; + fd_set w_fd; + int n; + + do { + FD_ZERO(&r_fd); + FD_SET(s, &r_fd); + w_fd = r_fd; + + timeout.tv_sec = sec; + timeout.tv_usec = 0; + + n = select(s + 1, &r_fd, &w_fd, NULL, &timeout); + } while (n < 0 && errno == EINTR); + + if (n > 0) { + /* We have to check the socket for error */ + if (FD_ISSET(s, &r_fd) || (FD_ISSET(s, &w_fd))) + retval = check_socket(s); + } else if (n == 0) { + PRINT_DEBUG("No data within %d seconds\n", sec); + } else { + PRINT_DEBUG("select failed with errno %d: %s\n", + errno, strerror(errno)); + } + } + + if (sec > 0) + deactivate_nonblock(s); + + FUNC_EXIT_INT(retval); + return retval; +} + + +/** + * check_socket - checking a socket on error. + * + * @s: socket; + */ +int +check_socket(int s) +{ + socklen_t err_len = 0; + int retval = 0; + int error = 0; + + FUNC_ENTRY(); + + err_len = sizeof(error); + retval = getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &err_len); + if (retval < 0 || error != 0) + PRINT_DEBUG("getsockopt failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_INT(retval); + return retval; +} + +void +close_socket(int s) +{ + int ret; + + FUNC_ENTRY(); + + ret = shutdown(s, SHUT_RDWR); + if (ret) + PRINT_DEBUG("shutdown failed with errno %d: %s\n", + errno, strerror(errno)); + close(s); + + FUNC_EXIT_VOID(); +} + +void +activate_nodelay(int s) +{ + int ret = 0; + int nodelay = 1; + + FUNC_ENTRY(); + + ret = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &nodelay, + sizeof(nodelay)); + if (ret != 0) + PRINT_DEBUG("setsockopt failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +activate_cork(int s) +{ + int ret = 0; + int on = 1; + + FUNC_ENTRY(); + + ret = setsockopt(s, IPPROTO_TCP, TCP_CORK, &on, sizeof(on)); + if (ret != 0) + PRINT_DEBUG("setsockopt failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +activate_reuseaddr(int s) +{ + int ret = 0; + int on = 1; + + FUNC_ENTRY(); + + ret = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, + sizeof(on)); + if (ret != 0) + PRINT_DEBUG("setsockopt failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +int +get_ipv4_socket(void) +{ + int ipv4_sock; + + FUNC_ENTRY(); + + ipv4_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); + if (ipv4_sock < 0) + PRINT_DEBUG("socket failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_INT(ipv4_sock); + return ipv4_sock; +} + +int +get_ipv6_socket(void) +{ + int ipv6_sock; + + FUNC_ENTRY(); + + ipv6_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); + if (ipv6_sock < 0) + PRINT_DEBUG("socket failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_INT(ipv6_sock); + return ipv6_sock; +} + + +void +activate_nonblock(int s) +{ + int retval = -1; + int flags = 0; + + FUNC_ENTRY(); + + flags = fcntl(s, F_GETFL); + if (flags > 0) { + flags |= O_NONBLOCK; + retval = fcntl(s, F_SETFL, flags); + } + + if (retval < 0) + PRINT_DEBUG("fcntl failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +deactivate_nonblock(int s) +{ + int retval = -1; + int flags = 0; + + FUNC_ENTRY(); + + flags = fcntl(s, F_GETFL); + if (flags > 0) { + flags &= ~O_NONBLOCK; + retval = fcntl(s, F_SETFL, flags); + } + + if (retval < 0) + PRINT_DEBUG("fcntl failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..453bf95 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,58 @@ +#include <stdio.h> +#include <sys/types.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> +#include <debug.h> + +/* local headers */ +#include <list.h> +#include <mem.h> + +void +set_euid(uid_t euid) +{ + FUNC_ENTRY(); + + if (seteuid(euid) < 0) + PRINT_DEBUG("seteuid [%d] failed with errno %u: %s\n", + euid, errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +reset_euid(void) +{ + FUNC_ENTRY(); + + if (seteuid(0) < 0) + PRINT_DEBUG("seteuid failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +set_egid(gid_t egid) +{ + FUNC_ENTRY(); + + if (setegid(egid) < 0) + PRINT_DEBUG("setegid [%d] failed with errno %u: %s\n", + egid, errno, strerror(errno)); + + FUNC_EXIT_VOID(); +} + +void +reset_egid(void) +{ + FUNC_ENTRY(); + + if (setegid(0) < 0) + PRINT_DEBUG("setegid failed with errno %d: %s\n", + errno, strerror(errno)); + + FUNC_EXIT_VOID(); +}
jesseadams/cenarius
bb77390ede3e233a3d8b04f3b98261f57888ce0c
Dynamically determine path
diff --git a/cenarius b/cenarius index e012feb..7f96c85 100755 --- a/cenarius +++ b/cenarius @@ -1,56 +1,58 @@ #!/usr/bin/ruby +BASE_DIR = File.expand_path(File.dirname(__FILE__)) + require 'rubygems' require 'yaml' require 'ostruct' require 'cloudfiles' require 'duration' -require 'lib/float' +require BASE_DIR + '/lib/float' require 'date' -config = OpenStruct.new(YAML::load_file('config.yml')) +config = OpenStruct.new(YAML::load_file(BASE_DIR + '/config.yml')) print "Connecting to RackSpace CloudFiles... " cf = CloudFiles::Connection.new(config.username, config.api_key) print "OK!\n" Dir.chdir "/tmp" date = Date.today suffix = date.strftime "%Y%m%d" config.backups.each do |cont, base_dirs| puts ">> Processing #{cont}..." unless cf.container_exists? cont puts " ### Container did not exist and was created ###" cf.create_container cont end container = cf.container(cont) base_dirs.each do |base_dir, folders| folders.each do |folder| filename = "#{folder}_#{suffix}.tar" time = Time.now print " > Processing #{base_dir}/#{folder}... " system("tar -cf #{filename} #{base_dir}/#{folder} 2> /dev/null") system("gzip #{filename}") filename = filename + '.gz' print "uploading #{File.size(filename).to_f.humanize}... " file = container.create_object(filename, true) file.load_from_filename(filename) elapsed = Time.now - time if elapsed < 1 print "less than a second.\n" else print Duration.new(elapsed).to_s + ".\n" end end end end puts "Cleaning up..." system("rm -f /tmp/*.tar.gz")
meh/lulzjs-ncurses
c10ff7ec0c99d4708cabe4333e9a17d7c631a9a5
Mac OS compatible.
diff --git a/Makefile b/Makefile index 75810aa..69928d5 100644 --- a/Makefile +++ b/Makefile @@ -1,54 +1,54 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" $(shell js-config --cflags) -I./src -LDFLAGS = $(shell js-config --libs) -llulzjs +LDFLAGS = $(shell js-config --libs | sed 's/-dynamic.*/-lm/') -llulzjs ifdef DEBUG CFLAGS += -g -Wall endif ifdef DDEBUG CFLAGS += -DDEBUG -g -Wall endif LIB_DIR = src LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o ${LIB_DIR}/Panel.o LIB_CFLAGS = ${CFLAGS} LIB_LDFLAGS = ${LDFLAGS} -lpanel -lform -lmenu -lncurses all: lib lib: $(LIB) $(LIB) : $(LIB:.o=.cpp) ${CXX} ${LIB_CFLAGS} -fPIC -c $*.cpp -o $*.lo - ${CXX} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc + ${CXX} ${LIB_LDFLAGS} -dynamiclib -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js cp -f ${LIB_DIR}/Window.o ${LJS_LIBDIR}/ncurses/Window.so cp -f ${LIB_DIR}/Window.js ${LJS_LIBDIR}/ncurses/Window.js cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js cp -f ${LIB_DIR}/Panel.o ${LJS_LIBDIR}/ncurses/Panel.so cp -f ${LIB_DIR}/Panel.js ${LJS_LIBDIR}/ncurses/Panel.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses lib_uninstall: rm -rf ${LJS_LIBDIR}/ncurses install: lib_install uninstall: lib_uninstall clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Panel.cpp b/src/Panel.cpp index d30372c..83a771a 100644 --- a/src/Panel.cpp +++ b/src/Panel.cpp @@ -1,247 +1,232 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval property = JS_EVAL(cx, "ncurses.Window"); JSObject* obj = JSVAL_TO_OBJECT(property); - JSClass* klass = JS_GET_CLASS(cx, obj); - JSObject* Window = JS_NewObject(cx, klass, NULL, NULL); - - JS_GetProperty(cx, obj, "prototype", &property); - - if (!JSVAL_IS_VOID(property)) { - JS_SetPrototype(cx, Window, JSVAL_TO_OBJECT(property)); - } - - JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(obj), argc, argv, &property); - - if (!JSVAL_IS_VOID(property)) { - JS_SetProperty(cx, object, "__window", &property); - } - else { - property = OBJECT_TO_JSVAL(Window); - JS_SetProperty(cx, object, "__window", &property); - } + JSObject* Window = JS_New(cx, obj, argc, argv); + property = OBJECT_TO_JSVAL(Window); + JS_SetProperty(cx, object, "__window", property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels[panel] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, Panel_below, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, Panel_above, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); if (panel) { panels.erase(panel); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); hide_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); show_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); JS_ValueToObject(cx, argv[0], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* above = panel_above(panel); *vp = OBJECT_TO_JSVAL(panels[above]); return JS_TRUE; } JSBool Panel_below (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* below = panel_below(panel); *vp = OBJECT_TO_JSVAL(panels[below]); return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/test/binclock.js b/test/binclock.js index a323343..d0ad935 100755 --- a/test/binclock.js +++ b/test/binclock.js @@ -1,165 +1,167 @@ #! /usr/bin/env ljs require("ncurses"); var screen = ncurses.Screen.init({buffering: ncurses.Buffering.CBreak}); screen.show = true; screen.showClock = function () { this.createContainer(); for (let name in bcd) { let x; switch (name) { case "hours": x = 15; break; case "minutes": x = 25; break; case "seconds": x = 36; break; } for (let i = 3; i >= 0; i--) { this.printString(bcd[name].u[i], {x: x, y: i+5, fg: ncurses.Colors.Blue}); } if (name != "hours") { for (let i = 2; i >= 0; i--) { this.printString(bcd[name].d[i], {x: x-4, y: i+6, fg: ncurses.Colors.Blue}); } } else { for (let i = 1; i >= 0; i--) { this.printString(bcd[name].d[i], {x: x-4, y: i+7, fg: ncurses.Colors.Blue}); } } } for (let name in binary) { let x; switch (name) { case "hours": x = 13; break; case "minutes": x = 23; break; case "seconds": x = 34; break; } if (name != "hours") { for (let i = 5; i >= 0; i--) { this.printString(binary[name][i], {x: x, y: i+10, fg: ncurses.Colors.Blue}); } } else { for (let i = 4; i >= 0; i--) { this.printString(binary[name][i], {x: x, y: i+11, fg: ncurses.Colors.Blue}); } } } var hours = now.getHours().toPaddedString(2).toArray(); var minutes = now.getMinutes().toPaddedString(2).toArray(); var seconds = now.getSeconds().toPaddedString(2).toArray(); this.printString(hours[0]+" "+hours[1], {x: 12, y: 17, fg: ncurses.Colors.Blue}); this.printString(":", {x: 18, y: 17, fg: ncurses.Colors.Blue}); this.printString(minutes[0]+" "+minutes[1], {x: 22, y: 17, fg: ncurses.Colors.Blue}); this.printString(":", {x: 29, y: 17, fg: ncurses.Colors.Blue}); this.printString(seconds[0]+" "+seconds[1], {x: 33, y: 17, fg: ncurses.Colors.Blue}); this.refresh(); }; screen.createContainer = function () { this.printString("Hours", {x: 11, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("Minutes", {x: 20, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("Seconds", {x: 31, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("8", {x: 8, y: 5, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("4", {x: 8, y: 6, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("2", {x: 8, y: 7, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("1", {x: 8, y: 8, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("B", {x: 40, y: 5, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("C", {x: 40, y: 6, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("D", {x: 40, y: 7, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString(" ".times(31), {x: 9, y: 4, bg: ncurses.Colors.Red}); for each (let i in range(5, 9)) { this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); } this.printString(" ".times(31), {x: 9, y: 9, bg: ncurses.Colors.Red}); this.printString("32", {x: 7, y: 10, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("16", {x: 7, y: 11, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "8", {x: 8, y: 12, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "4", {x: 8, y: 13, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "2", {x: 8, y: 14, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "1", {x: 8, y: 15, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("B", {x: 40, y: 10, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("I", {x: 40, y: 11, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("N", {x: 40, y: 12, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("A", {x: 40, y: 13, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("R", {x: 40, y: 14, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("Y", {x: 40, y: 15, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); for each (let i in range(10, 15)) { this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); } this.printString(" ".times(31), {x: 9, y: 16, bg: ncurses.Colors.Red}); this.printString(" ", {x: 9, y: 17, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: 17, bg: ncurses.Colors.Red}); this.printString(" ".times(31), {x: 9, y: 18, bg: ncurses.Colors.Red}); } screen.onResize = function () { - if (this.Size.Width < 40 || this.Size.Height < 23) { - this.erase(); - this.printString("LOL FAG", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + if (this.Size.Width < 50 || this.Size.Height < 23) { this.show = false; } else { - this.erase(); - showClock(); this.show = true; + this.erase(); + this.showClock(); } - this.refresh(); }; screen.printString("Press C-c to close the program", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); screen.refresh(); while (true) { now = new Date; binary = { seconds: now.getSeconds().toPaddedString(6, 2).toArray(), minutes: now.getMinutes().toPaddedString(6, 2).toArray(), hours : now.getHours().toPaddedString(5, 2).toArray() }; bcd = { seconds: { d: Math.floor(now.getSeconds()/10).toPaddedString(3, 2).toArray(), u: (now.getSeconds()%10).toPaddedString(4, 2).toArray() }, minutes: { d: Math.floor(now.getMinutes()/10).toPaddedString(3, 2).toArray(), u: (now.getMinutes()%10).toPaddedString(4, 2).toArray() }, hours: { d: Math.floor(now.getHours()/10).toPaddedString(2, 2).toArray(), u: (now.getHours()%10).toPaddedString(4, 2).toArray() } }; if (screen.show) { + screen.printString(screen.show, {x: 2, y: 2}); screen.showClock(); } + else { + screen.erase(); + screen.printString("LOL FAG", {x: 2, y: 2, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + } sleep(1); }
meh/lulzjs-ncurses
fe77860a9f36e892491fe13eea477a17c0e14bb2
Improved some stuff :3
diff --git a/test/binclock.js b/test/binclock.js index fa58cc0..a323343 100755 --- a/test/binclock.js +++ b/test/binclock.js @@ -1,155 +1,165 @@ #! /usr/bin/env ljs require("ncurses"); -show = true; - var screen = ncurses.Screen.init({buffering: ncurses.Buffering.CBreak}); +screen.show = true; screen.showClock = function () { this.createContainer(); for (let name in bcd) { let x; switch (name) { case "hours": x = 15; break; case "minutes": x = 25; break; case "seconds": x = 36; break; } for (let i = 3; i >= 0; i--) { this.printString(bcd[name].u[i], {x: x, y: i+5, fg: ncurses.Colors.Blue}); } if (name != "hours") { for (let i = 2; i >= 0; i--) { this.printString(bcd[name].d[i], {x: x-4, y: i+6, fg: ncurses.Colors.Blue}); } } else { for (let i = 1; i >= 0; i--) { this.printString(bcd[name].d[i], {x: x-4, y: i+7, fg: ncurses.Colors.Blue}); } } } for (let name in binary) { let x; switch (name) { case "hours": x = 13; break; case "minutes": x = 23; break; case "seconds": x = 34; break; } if (name != "hours") { for (let i = 5; i >= 0; i--) { this.printString(binary[name][i], {x: x, y: i+10, fg: ncurses.Colors.Blue}); } } else { for (let i = 4; i >= 0; i--) { this.printString(binary[name][i], {x: x, y: i+11, fg: ncurses.Colors.Blue}); } } } - var hours = now.getHours().toPaddedString(2).split(''); - var minutes = now.getMinutes().toPaddedString(2).split(''); - var seconds = now.getSeconds().toPaddedString(2).split(''); + var hours = now.getHours().toPaddedString(2).toArray(); + var minutes = now.getMinutes().toPaddedString(2).toArray(); + var seconds = now.getSeconds().toPaddedString(2).toArray(); this.printString(hours[0]+" "+hours[1], {x: 12, y: 17, fg: ncurses.Colors.Blue}); this.printString(":", {x: 18, y: 17, fg: ncurses.Colors.Blue}); this.printString(minutes[0]+" "+minutes[1], {x: 22, y: 17, fg: ncurses.Colors.Blue}); this.printString(":", {x: 29, y: 17, fg: ncurses.Colors.Blue}); this.printString(seconds[0]+" "+seconds[1], {x: 33, y: 17, fg: ncurses.Colors.Blue}); this.refresh(); }; screen.createContainer = function () { this.printString("Hours", {x: 11, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("Minutes", {x: 20, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("Seconds", {x: 31, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("8", {x: 8, y: 5, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("4", {x: 8, y: 6, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("2", {x: 8, y: 7, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("1", {x: 8, y: 8, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("B", {x: 40, y: 5, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("C", {x: 40, y: 6, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("D", {x: 40, y: 7, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString(" ".times(31), {x: 9, y: 4, bg: ncurses.Colors.Red}); for each (let i in range(5, 9)) { this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); } this.printString(" ".times(31), {x: 9, y: 9, bg: ncurses.Colors.Red}); this.printString("32", {x: 7, y: 10, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString("16", {x: 7, y: 11, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "8", {x: 8, y: 12, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "4", {x: 8, y: 13, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "2", {x: 8, y: 14, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); this.printString( "1", {x: 8, y: 15, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("B", {x: 40, y: 10, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("I", {x: 40, y: 11, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("N", {x: 40, y: 12, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("A", {x: 40, y: 13, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("R", {x: 40, y: 14, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("Y", {x: 40, y: 15, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + for each (let i in range(10, 15)) { this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); } this.printString(" ".times(31), {x: 9, y: 16, bg: ncurses.Colors.Red}); this.printString(" ", {x: 9, y: 17, bg: ncurses.Colors.Red}); this.printString(" ", {x: 39, y: 17, bg: ncurses.Colors.Red}); this.printString(" ".times(31), {x: 9, y: 18, bg: ncurses.Colors.Red}); } screen.onResize = function () { if (this.Size.Width < 40 || this.Size.Height < 23) { this.erase(); this.printString("LOL FAG", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); - show = false; + this.show = false; } else { this.erase(); showClock(); - show = true; + this.show = true; } this.refresh(); }; screen.printString("Press C-c to close the program", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); screen.refresh(); while (true) { now = new Date; binary = { - seconds: now.getSeconds().toPaddedString(6, 2).split(''), - minutes: now.getMinutes().toPaddedString(6, 2).split(''), - hours : now.getHours().toPaddedString(5, 2).split('') + seconds: now.getSeconds().toPaddedString(6, 2).toArray(), + minutes: now.getMinutes().toPaddedString(6, 2).toArray(), + hours : now.getHours().toPaddedString(5, 2).toArray() }; bcd = { seconds: { - d: Math.floor(now.getSeconds()/10).toPaddedString(3, 2).split(''), - u: (now.getSeconds()%10).toPaddedString(4, 2).split('') + d: Math.floor(now.getSeconds()/10).toPaddedString(3, 2).toArray(), + u: (now.getSeconds()%10).toPaddedString(4, 2).toArray() }, minutes: { - d: Math.floor(now.getMinutes()/10).toPaddedString(3, 2).split(''), - u: (now.getMinutes()%10).toPaddedString(4, 2).split('') + d: Math.floor(now.getMinutes()/10).toPaddedString(3, 2).toArray(), + u: (now.getMinutes()%10).toPaddedString(4, 2).toArray() }, hours: { - d: Math.floor(now.getHours()/10).toPaddedString(2, 2).split(''), - u: (now.getHours()%10).toPaddedString(4, 2).split('') + d: Math.floor(now.getHours()/10).toPaddedString(2, 2).toArray(), + u: (now.getHours()%10).toPaddedString(4, 2).toArray() } }; - if (show) { + if (screen.show) { screen.showClock(); } sleep(1); }
meh/lulzjs-ncurses
717431f947ab1159aa5151120f89840072896127
Added some methods and an example.
diff --git a/src/Panel.cpp b/src/Panel.cpp index 60fde70..d30372c 100644 --- a/src/Panel.cpp +++ b/src/Panel.cpp @@ -1,238 +1,247 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval property = JS_EVAL(cx, "ncurses.Window"); - JSObject* klass = JSVAL_TO_OBJECT(property); + JSObject* obj = JSVAL_TO_OBJECT(property); - JS_GetProperty(cx, klass, "prototype", &property); - JSObject* proto = JSVAL_TO_OBJECT(property); - - JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, klass), proto, NULL); - JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(klass), argc, argv, &property); + JSClass* klass = JS_GET_CLASS(cx, obj); + JSObject* Window = JS_NewObject(cx, klass, NULL, NULL); + + JS_GetProperty(cx, obj, "prototype", &property); + + if (!JSVAL_IS_VOID(property)) { + JS_SetPrototype(cx, Window, JSVAL_TO_OBJECT(property)); + } - property = OBJECT_TO_JSVAL(Window); - JS_SetProperty(cx, object, "__window", &property); + JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(obj), argc, argv, &property); + + if (!JSVAL_IS_VOID(property)) { + JS_SetProperty(cx, object, "__window", &property); + } + else { + property = OBJECT_TO_JSVAL(Window); + JS_SetProperty(cx, object, "__window", &property); + } PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); - panels[panel] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, Panel_below, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, Panel_above, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); if (panel) { panels.erase(panel); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); hide_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); show_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); JS_ValueToObject(cx, argv[0], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* above = panel_above(panel); *vp = OBJECT_TO_JSVAL(panels[above]); return JS_TRUE; } JSBool Panel_below (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* below = panel_below(panel); *vp = OBJECT_TO_JSVAL(panels[below]); return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.js b/src/Panel.js index 92dffe0..6ad1ee8 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,62 +1,70 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { refresh: function () { this.__window.refresh(); }, + clear: function () { + this.__window.clear(); + }, + + erase: function () { + this.__window.erase(); + }, + resize: function (obj) { this.__window.resize(obj); ncurses.Panel.update(); ncurses.Screen.update(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); }, getString: function (options) { return (options ? this.__window.getString(options) : this.__window.getString()); } }); Object.addGetters(ncurses.Panel, { Size: function () { return this.__window.Size; }, Position: function () { return this.__window.Position; } }); diff --git a/src/Window.cpp b/src/Window.cpp index 3b67146..91a4a80 100644 --- a/src/Window.cpp +++ b/src/Window.cpp @@ -1,669 +1,687 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" #include <assert.h> void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = (WINDOW*) JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); JS_ValueToObject(cx, argv[0], &options); jsval width, height; JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } +JSBool +Window_clear (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); + + wclear(win); + return JS_TRUE; +} + +JSBool +Window_erase (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); + + werase(win); + return JS_TRUE; +} + JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { char* string = (char*) JS_malloc(cx, 16*sizeof(char)); size_t length = 0; JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 16) { string = (char*) JS_realloc(cx, string, (length+16+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; string = (char*) JS_realloc(cx, string, length*sizeof(char)); JSString* jsString = JS_NewString(cx, string, strlen(string)); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return jsString; } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getmaxyx(win, height, width); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getbegyx(win, y, x); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); } diff --git a/src/Window.h b/src/Window.h index 1035514..f343c02 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,62 +1,66 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_WINDOW_H #define _LULZJS_NCURSES_WINDOW_H #include "common.h" extern "C" JSBool exec (JSContext* cx); JSBool Window_initialize (JSContext* cx); JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; #include "Window_private.h" JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_clear (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_erase (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, {"resize", Window_resize, 0, 0, 0}, + {"clear", Window_clear, 0, 0, 0}, + {"erase", Window_erase, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, {"getString", Window_getString, 0, 0, 0}, {NULL} }; #endif diff --git a/test/binclock.js b/test/binclock.js new file mode 100755 index 0000000..fa58cc0 --- /dev/null +++ b/test/binclock.js @@ -0,0 +1,155 @@ +#! /usr/bin/env ljs +require("ncurses"); + +show = true; + +var screen = ncurses.Screen.init({buffering: ncurses.Buffering.CBreak}); + +screen.showClock = function () +{ + this.createContainer(); + + for (let name in bcd) { + let x; + switch (name) { + case "hours": x = 15; break; + case "minutes": x = 25; break; + case "seconds": x = 36; break; + } + + for (let i = 3; i >= 0; i--) { + this.printString(bcd[name].u[i], {x: x, y: i+5, fg: ncurses.Colors.Blue}); + } + + if (name != "hours") { + for (let i = 2; i >= 0; i--) { + this.printString(bcd[name].d[i], {x: x-4, y: i+6, fg: ncurses.Colors.Blue}); + } + } + else { + for (let i = 1; i >= 0; i--) { + this.printString(bcd[name].d[i], {x: x-4, y: i+7, fg: ncurses.Colors.Blue}); + } + } + } + + for (let name in binary) { + let x; + switch (name) { + case "hours": x = 13; break; + case "minutes": x = 23; break; + case "seconds": x = 34; break; + } + + if (name != "hours") { + for (let i = 5; i >= 0; i--) { + this.printString(binary[name][i], {x: x, y: i+10, fg: ncurses.Colors.Blue}); + } + } + else { + for (let i = 4; i >= 0; i--) { + this.printString(binary[name][i], {x: x, y: i+11, fg: ncurses.Colors.Blue}); + } + } + } + + var hours = now.getHours().toPaddedString(2).split(''); + var minutes = now.getMinutes().toPaddedString(2).split(''); + var seconds = now.getSeconds().toPaddedString(2).split(''); + + this.printString(hours[0]+" "+hours[1], {x: 12, y: 17, fg: ncurses.Colors.Blue}); + this.printString(":", {x: 18, y: 17, fg: ncurses.Colors.Blue}); + this.printString(minutes[0]+" "+minutes[1], {x: 22, y: 17, fg: ncurses.Colors.Blue}); + this.printString(":", {x: 29, y: 17, fg: ncurses.Colors.Blue}); + this.printString(seconds[0]+" "+seconds[1], {x: 33, y: 17, fg: ncurses.Colors.Blue}); + + this.refresh(); +}; + +screen.createContainer = function () +{ + this.printString("Hours", {x: 11, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("Minutes", {x: 20, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("Seconds", {x: 31, y: 3, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + + this.printString("8", {x: 8, y: 5, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("4", {x: 8, y: 6, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("2", {x: 8, y: 7, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("1", {x: 8, y: 8, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + + this.printString(" ".times(31), {x: 9, y: 4, bg: ncurses.Colors.Red}); + for each (let i in range(5, 9)) { + this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); + this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); + } + this.printString(" ".times(31), {x: 9, y: 9, bg: ncurses.Colors.Red}); + + this.printString("32", {x: 7, y: 10, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString("16", {x: 7, y: 11, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString( "8", {x: 8, y: 12, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString( "4", {x: 8, y: 13, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString( "2", {x: 8, y: 14, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + this.printString( "1", {x: 8, y: 15, fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + + for each (let i in range(10, 15)) { + this.printString(" ", {x: 9, y: i, bg: ncurses.Colors.Red}); + this.printString(" ", {x: 39, y: i, bg: ncurses.Colors.Red}); + } + this.printString(" ".times(31), {x: 9, y: 16, bg: ncurses.Colors.Red}); + + this.printString(" ", {x: 9, y: 17, bg: ncurses.Colors.Red}); + this.printString(" ", {x: 39, y: 17, bg: ncurses.Colors.Red}); + + this.printString(" ".times(31), {x: 9, y: 18, bg: ncurses.Colors.Red}); +} + +screen.onResize = function () { + if (this.Size.Width < 40 || this.Size.Height < 23) { + this.erase(); + this.printString("LOL FAG", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Standout}); + show = false; + } + else { + this.erase(); + showClock(); + show = true; + } + this.refresh(); +}; + +screen.printString("Press C-c to close the program", {fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); +screen.refresh(); + +while (true) { + now = new Date; + + binary = { + seconds: now.getSeconds().toPaddedString(6, 2).split(''), + minutes: now.getMinutes().toPaddedString(6, 2).split(''), + hours : now.getHours().toPaddedString(5, 2).split('') + }; + + bcd = { + seconds: { + d: Math.floor(now.getSeconds()/10).toPaddedString(3, 2).split(''), + u: (now.getSeconds()%10).toPaddedString(4, 2).split('') + }, + + minutes: { + d: Math.floor(now.getMinutes()/10).toPaddedString(3, 2).split(''), + u: (now.getMinutes()%10).toPaddedString(4, 2).split('') + }, + + hours: { + d: Math.floor(now.getHours()/10).toPaddedString(2, 2).split(''), + u: (now.getHours()%10).toPaddedString(4, 2).split('') + } + }; + + if (show) { + screen.showClock(); + } + + sleep(1); +} +
meh/lulzjs-ncurses
9df071733475e2a9b44ec900c11eae51cdeee173
Probably fixes to threadsafe.
diff --git a/src/Panel.cpp b/src/Panel.cpp index 57a5a07..60fde70 100644 --- a/src/Panel.cpp +++ b/src/Panel.cpp @@ -1,240 +1,238 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval property = JS_EVAL(cx, "ncurses.Window"); JSObject* klass = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, klass, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, klass), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(klass), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels[panel] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, - (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), - NULL, JSPROP_GETTER|JSPROP_READONLY + Panel_below, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, - (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), - NULL, JSPROP_GETTER|JSPROP_READONLY + Panel_above, NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); if (panel) { panels.erase(panel); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); hide_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); show_panel(panel); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); JS_ValueToObject(cx, argv[0], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); JS_BeginRequest(cx); JS_EnterLocalRootScope(cx); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } JS_LeaveLocalRootScope(cx); JS_EndRequest(cx); PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool -Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +Panel_above (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { - PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* above = panel_above(panel); - *rval = OBJECT_TO_JSVAL(panels[above]); + *vp = OBJECT_TO_JSVAL(panels[above]); return JS_TRUE; } JSBool -Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +Panel_below (JSContext *cx, JSObject *obj, jsval id, jsval *vp) { - PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, obj); PANEL* below = panel_below(panel); - *rval = OBJECT_TO_JSVAL(panels[below]); + *vp = OBJECT_TO_JSVAL(panels[below]); return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index e21a2fd..7b98627 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,66 +1,66 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_PANEL_H #define _LULZJS_NCURSES_PANEL_H #include "common.h" #include <map> std::map <PANEL*, JSObject*> panels; extern "C" JSBool exec (JSContext* cx); JSBool Panel_initialize (JSContext* cx); JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_above (JSContext *cx, JSObject *obj, jsval id, jsval *vp); +JSBool Panel_below (JSContext *cx, JSObject *obj, jsval id, jsval *vp); JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"move", Panel_move, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif
meh/lulzjs-ncurses
e9694c867403c2b08a50eb63bcf3d6c0ad35838c
Near the solution, GC LOL FAIL.
diff --git a/src/Panel.cpp b/src/Panel.cpp index d80177c..57a5a07 100644 --- a/src/Panel.cpp +++ b/src/Panel.cpp @@ -1,213 +1,240 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - jsval property; - JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); - JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval property = JS_EVAL(cx, "ncurses.Window"); JSObject* klass = JSVAL_TO_OBJECT(property); + JS_GetProperty(cx, klass, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, klass), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(klass), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels[panel] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); if (panel) { panels.erase(panel); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); hide_panel(panel); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); show_panel(panel); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + JS_ValueToObject(cx, argv[0], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); + + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); *rval = OBJECT_TO_JSVAL(panels[above]); return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); *rval = OBJECT_TO_JSVAL(panels[below]); return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index 27e4cc4..e21a2fd 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,66 +1,66 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_PANEL_H #define _LULZJS_NCURSES_PANEL_H #include "common.h" #include <map> std::map <PANEL*, JSObject*> panels; -extern JSBool exec (JSContext* cx); -extern JSBool Panel_initialize (JSContext* cx); +extern "C" JSBool exec (JSContext* cx); +JSBool Panel_initialize (JSContext* cx); -extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern void Panel_finalize (JSContext* cx, JSObject* object); +JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; -extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"move", Panel_move, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Screen.h b/src/Screen.h index 950b320..3c926bf 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,51 +1,51 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window.h" #include <signal.h> -extern JSBool exec (JSContext* cx); -extern JSBool Screen_initialize (JSContext* cx); +extern "C" JSBool exec (JSContext* cx); +JSBool Screen_initialize (JSContext* cx); -extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern void Screen_finalize (JSContext* cx, JSObject* object); +JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" -extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.cpp b/src/Window.cpp index 4c68f69..3b67146 100644 --- a/src/Window.cpp +++ b/src/Window.cpp @@ -1,592 +1,669 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" #include <assert.h> void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); - printf("%s - ", Window_class.name); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); - printf("%s\n", Window_class.name); - - assert(object != NULL); - JSClass* lol = JS_GET_CLASS(cx, object); - assert(lol == &Window_class); - printf("%s %d\n\n", lol->name, lol->flags); - getchar(); if (object) { + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = (WINDOW*) JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + JS_ValueToObject(cx, argv[0], &options); jsval width, height; JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_TRUE; - } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { - char* string = (char*) malloc(512*sizeof(char)); + char* string = (char*) JS_malloc(cx, 16*sizeof(char)); size_t length = 0; + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { - if ((length+1) % 512) { - string = (char*) realloc(string, (length+512+1)*sizeof(char)); + if ((length+1) % 16) { + string = (char*) JS_realloc(cx, string, (length+16+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; - string = (char*) realloc(string, length*sizeof(char)); + string = (char*) JS_realloc(cx, string, length*sizeof(char)); + + JSString* jsString = JS_NewString(cx, string, strlen(string)); - return JS_NewString(cx, string, strlen(string)); + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); + return jsString; } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getmaxyx(win, height, width); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getbegyx(win, y, x); + JS_BeginRequest(cx); + JS_EnterLocalRootScope(cx); + jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); + + JS_LeaveLocalRootScope(cx); + JS_EndRequest(cx); } diff --git a/src/Window.h b/src/Window.h index 5fabfa7..1035514 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,62 +1,62 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_WINDOW_H #define _LULZJS_NCURSES_WINDOW_H #include "common.h" -extern JSBool exec (JSContext* cx); -extern JSBool Window_initialize (JSContext* cx); +extern "C" JSBool exec (JSContext* cx); +JSBool Window_initialize (JSContext* cx); -extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern void Window_finalize (JSContext* cx, JSObject* object); +JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; #include "Window_private.h" -extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -extern JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, {"resize", Window_resize, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, {"getString", Window_getString, 0, 0, 0}, {NULL} }; #endif diff --git a/src/ncurses.h b/src/ncurses.h index 5e3a1a2..3e654f6 100644 --- a/src/ncurses.h +++ b/src/ncurses.h @@ -1,39 +1,39 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_H #define _LULZJS_NCURSES_H #include "common.h" -extern JSBool exec (JSContext* cx); -extern JSBool ncurses_initialize (JSContext* cx); +extern "C" JSBool exec (JSContext* cx); +JSBool ncurses_initialize (JSContext* cx); static JSClass ncurses_class = { "ncurses", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; -extern JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec ncurses_methods[] = { {NULL} }; #endif
meh/lulzjs-ncurses
0996dca0dba3866c42df6b88d2979e937b39a3e3
Going to C++.
diff --git a/Makefile b/Makefile index 2966fc4..75810aa 100644 --- a/Makefile +++ b/Makefile @@ -1,54 +1,54 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" $(shell js-config --cflags) -I./src LDFLAGS = $(shell js-config --libs) -llulzjs ifdef DEBUG CFLAGS += -g -Wall endif ifdef DDEBUG CFLAGS += -DDEBUG -g -Wall endif LIB_DIR = src LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o ${LIB_DIR}/Panel.o LIB_CFLAGS = ${CFLAGS} LIB_LDFLAGS = ${LDFLAGS} -lpanel -lform -lmenu -lncurses all: lib lib: $(LIB) -$(LIB) : $(LIB:.o=.c) - ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo - ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc +$(LIB) : $(LIB:.o=.cpp) + ${CXX} ${LIB_CFLAGS} -fPIC -c $*.cpp -o $*.lo + ${CXX} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js cp -f ${LIB_DIR}/Window.o ${LJS_LIBDIR}/ncurses/Window.so cp -f ${LIB_DIR}/Window.js ${LJS_LIBDIR}/ncurses/Window.js cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js cp -f ${LIB_DIR}/Panel.o ${LJS_LIBDIR}/ncurses/Panel.so cp -f ${LIB_DIR}/Panel.js ${LJS_LIBDIR}/ncurses/Panel.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses lib_uninstall: rm -rf ${LJS_LIBDIR}/ncurses install: lib_install uninstall: lib_uninstall clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Panel.c b/src/Panel.cpp similarity index 77% rename from src/Panel.c rename to src/Panel.cpp index 8486917..d80177c 100644 --- a/src/Panel.c +++ b/src/Panel.cpp @@ -1,244 +1,213 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" -extern JSObject** panels; -extern int panelsSize; - JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); - JSObject* class = JSVAL_TO_OBJECT(property); - JS_GetProperty(cx, class, "prototype", &property); + JSObject* klass = JSVAL_TO_OBJECT(property); + JS_GetProperty(cx, klass, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); - JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); - JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); + JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, klass), proto, NULL); + JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(klass), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); - panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); - panels[panelsSize-1] = object; + panels[panel] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); if (panel) { - // Find the object being finalized and remove it from the list - int i; - for (i = 0; i < panelsSize; i++) { - if (object == panels[i]) { - break; - } - } - for (i++; i < panelsSize; i++) { - panels[i-1] = panels[i]; - } - panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); - + panels.erase(panel); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); - int i; - for (i = 0; i < panelsSize; i++) { - PANEL* check = JS_GetPrivate(cx, panels[i]); - - if (check == above) { - *rval = OBJECT_TO_JSVAL(panels[i]); - break; - } - } + *rval = OBJECT_TO_JSVAL(panels[above]); return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - PANEL* panel = JS_GetPrivate(cx, object); + PANEL* panel = (PANEL*) JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); - int i; - for (i = 0; i < panelsSize; i++) { - PANEL* check = JS_GetPrivate(cx, panels[i]); - - if (check == below) { - *rval = OBJECT_TO_JSVAL(panels[i]); - break; - } - } + *rval = OBJECT_TO_JSVAL(panels[below]); return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index caa1b11..27e4cc4 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,67 +1,66 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_PANEL_H #define _LULZJS_NCURSES_PANEL_H #include "common.h" -#include "Window_private.h" +#include <map> -JSObject** panels = NULL; -int panelsSize = 0; +std::map <PANEL*, JSObject*> panels; extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"move", Panel_move, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Screen.c b/src/Screen.cpp similarity index 95% rename from src/Screen.c rename to src/Screen.cpp index 2cd5f41..687cf71 100644 --- a/src/Screen.c +++ b/src/Screen.cpp @@ -1,318 +1,316 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } - ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); + ScreenInformation* data = new ScreenInformation; JS_SetPrivate(cx, object, data); signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } - jsval property; - JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); - JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); - JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); + jsval property = JS_EVAL(cx, "ncurses.Window"); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); - JSObject* Window = JS_NewObject(cx, class, proto, NULL); + JSObject* Window = JS_NewObject(cx, &Window_class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); - JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); + property = JSVAL_FALSE; + JS_SetProperty(cx, Window, "border", &property); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); option = JSVAL_FALSE; } else { echo(); option = JSVAL_TRUE; } data->echo = JSVAL_TO_BOOLEAN(option); JS_SetProperty(cx, object, "echo", &option); // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case 2: raw(); break; case 3: cbreak(); break; default: option = INT_TO_JSVAL(1); break; } data->buffering = JSVAL_TO_INT(option); JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); option = JSVAL_TRUE; } else { option = JSVAL_FALSE; } data->keypad = JSVAL_TO_BOOLEAN(option); JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); jsint cursor = JS_ParseInt(cx, option, 0); curs_set(cursor); option = INT_TO_JSVAL(cursor); JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { - ScreenInformation* data = JS_GetPrivate(cx, object); + ScreenInformation* data = (ScreenInformation*) JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case 2: noraw(); break; case 3: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); - JS_free(cx, data); + delete data; } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index b0207e2..950b320 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,51 +1,51 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" -#include "Window_private.h" +#include "Window.h" #include <signal.h> extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.c b/src/Window.cpp similarity index 94% rename from src/Window.c rename to src/Window.cpp index a34b890..4c68f69 100644 --- a/src/Window.c +++ b/src/Window.cpp @@ -1,583 +1,592 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" +#include <assert.h> void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); + printf("%s - ", Window_class.name); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); + printf("%s\n", Window_class.name); + + assert(object != NULL); + JSClass* lol = JS_GET_CLASS(cx, object); + assert(lol == &Window_class); + printf("%s %d\n\n", lol->name, lol->flags); + getchar(); if (object) { return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { - WINDOW* parentWin = JS_GetPrivate(cx, parent); + WINDOW* parentWin = (WINDOW*) JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width, height; JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_NULL(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_NULL(height)) { JS_GetProperty(cx, options, "Height", &height); } if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_NULL(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_NULL(y)) { JS_GetProperty(cx, options, "Y", &y); } __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { - char* string = JS_malloc(cx, 512*sizeof(char)); + char* string = (char*) malloc(512*sizeof(char)); size_t length = 0; string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 512) { - string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); + string = (char*) realloc(string, (length+512+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; - string = JS_realloc(cx, string, length*sizeof(char)); + string = (char*) realloc(string, length*sizeof(char)); return JS_NewString(cx, string, strlen(string)); } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = (WINDOW*) JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/ncurses.c b/src/ncurses.cpp similarity index 100% rename from src/ncurses.c rename to src/ncurses.cpp
meh/lulzjs-ncurses
a71036f03259e1ae7afb7e3d477aeba6f4bfaf46
Added TODO.
diff --git a/TODO b/TODO new file mode 100644 index 0000000..b503695 --- /dev/null +++ b/TODO @@ -0,0 +1 @@ +Implement Menu and Form.
meh/lulzjs-ncurses
bc82d73027f6d6672126ed39b1969ccda76de4c2
Fixes.
diff --git a/Makefile b/Makefile index 96bb2b4..f9f7be7 100644 --- a/Makefile +++ b/Makefile @@ -1,54 +1,54 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" -I/usr/include/js -I./src LDFLAGS = -ljs -llulzjs ifdef DEBUG -CFLAGS += -g +CFLAGS += -g -Wall endif ifdef DDEBUG -CFLAGS += -DDEBUG -g +CFLAGS += -DDEBUG -g -Wall endif LIB_DIR = src LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o ${LIB_DIR}/Panel.o LIB_CFLAGS = ${CFLAGS} LIB_LDFLAGS = ${LDFLAGS} -lpanel -lform -lmenu -lncurses all: lib lib: $(LIB) $(LIB) : $(LIB:.o=.c) ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js cp -f ${LIB_DIR}/Window.o ${LJS_LIBDIR}/ncurses/Window.so cp -f ${LIB_DIR}/Window.js ${LJS_LIBDIR}/ncurses/Window.js cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js cp -f ${LIB_DIR}/Panel.o ${LJS_LIBDIR}/ncurses/Panel.so cp -f ${LIB_DIR}/Panel.js ${LJS_LIBDIR}/ncurses/Panel.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses lib_uninstall: rm -rf ${LJS_LIBDIR}/ncurses install: lib_install uninstall: lib_uninstall clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Panel.h b/src/Panel.h index cd678d6..caa1b11 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,67 +1,67 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ -#ifndef _LULZJS_NCURSES_SCREEN_H -#define _LULZJS_NCURSES_SCREEN_H +#ifndef _LULZJS_NCURSES_PANEL_H +#define _LULZJS_NCURSES_PANEL_H #include "common.h" #include "Window_private.h" JSObject** panels = NULL; int panelsSize = 0; extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"move", Panel_move, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.c b/src/Window.c index 381950c..ca4ac84 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,554 +1,553 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { - return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_UNDEFINED(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_UNDEFINED(height)) { JS_GetProperty(cx, options, "Height", &height); } JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width, height; JS_GetProperty(cx, options, "width", &width); if (JSVAL_IS_VOID(width) || JSVAL_IS_UNDEFINED(width)) { JS_GetProperty(cx, options, "Width", &width); } JS_GetProperty(cx, options, "height", &height); if (JSVAL_IS_VOID(height) || JSVAL_IS_UNDEFINED(height)) { JS_GetProperty(cx, options, "Height", &height); } if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { JS_GetProperty(cx, options, "Y", &y); } jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { JS_GetProperty(cx, options, "Y", &y); } if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { JS_GetProperty(cx, options, "X", &x); } JS_GetProperty(cx, options, "y", &y); if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { JS_GetProperty(cx, options, "Y", &y); } __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { char* string = JS_malloc(cx, 512*sizeof(char)); size_t length = 0; string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 512) { string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; string = JS_realloc(cx, string, length*sizeof(char)); return JS_NewString(cx, string, strlen(string)); } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); diff --git a/src/Window.h b/src/Window.h index 22cbff1..5fabfa7 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,62 +1,62 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ -#ifndef _LULZJS_NCURSES_SCREEN_H -#define _LULZJS_NCURSES_SCREEN_H +#ifndef _LULZJS_NCURSES_WINDOW_H +#define _LULZJS_NCURSES_WINDOW_H #include "common.h" extern JSBool exec (JSContext* cx); extern JSBool Window_initialize (JSContext* cx); extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; #include "Window_private.h" extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, {"resize", Window_resize, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, {"getString", Window_getString, 0, 0, 0}, {NULL} }; #endif
meh/lulzjs-ncurses
b8544657fe540a74db6f8a88511181cb6441fd45
Some bug fixes.
diff --git a/src/Panel.c b/src/Panel.c index 13a1a3d..feb3f68 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,235 +1,244 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); - jsval x; JS_GetProperty(cx, options, "x", &x); - jsval y; JS_GetProperty(cx, options, "y", &y); + jsval x, y; + + JS_GetProperty(cx, options, "x", &x); + if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { + JS_GetProperty(cx, options, "X", &x); + } + + JS_GetProperty(cx, options, "y", &y); + if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { + JS_GetProperty(cx, options, "Y", &y); + } if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } PANEL* panel = JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Window.c b/src/Window.c index 59c2163..381950c 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,534 +1,584 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); + JS_GetProperty(cx, options, "width", &width); + if (JSVAL_IS_VOID(width) || JSVAL_IS_UNDEFINED(width)) { + JS_GetProperty(cx, options, "Width", &width); + } + JS_GetProperty(cx, options, "height", &height); + if (JSVAL_IS_VOID(height) || JSVAL_IS_UNDEFINED(height)) { + JS_GetProperty(cx, options, "Height", &height); + } + JS_GetProperty(cx, options, "x", &x); + if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { + JS_GetProperty(cx, options, "X", &x); + } + JS_GetProperty(cx, options, "y", &y); + if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { + JS_GetProperty(cx, options, "Y", &y); + } jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); - jsval width; JS_GetProperty(cx, options, "width", &width); - jsval height; JS_GetProperty(cx, options, "height", &height); + + jsval width, height; + + JS_GetProperty(cx, options, "width", &width); + if (JSVAL_IS_VOID(width) || JSVAL_IS_UNDEFINED(width)) { + JS_GetProperty(cx, options, "Width", &width); + } + + JS_GetProperty(cx, options, "height", &height); + if (JSVAL_IS_VOID(height) || JSVAL_IS_UNDEFINED(height)) { + JS_GetProperty(cx, options, "Height", &height); + } if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; + JS_GetProperty(cx, options, "x", &x); + if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { + JS_GetProperty(cx, options, "X", &x); + } + JS_GetProperty(cx, options, "y", &y); + if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { + JS_GetProperty(cx, options, "Y", &y); + } jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; + JS_GetProperty(cx, options, "x", &x); + if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { + JS_GetProperty(cx, options, "X", &x); + } + JS_GetProperty(cx, options, "y", &y); + if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { + JS_GetProperty(cx, options, "Y", &y); + } if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; + JS_GetProperty(cx, options, "x", &x); + if (JSVAL_IS_VOID(x) || JSVAL_IS_UNDEFINED(x)) { + JS_GetProperty(cx, options, "X", &x); + } + JS_GetProperty(cx, options, "y", &y); + if (JSVAL_IS_VOID(y) || JSVAL_IS_UNDEFINED(y)) { + JS_GetProperty(cx, options, "Y", &y); + } __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { char* string = JS_malloc(cx, 512*sizeof(char)); size_t length = 0; string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 512) { string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; string = JS_realloc(cx, string, length*sizeof(char)); return JS_NewString(cx, string, strlen(string)); } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); }
meh/lulzjs-ncurses
df357f73a164f8d4e888b5960f1c4619db44ae88
Forgot this file lol
diff --git a/src/Screen_private.h b/src/Screen_private.h new file mode 100644 index 0000000..57fc6d1 --- /dev/null +++ b/src/Screen_private.h @@ -0,0 +1,24 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +typedef struct { + int buffering; + JSBool keypad; + JSBool echo; +} ScreenInformation; +
meh/lulzjs-ncurses
e3303eae0cb14bc0262306fb1ae337870b265c50
Fixed some minor bugs.
diff --git a/src/Panel.c b/src/Panel.c index b49f0b6..13a1a3d 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,237 +1,235 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { - jsval property; - return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval x; JS_GetProperty(cx, options, "x", &x); jsval y; JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(x)) { JS_GetProperty(cx, object, "Position", &x); JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); } if (!JSVAL_IS_INT(y)) { JS_GetProperty(cx, object, "Position", &y); JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); } PANEL* panel = JS_GetPrivate(cx, object); move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); refresh(); update_panels(); doupdate(); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Screen.c b/src/Screen.c index 4cbedc5..101f24a 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,317 +1,317 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); - // Default properties - jsval property; - return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } + ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); + signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); option = JSVAL_FALSE; } else { echo(); option = JSVAL_TRUE; } + data->echo = JSVAL_TO_BOOLEAN(option); JS_SetProperty(cx, object, "echo", &option); // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case 2: raw(); break; case 3: cbreak(); break; default: option = INT_TO_JSVAL(1); break; } + data->buffering = JSVAL_TO_INT(option); JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); option = JSVAL_TRUE; } else { option = JSVAL_FALSE; } + data->keypad = JSVAL_TO_BOOLEAN(option); JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); jsint cursor = JS_ParseInt(cx, option, 0); curs_set(cursor); option = INT_TO_JSVAL(cursor); JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { - jsval jsScreen, jsBuffering, jsKeypad, jsEcho; - JS_GetProperty(cx, object, "ncurses", &jsScreen); - JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "Screen", &jsScreen); + ScreenInformation* data = JS_GetPrivate(cx, object); - JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "buffering", &jsBuffering); - JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "keypad", &jsBuffering); - JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "echo", &jsBuffering); + if (data) { + switch (data->buffering) { + case 2: noraw(); break; + case 3: nocbreak(); break; + } - switch (JSVAL_TO_INT(jsBuffering)) { - case 2: noraw(); break; - case 3: nocbreak(); break; - } + if (data->keypad) { + keypad(stdscr, FALSE); + } - if (JSVAL_TO_BOOLEAN(jsKeypad)) { - keypad(stdscr, FALSE); - } + if (!data->echo) { + echo(); + } - if (!JSVAL_TO_BOOLEAN(jsEcho)) { - echo(); - } + curs_set(1); + endwin(); - curs_set(1); - endwin(); + JS_free(cx, data); + } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index 9b76f92..b0207e2 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,49 +1,51 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" #include <signal.h> extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; +#include "Screen_private.h" + extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.c b/src/Window.c index 209c507..59c2163 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,536 +1,534 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { - // Default properties - jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } - WINDOW* win; + WINDOW* win = NULL; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); jsval property; JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); JS_GetProperty(cx, Screen, "cursor", &property); jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } return JS_TRUE; } void __Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { curs_set(1); echo(); } else { noecho(); } } else { curs_set(1); echo(); } } else { if (echoing) { echo(); } else { noecho(); } curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { char* string = JS_malloc(cx, 512*sizeof(char)); size_t length = 0; string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 512) { string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; string = JS_realloc(cx, string, length*sizeof(char)); return JS_NewString(cx, string, strlen(string)); } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); }
meh/lulzjs-ncurses
c45b9b296e5efa2acb529d865987b2713d33826c
Fixes and changes.
diff --git a/src/Screen.c b/src/Screen.c index 0d48d65..4cbedc5 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,318 +1,317 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } - ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); - JS_SetPrivate(cx, object, data); - jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); option = JSVAL_FALSE; } else { echo(); option = JSVAL_TRUE; } JS_SetProperty(cx, object, "echo", &option); // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { - case Raw : raw(); break; - case CBreak: cbreak(); break; - default : option = INT_TO_JSVAL(Normal); break; + case 2: raw(); break; + case 3: cbreak(); break; + default: option = INT_TO_JSVAL(1); break; } JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); option = JSVAL_TRUE; } else { option = JSVAL_FALSE; } JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); jsint cursor = JS_ParseInt(cx, option, 0); curs_set(cursor); option = INT_TO_JSVAL(cursor); JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { - ScreenInformation* data = JS_GetPrivate(cx, object); - - if (data) { - switch (data->buffering) { - case Raw : noraw(); break; - case CBreak: nocbreak(); break; - } + jsval jsScreen, jsBuffering, jsKeypad, jsEcho; + JS_GetProperty(cx, object, "ncurses", &jsScreen); + JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "Screen", &jsScreen); - if (data->keypad) { - keypad(stdscr, FALSE); - } + JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "buffering", &jsBuffering); + JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "keypad", &jsBuffering); + JS_GetProperty(cx, JSVAL_TO_OBJECT(jsScreen), "echo", &jsBuffering); - if (!data->echo) { - echo(); - } + switch (JSVAL_TO_INT(jsBuffering)) { + case 2: noraw(); break; + case 3: nocbreak(); break; + } - curs_set(1); - endwin(); + if (JSVAL_TO_BOOLEAN(jsKeypad)) { + keypad(stdscr, FALSE); + } - JS_free(cx, data); + if (!JSVAL_TO_BOOLEAN(jsEcho)) { + echo(); } + + curs_set(1); + endwin(); } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index b0207e2..9b76f92 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,51 +1,49 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" #include <signal.h> extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; -#include "Screen_private.h" - extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Screen_private.h b/src/Screen_private.h deleted file mode 100644 index 09aa136..0000000 --- a/src/Screen_private.h +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** -* This file is part of lulzJS-ncurses * -* Copyleft meh. * -* * -* lulzJS-ncurses is free software: you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation, either version 3 of the License, or * -* (at your option) any later version. * -* * -* lulzJS-ncurses is distributed in the hope that it will be useful. * -* but WITHOUT ANY WARRANTY; without even the implied warranty o. * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU General Public License * -* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * -****************************************************************************/ - -#ifndef _LULZJS_NCURSES_SCREEN_PRIVATE -#define _LULZJS_NCURSES_SCREEN_PRIVATE - -typedef enum { - Normal, - Raw, - CBreak -} Buffering; - -typedef struct { - JSBool echo; - Buffering buffering; - JSBool keypad; -} ScreenInformation; - -#endif diff --git a/src/ncurses.c b/src/ncurses.c index 267ca9b..fe09117 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,317 +1,317 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); - property = INT_TO_JSVAL(Normal); + property = INT_TO_JSVAL(1); JS_SetProperty(cx, Buffering, "Normal", &property); - property = INT_TO_JSVAL(Raw); + property = INT_TO_JSVAL(2); JS_SetProperty(cx, Buffering, "Raw", &property); - property = INT_TO_JSVAL(CBreak); + property = INT_TO_JSVAL(3); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); JS_SetProperty(cx, Keys, "EndOfScreen", &property); property = INT_TO_JSVAL(KEY_EOL); JS_SetProperty(cx, Keys, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SF); JS_SetProperty(cx, Keys, "ScrollForward", &property); property = INT_TO_JSVAL(KEY_SR); JS_SetProperty(cx, Keys, "ScrollBackward", &property); property = INT_TO_JSVAL(KEY_NPAGE); JS_SetProperty(cx, Keys, "NextPage", &property); property = INT_TO_JSVAL(KEY_PPAGE); JS_SetProperty(cx, Keys, "PreviousPage", &property); property = INT_TO_JSVAL(KEY_STAB); JS_SetProperty(cx, Keys, "SetTab", &property); property = INT_TO_JSVAL(KEY_CTAB); JS_SetProperty(cx, Keys, "ClearTab", &property); property = INT_TO_JSVAL(KEY_CATAB); JS_SetProperty(cx, Keys, "ClearAllTabs", &property); property = INT_TO_JSVAL(KEY_ENTER); JS_SetProperty(cx, Keys, "Enter", &property); property = INT_TO_JSVAL(KEY_SRESET); JS_SetProperty(cx, Keys, "SoftReset", &property); property = INT_TO_JSVAL(KEY_RESET); JS_SetProperty(cx, Keys, "Reset", &property); property = INT_TO_JSVAL(KEY_PRINT); JS_SetProperty(cx, Keys, "Print", &property); property = INT_TO_JSVAL(KEY_LL); JS_SetProperty(cx, Keys, "Bottom", &property); property = INT_TO_JSVAL(KEY_A1); JS_SetProperty(cx, Keys, "UpperLeft", &property); property = INT_TO_JSVAL(KEY_A3); JS_SetProperty(cx, Keys, "UpperRight", &property); property = INT_TO_JSVAL(KEY_B2); JS_SetProperty(cx, Keys, "Center", &property); property = INT_TO_JSVAL(KEY_C1); JS_SetProperty(cx, Keys, "LowerLeft", &property); property = INT_TO_JSVAL(KEY_C3); JS_SetProperty(cx, Keys, "LowerRight", &property); property = INT_TO_JSVAL(KEY_BTAB); JS_SetProperty(cx, Keys, "BackTab", &property); property = INT_TO_JSVAL(KEY_BEG); JS_SetProperty(cx, Keys, "Beginning", &property); property = INT_TO_JSVAL(KEY_CANCEL); JS_SetProperty(cx, Keys, "Cancel", &property); property = INT_TO_JSVAL(KEY_CLOSE); JS_SetProperty(cx, Keys, "Close", &property); property = INT_TO_JSVAL(KEY_COMMAND); JS_SetProperty(cx, Keys, "Command", &property); property = INT_TO_JSVAL(KEY_COPY); JS_SetProperty(cx, Keys, "Copy", &property); property = INT_TO_JSVAL(KEY_CREATE); JS_SetProperty(cx, Keys, "Create", &property); property = INT_TO_JSVAL(KEY_END); JS_SetProperty(cx, Keys, "End", &property); property = INT_TO_JSVAL(KEY_EXIT); JS_SetProperty(cx, Keys, "Exit", &property); property = INT_TO_JSVAL(KEY_FIND); JS_SetProperty(cx, Keys, "Find", &property); property = INT_TO_JSVAL(KEY_HELP); JS_SetProperty(cx, Keys, "Help", &property); property = INT_TO_JSVAL(KEY_MARK); JS_SetProperty(cx, Keys, "Mark", &property); property = INT_TO_JSVAL(KEY_MESSAGE); JS_SetProperty(cx, Keys, "Message", &property); property = INT_TO_JSVAL(KEY_MOUSE); JS_SetProperty(cx, Keys, "Mouse", &property); property = INT_TO_JSVAL(KEY_MOVE); JS_SetProperty(cx, Keys, "Move", &property); property = INT_TO_JSVAL(KEY_NEXT); JS_SetProperty(cx, Keys, "Next", &property); property = INT_TO_JSVAL(KEY_OPEN); JS_SetProperty(cx, Keys, "Open", &property); property = INT_TO_JSVAL(KEY_OPTIONS); JS_SetProperty(cx, Keys, "Options", &property); property = INT_TO_JSVAL(KEY_PREVIOUS); JS_SetProperty(cx, Keys, "Previous", &property); property = INT_TO_JSVAL(KEY_REDO); JS_SetProperty(cx, Keys, "Redo", &property); property = INT_TO_JSVAL(KEY_REFERENCE); JS_SetProperty(cx, Keys, "Reference", &property); property = INT_TO_JSVAL(KEY_REFRESH); JS_SetProperty(cx, Keys, "Refresh", &property); property = INT_TO_JSVAL(KEY_REPLACE); JS_SetProperty(cx, Keys, "Replace", &property); property = INT_TO_JSVAL(KEY_RESIZE); JS_SetProperty(cx, Keys, "Resize", &property); property = INT_TO_JSVAL(KEY_RESTART); JS_SetProperty(cx, Keys, "Restart", &property); property = INT_TO_JSVAL(KEY_RESUME); JS_SetProperty(cx, Keys, "Resume", &property); property = INT_TO_JSVAL(KEY_SAVE); JS_SetProperty(cx, Keys, "Save", &property); property = INT_TO_JSVAL(KEY_SELECT); JS_SetProperty(cx, Keys, "Select", &property); property = INT_TO_JSVAL(KEY_SUSPEND); JS_SetProperty(cx, Keys, "Suspend", &property); property = INT_TO_JSVAL(KEY_UNDO); JS_SetProperty(cx, Keys, "Undo", &property); JSObject* Shifted = JS_NewObject(cx, NULL, NULL, NULL); jsval jsShifted = OBJECT_TO_JSVAL(Shifted); JS_SetProperty(cx, Keys, "Shifted", &jsShifted); property = INT_TO_JSVAL(KEY_SBEG); JS_SetProperty(cx, Shifted, "Beginning", &property); property = INT_TO_JSVAL(KEY_SCANCEL); JS_SetProperty(cx, Shifted, "Cancel", &property); property = INT_TO_JSVAL(KEY_SCOMMAND); JS_SetProperty(cx, Shifted, "Command", &property); property = INT_TO_JSVAL(KEY_SCOPY); JS_SetProperty(cx, Shifted, "Copy", &property); property = INT_TO_JSVAL(KEY_SCREATE); JS_SetProperty(cx, Shifted, "Create", &property); property = INT_TO_JSVAL(KEY_SDC); JS_SetProperty(cx, Shifted, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_SDL); JS_SetProperty(cx, Shifted, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_SEND); JS_SetProperty(cx, Shifted, "End", &property); property = INT_TO_JSVAL(KEY_SEOL); JS_SetProperty(cx, Shifted, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SEXIT); JS_SetProperty(cx, Shifted, "Exit", &property); property = INT_TO_JSVAL(KEY_SFIND); JS_SetProperty(cx, Shifted, "Find", &property); property = INT_TO_JSVAL(KEY_SHELP); JS_SetProperty(cx, Shifted, "Help", &property); property = INT_TO_JSVAL(KEY_SHOME); JS_SetProperty(cx, Shifted, "Home", &property); property = INT_TO_JSVAL(KEY_SIC); JS_SetProperty(cx, Shifted, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_SLEFT); JS_SetProperty(cx, Shifted, "Left", &property); property = INT_TO_JSVAL(KEY_SMESSAGE); JS_SetProperty(cx, Shifted, "Message", &property); property = INT_TO_JSVAL(KEY_SMOVE); JS_SetProperty(cx, Shifted, "Move", &property); property = INT_TO_JSVAL(KEY_SNEXT); JS_SetProperty(cx, Shifted, "Next", &property); property = INT_TO_JSVAL(KEY_SOPTIONS); JS_SetProperty(cx, Shifted, "Options", &property); property = INT_TO_JSVAL(KEY_SPREVIOUS); JS_SetProperty(cx, Shifted, "Previous", &property); property = INT_TO_JSVAL(KEY_SPRINT); JS_SetProperty(cx, Shifted, "Print", &property); property = INT_TO_JSVAL(KEY_SREDO); JS_SetProperty(cx, Shifted, "Redo", &property); property = INT_TO_JSVAL(KEY_SREPLACE); JS_SetProperty(cx, Shifted, "Replace", &property); property = INT_TO_JSVAL(KEY_SRIGHT); JS_SetProperty(cx, Shifted, "Right", &property); property = INT_TO_JSVAL(KEY_SRSUME); JS_SetProperty(cx, Shifted, "Resume", &property); property = INT_TO_JSVAL(KEY_SSAVE); JS_SetProperty(cx, Shifted, "Save", &property); property = INT_TO_JSVAL(KEY_SSUSPEND); JS_SetProperty(cx, Shifted, "Suspend", &property); property = INT_TO_JSVAL(KEY_SUNDO); JS_SetProperty(cx, Shifted, "Undo", &property); return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); if (n < 0 || n > 63) { JS_ReportError(cx, "Out of range."); return JS_FALSE; } *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; } diff --git a/src/ncurses.h b/src/ncurses.h index 977af82..5e3a1a2 100644 --- a/src/ncurses.h +++ b/src/ncurses.h @@ -1,40 +1,39 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_H #define _LULZJS_NCURSES_H #include "common.h" -#include "Screen.h" extern JSBool exec (JSContext* cx); extern JSBool ncurses_initialize (JSContext* cx); static JSClass ncurses_class = { "ncurses", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; extern JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec ncurses_methods[] = { {NULL} }; #endif
meh/lulzjs-ncurses
d5d69569962c7bf39cec197069b032eaa587e457
Fixes.
diff --git a/src/Screen.c b/src/Screen.c index 4e979ce..0d48d65 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,316 +1,318 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); option = JSVAL_FALSE; } else { echo(); option = JSVAL_TRUE; } JS_SetProperty(cx, object, "echo", &option); // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); break; case CBreak: cbreak(); break; default : option = INT_TO_JSVAL(Normal); break; } JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); option = JSVAL_TRUE; } else { option = JSVAL_FALSE; } JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); - curs_set(JS_ParseInt(cx, option, 0)); + jsint cursor = JS_ParseInt(cx, option, 0); + curs_set(cursor); + option = INT_TO_JSVAL(cursor); JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Window.c b/src/Window.c index 4f81b64..209c507 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,525 +1,536 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updatePosition (JSContext* cx, JSObject* object); void __Window_updateSize (JSContext* cx, JSObject* object); -void __Window_echofy (jsval echo, JSBool echoing, JSBool start); +void __Window_echofy (jsval echo, JSBool echoing, jsint cursor, JSBool start); JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); - jsval property; JS_GetProperty(cx, Screen, "echo", &property); + jsval property; + JS_GetProperty(cx, Screen, "echo", &property); JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); + JS_GetProperty(cx, Screen, "cursor", &property); + jsint windowCursor = JSVAL_TO_INT(property); if (argc == 0) { echo(); + curs_set(1); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); if (!windowEchoing) { noecho(); } + curs_set(windowCursor); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { - __Window_echofy(jsEcho, windowEchoing, JS_TRUE); + __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); - __Window_echofy(jsEcho, windowEchoing, JS_FALSE); + __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } else { - __Window_echofy(jsEcho, windowEchoing, JS_TRUE); + __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_TRUE); *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); - __Window_echofy(jsEcho, windowEchoing, JS_FALSE); + __Window_echofy(jsEcho, windowEchoing, windowCursor, JS_FALSE); } } return JS_TRUE; } void -__Window_echofy (jsval jsEcho, JSBool echoing, JSBool start) +__Window_echofy (jsval jsEcho, JSBool echoing, jsint cursor, JSBool start) { if (start) { if (JSVAL_IS_BOOLEAN(jsEcho)) { if (JSVAL_TO_BOOLEAN(jsEcho)) { + curs_set(1); echo(); } else { noecho(); } } else { + curs_set(1); echo(); } } else { - if (!echoing) { + if (echoing) { + echo(); + } + else { noecho(); } + curs_set(cursor); } } JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) { char* string = JS_malloc(cx, 512*sizeof(char)); size_t length = 0; string[0] = (moveFirst ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) : wgetch(win)); while (string[(++length)-1] != '\n') { if ((length+1) % 512) { string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); } string[length] = (char) wgetch(win); } string[length-1] = '\0'; string = JS_realloc(cx, string, length*sizeof(char)); return JS_NewString(cx, string, strlen(string)); } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); }
meh/lulzjs-ncurses
1e0917bffe61d9fdf1d47b3b8fa40bc1483f2c88
Window#getString near working.
diff --git a/src/Panel.js b/src/Panel.js index 682fbf7..92dffe0 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,55 +1,62 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { refresh: function () { this.__window.refresh(); }, resize: function (obj) { this.__window.resize(obj); ncurses.Panel.update(); ncurses.Screen.update(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); + }, + + getString: function (options) { + return (options + ? this.__window.getString(options) + : this.__window.getString()); } + }); Object.addGetters(ncurses.Panel, { Size: function () { return this.__window.Size; }, Position: function () { return this.__window.Position; } }); diff --git a/src/Screen.c b/src/Screen.c index 4c6c47f..4e979ce 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,312 +1,316 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" +void __Screen_updateSize (JSContext* cx, JSObject* object); +void __Screen_updateACS (JSContext* cx); + static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { - JS_ReportError(cx, "You can have only one Screen per program.") { + JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); - data->echo = JS_FALSE; + option = JSVAL_FALSE; } else { echo(); - data->echo = JS_TRUE; + option = JSVAL_TRUE; } + JS_SetProperty(cx, object, "echo", &option); // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); break; case CBreak: cbreak(); break; default : option = INT_TO_JSVAL(Normal); break; } JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); option = JSVAL_TRUE; } else { option = JSVAL_FALSE; } JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index ef34b2c..b0207e2 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,56 +1,51 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" #include <signal.h> -void __Screen_resize (int signum); - extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -void __Screen_updateSize (JSContext* cx, JSObject* object); -void __Screen_updateACS (JSContext* cx); - static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Screen.js b/src/Screen.js index a7c6902..a28aed0 100644 --- a/src/Screen.js +++ b/src/Screen.js @@ -1,39 +1,45 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Screen, { refresh: function () { this.__window.refresh(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); + }, + + getString: function (options) { + return (options + ? this.__window.getString(options) + : this.__window.getString()); } }); diff --git a/src/Window.c b/src/Window.c index d94592f..4f81b64 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,458 +1,525 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" +void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); +void __Window_updatePosition (JSContext* cx, JSObject* object); +void __Window_updateSize (JSContext* cx, JSObject* object); +void __Window_echofy (jsval echo, JSBool echoing, JSBool start); +JSString* __Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y); + JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; - WINDOW* win = JS_GetPrivate(cx, object) + WINDOW* win = JS_GetPrivate(cx, object); jsval parent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); JSObject* Screen = JSVAL_TO_OBJECT(parent); + jsval property; JS_GetProperty(cx, Screen, "echo", &property); + JSBool windowEchoing = JSVAL_TO_BOOLEAN(property); + if (argc == 0) { - *rval = INT_TO_JSVAL(wgetch(win)); + echo(); + + *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); + + if (!windowEchoing) { + noecho(); + } } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } - jsval x, y; + jsval x, y, jsEcho; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); + JS_GetProperty(cx, options, "echo", &jsEcho); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { - JS_ReportError(cx, "An option is missing or isn't an int."); - return JS_FALSE; + __Window_echofy(jsEcho, windowEchoing, JS_TRUE); + *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_FALSE, 0, 0)); + __Window_echofy(jsEcho, windowEchoing, JS_FALSE); + } + else { + __Window_echofy(jsEcho, windowEchoing, JS_TRUE); + *rval = STRING_TO_JSVAL(__Window_readLine(cx, win, JS_TRUE, x, y)); + __Window_echofy(jsEcho, windowEchoing, JS_FALSE); } - - *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } +void +__Window_echofy (jsval jsEcho, JSBool echoing, JSBool start) +{ + if (start) { + if (JSVAL_IS_BOOLEAN(jsEcho)) { + if (JSVAL_TO_BOOLEAN(jsEcho)) { + echo(); + } + else { + noecho(); + } + } + else { + echo(); + } + } + else { + if (!echoing) { + noecho(); + } + } +} + +JSString* +__Window_readLine (JSContext* cx, WINDOW* win, JSBool moveFirst, jsval x, jsval y) +{ + char* string = JS_malloc(cx, 512*sizeof(char)); + size_t length = 0; + + string[0] = (moveFirst + ? mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x)) + : wgetch(win)); + + while (string[(++length)-1] != '\n') { + if ((length+1) % 512) { + string = JS_realloc(cx, string, (length+512+1)*sizeof(char)); + } + + string[length] = (char) wgetch(win); + } + + string[length-1] = '\0'; + string = JS_realloc(cx, string, length*sizeof(char)); + + return JS_NewString(cx, string, strlen(string)); +} + void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/Window.h b/src/Window.h index 3690edc..22cbff1 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,66 +1,62 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" extern JSBool exec (JSContext* cx); extern JSBool Window_initialize (JSContext* cx); extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; #include "Window_private.h" extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); -void __Window_updateSize (JSContext* cx, JSObject* object); -void __Window_updatePosition (JSContext* cx, JSObject* object); - static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, {"resize", Window_resize, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, {"getString", Window_getString, 0, 0, 0}, {NULL} }; #endif
meh/lulzjs-ncurses
b901294be6fb72610c00ce36fb94a223541edcf4
I love the bot.
diff --git a/src/Screen.c b/src/Screen.c index 16224fe..4c6c47f 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,309 +1,312 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { - JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); + JS_ReportError(cx, "You can have only one Screen per program.") { return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); JS_SetPrivate(cx, Window, stdscr); JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { - case Raw : raw(); data->buffering = Raw; break; - case CBreak: cbreak(); data->buffering = CBreak; break; - default : data->buffering = Normal; break; + case Raw : raw(); break; + case CBreak: cbreak(); break; + default : option = INT_TO_JSVAL(Normal); break; } + JS_SetProperty(cx, object, "buffering", &option); // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); - data->keypad = JS_TRUE; + option = JSVAL_TRUE; } else { - data->keypad = JS_FALSE; + option = JSVAL_FALSE; } + JS_SetProperty(cx, object, "keypad", &option); // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); + JS_SetProperty(cx, object, "cursor", &option); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Window.c b/src/Window.c index 8057588..d94592f 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,420 +1,458 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } +JSBool +Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* options; + + WINDOW* win = JS_GetPrivate(cx, object) + + jsval parent; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &parent); + JS_GetProperty(cx, JSVAL_TO_OBJECT(parent), "Screen", &parent); + JSObject* Screen = JSVAL_TO_OBJECT(parent); + + if (argc == 0) { + *rval = INT_TO_JSVAL(wgetch(win)); + } + else { + JS_ValueToObject(cx, argv[0], &options); + + if (!options) { + JS_ReportError(cx, "Options isn't a valid object."); + return JS_FALSE; + } + + jsval x, y; + JS_GetProperty(cx, options, "x", &x); + JS_GetProperty(cx, options, "y", &y); + + if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { + JS_ReportError(cx, "An option is missing or isn't an int."); + return JS_FALSE; + } + + *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); + } + + return JS_TRUE; +} + void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/Window.h b/src/Window.h index a507e8d..3690edc 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,64 +1,66 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" extern JSBool exec (JSContext* cx); extern JSBool Window_initialize (JSContext* cx); extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; #include "Window_private.h" extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Window_getString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_updatePosition (JSContext* cx, JSObject* object); static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, {"resize", Window_resize, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, + {"getString", Window_getString, 0, 0, 0}, {NULL} }; #endif
meh/lulzjs-ncurses
b27907f4789f6012efb4cffa3826ddfe66a86681
Added Panel#move and fixed some minor bugs.
diff --git a/src/Panel.c b/src/Panel.c index 9ac824e..b49f0b6 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,199 +1,237 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } +JSBool +Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* options; + + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + JS_ValueToObject(cx, argv[0], &options); + jsval x; JS_GetProperty(cx, options, "x", &x); + jsval y; JS_GetProperty(cx, options, "y", &y); + + if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { + JS_ReportError(cx, "An option isn't an int."); + return JS_FALSE; + } + + if (!JSVAL_IS_INT(x)) { + JS_GetProperty(cx, object, "Position", &x); + JS_GetProperty(cx, JSVAL_TO_OBJECT(x), "X", &x); + } + + if (!JSVAL_IS_INT(y)) { + JS_GetProperty(cx, object, "Position", &y); + JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "Y", &y); + } + + PANEL* panel = JS_GetPrivate(cx, object); + move_panel(panel, JSVAL_TO_INT(y), JSVAL_TO_INT(x)); + refresh(); + update_panels(); + doupdate(); + + return JS_TRUE; +} + JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index c65df20..cd678d6 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,65 +1,67 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" JSObject** panels = NULL; int panelsSize = 0; extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Panel_move (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, + {"move", Panel_move, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.c b/src/Window.c index d960996..8057588 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,420 +1,420 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WINDOW* win; switch (argc) { case 0: case 1: { win = newwin( JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); if (border) { box(win, 0, 0); JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win && win != stdscr) { delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); - JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Height", &height); + JS_GetProperty(cx, JSVAL_TO_OBJECT(height), "Height", &height); } WINDOW* win = JS_GetPrivate(cx, object); jsval border; JS_GetProperty(cx, object, "border", &border); if (JSVAL_TO_BOOLEAN(border)) { - wborder(win, ' ', ' ', ' ',' ',' ',' ',' ',' '); + wborder(win,' ',' ',' ',' ',' ',' ',' ',' '); wrefresh(win); wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); box(win, 0, 0); } else { wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval property; JS_GetProperty(cx, object, "Size", &property); JSObject* Size = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, object, "border", &property); JSBool border = JSVAL_TO_BOOLEAN(property); property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/test/panel.js b/test/panel.js index 92cab11..9fdc2eb 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,16 +1,18 @@ #! /usr/bin/env ljs require("ncurses"); var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); var panels = [] panels.push(new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true})); panels.push(new ncurses.Panel({x: 4, y: 5, width: 30, height: 10, border: true})); panels[0].printString("Width: {Width}, Height: {Height} ".format(panels[0].Size), {x: 1, y: 1}); panels[1].printString("PENIS", {x: 10, y: 4}); panels[0].toTop(); panels[0].getChar(); panels[0].below.getChar(); panels[0].resize({height: 1}); panels[0].printString("Width: {Width}, Height: {Height} ".format(panels[0].Size), {x: 1, y: 1}); panels[0].getChar(); +panels[0].move({x: 7, y: 20}); +panels[0].getChar();
meh/lulzjs-ncurses
ea2a7033e472e42dc344bdecbc3b48ab86fbd212
Fixes and changes.
diff --git a/src/Panel.c b/src/Panel.c index a9b3d27..9ac824e 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,199 +1,199 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); - PANEL* panel = new_panel(((WindowInformation*)JS_GetPrivate(cx, Window))->win); + PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Screen.c b/src/Screen.c index 0aade35..16224fe 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,312 +1,309 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); - - WindowInformation* windowData = JS_malloc(cx, sizeof(WindowInformation)); - windowData->win = stdscr; - windowData->border = JS_FALSE; - JS_SetPrivate(cx, Window, windowData); + JS_SetPrivate(cx, Window, stdscr); + JS_DefineProperty(cx, Window, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { doupdate(); return JS_TRUE; } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Window.c b/src/Window.c index c587790..d960996 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,417 +1,420 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); + jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); + JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); + if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } - WindowInformation* data = JS_malloc(cx, sizeof(WindowInformation)); + WINDOW* win; switch (argc) { case 0: case 1: { - data->win = newwin( - JSVAL_TO_INT(height), JSVAL_TO_INT(width), + win = newwin( + JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { - WINDOW* parentWin = ((WindowInformation*)JS_GetPrivate(cx, parent))->win; - data->win = subwin(parentWin, - JSVAL_TO_INT(height), JSVAL_TO_INT(width), + WINDOW* parentWin = JS_GetPrivate(cx, parent); + win = subwin(parentWin, + JSVAL_TO_INT(border ? height+3 : height), JSVAL_TO_INT(border ? width+3 : width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } - JS_SetPrivate(cx, object, data); + JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); - jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); - JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (border) { - box(data->win, 0, 0); - data->border = JS_TRUE; + box(win, 0, 0); + JS_DefineProperty(cx, object, "border", JSVAL_TRUE, NULL, NULL, JSPROP_READONLY); } else { - data->border = JS_FALSE; + JS_DefineProperty(cx, object, "border", JSVAL_FALSE, NULL, NULL, JSPROP_READONLY); } - wrefresh(data->win); + wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { - WindowInformation* data = JS_GetPrivate(cx, object); + WINDOW* win = JS_GetPrivate(cx, object); - if (data) { - if (data->win && data->win != stdscr) { - delwin(data->win); - } + if (win && win != stdscr) { + delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } if (!JSVAL_IS_INT(width)) { JS_GetProperty(cx, object, "Size", &width); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); } if (!JSVAL_IS_INT(height)) { JS_GetProperty(cx, object, "Size", &height); JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Height", &height); } - WindowInformation* data = JS_GetPrivate(cx, object); - if (data->border) { - wborder(data->win, ' ', ' ', ' ',' ',' ',' ',' ',' '); - wrefresh(data->win); - wresize(data->win, height, width); - box(data->win, 0, 0); + WINDOW* win = JS_GetPrivate(cx, object); + + jsval border; JS_GetProperty(cx, object, "border", &border); + if (JSVAL_TO_BOOLEAN(border)) { + wborder(win, ' ', ' ', ' ',' ',' ',' ',' ',' '); + wrefresh(win); + wresize(win, JSVAL_TO_INT(height+3), JSVAL_TO_INT(width+3)); + box(win, 0, 0); } else { - wresize(data->win, height+2, width+2); + wresize(win, JSVAL_TO_INT(height), JSVAL_TO_INT(width)); } - wrefresh(data->win); + wrefresh(win); __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); - jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); - JSObject* Size = JSVAL_TO_OBJECT(jsSize); - jsval property; - property = INT_TO_JSVAL(height); + JS_GetProperty(cx, object, "Size", &property); + JSObject* Size = JSVAL_TO_OBJECT(property); + JS_GetProperty(cx, object, "border", &property); + JSBool border = JSVAL_TO_BOOLEAN(property); + + property = INT_TO_JSVAL(border ? height-2 : height); JS_SetProperty(cx, Size, "Height", &property); - property = INT_TO_JSVAL(width); + property = INT_TO_JSVAL(border ? width-2 : width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; - WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; + WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); }
meh/lulzjs-ncurses
7dfd4bd32bb3bbd50753c37ea7afbcd37ebd54d7
Little addition to the test :P
diff --git a/test/panel.js b/test/panel.js index 4e0ddf4..92cab11 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,15 +1,16 @@ #! /usr/bin/env ljs require("ncurses"); var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); var panels = [] panels.push(new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true})); panels.push(new ncurses.Panel({x: 4, y: 5, width: 30, height: 10, border: true})); -panels[0].printString("Width: {Width}, Height: {Height}".format(panels[0].Size), {x: 1, y: 1}); +panels[0].printString("Width: {Width}, Height: {Height} ".format(panels[0].Size), {x: 1, y: 1}); panels[1].printString("PENIS", {x: 10, y: 4}); panels[0].toTop(); panels[0].getChar(); panels[0].below.getChar(); panels[0].resize({height: 1}); +panels[0].printString("Width: {Width}, Height: {Height} ".format(panels[0].Size), {x: 1, y: 1}); panels[0].getChar();
meh/lulzjs-ncurses
fbea1e1295305248da2526a2ae247b7299455b20
Improvements.
diff --git a/src/Panel.c b/src/Panel.c index ca8df50..a9b3d27 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,200 +1,199 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel(((WindowInformation*)JS_GetPrivate(cx, Window))->win); JS_SetPrivate(cx, object, panel); update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); - doupdate(); return JS_TRUE; } diff --git a/src/Panel.js b/src/Panel.js index 14b59d0..682fbf7 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,54 +1,55 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { refresh: function () { this.__window.refresh(); }, resize: function (obj) { this.__window.resize(obj); ncurses.Panel.update(); + ncurses.Screen.update(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); Object.addGetters(ncurses.Panel, { Size: function () { return this.__window.Size; }, Position: function () { return this.__window.Position; } }); diff --git a/src/Screen.c b/src/Screen.c index 120daa8..0aade35 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,305 +1,312 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_DefineObject( cx, parent, Screen_class.name, &Screen_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, Screen_methods); // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); WindowInformation* windowData = JS_malloc(cx, sizeof(WindowInformation)); windowData->win = stdscr; windowData->border = JS_FALSE; JS_SetPrivate(cx, Window, windowData); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); *rval = OBJECT_TO_JSVAL(object); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } +JSBool +Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + doupdate(); + return JS_TRUE; +} + JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index f36f781..ef34b2c 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,54 +1,56 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" #include <signal.h> void __Screen_resize (int signum); extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Screen_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSFunctionSpec Screen_methods[] = { {"init", Screen_init, 0, 0, 0}, + {"update", Screen_update, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif
meh/lulzjs-ncurses
c29700b7df9ce1f0b35aa265e6b72c661b0bb8db
Changes in Screen etc.
diff --git a/src/Panel.js b/src/Panel.js index 5af48d4..9e5b96b 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,53 +1,55 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { refresh: function () { this.__window.refresh(); }, resize: function (obj) { this.__window.resize(obj); + ncurses.Screen.refresh(); + ncurses.Panel.update(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); Object.addGetters(ncurses.Panel, { Size: function () { - this.__window.Size; + return this.__window.Size; }, Position: function () { - this.__window.Position; + return this.__window.Position; } }); diff --git a/src/Screen.c b/src/Screen.c index 89e2642..120daa8 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,301 +1,305 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); - JSObject* object = JS_InitClass( - cx, parent, NULL, &Screen_class, - Screen_constructor, 1, NULL, Screen_methods, NULL, NULL + JSObject* object = JS_DefineObject( + cx, parent, + Screen_class.name, &Screen_class, NULL, + JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); - if (object) { + JS_DefineFunctions(cx, object, Screen_methods); + // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool -Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); WindowInformation* windowData = JS_malloc(cx, sizeof(WindowInformation)); windowData->win = stdscr; windowData->border = JS_FALSE; JS_SetPrivate(cx, Window, windowData); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); + *rval = OBJECT_TO_JSVAL(object); + return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Screen_updateACS (JSContext* cx) { jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); property = INT_TO_JSVAL(ACS_BLOCK); JS_SetProperty(cx, AlternativeChars, "Block", &property); property = INT_TO_JSVAL(ACS_BOARD); JS_SetProperty(cx, AlternativeChars, "Board", &property); property = INT_TO_JSVAL(ACS_BTEE); JS_SetProperty(cx, AlternativeChars, "BottomT", &property); property = INT_TO_JSVAL(ACS_BULLET); JS_SetProperty(cx, AlternativeChars, "Bullet", &property); property = INT_TO_JSVAL(ACS_CKBOARD); JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); property = INT_TO_JSVAL(ACS_DARROW); JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); property = INT_TO_JSVAL(ACS_DEGREE); JS_SetProperty(cx, AlternativeChars, "Degree", &property); property = INT_TO_JSVAL(ACS_DIAMOND); JS_SetProperty(cx, AlternativeChars, "Diamond", &property); property = INT_TO_JSVAL(ACS_GEQUAL); JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); property = INT_TO_JSVAL(ACS_HLINE); JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); property = INT_TO_JSVAL(ACS_LANTERN); JS_SetProperty(cx, AlternativeChars, "Lantern", &property); property = INT_TO_JSVAL(ACS_LARROW); JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); property = INT_TO_JSVAL(ACS_LEQUAL); JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); property = INT_TO_JSVAL(ACS_LLCORNER); JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); property = INT_TO_JSVAL(ACS_LRCORNER); JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); property = INT_TO_JSVAL(ACS_LTEE); JS_SetProperty(cx, AlternativeChars, "LeftT", &property); property = INT_TO_JSVAL(ACS_NEQUAL); JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); property = INT_TO_JSVAL(ACS_PI); JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); property = INT_TO_JSVAL(ACS_PLMINUS); JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); property = INT_TO_JSVAL(ACS_PLUS); JS_SetProperty(cx, AlternativeChars, "Plus", &property); property = INT_TO_JSVAL(ACS_RARROW); JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); property = INT_TO_JSVAL(ACS_RTEE); JS_SetProperty(cx, AlternativeChars, "RightT", &property); property = INT_TO_JSVAL(ACS_S1); JS_SetProperty(cx, AlternativeChars, "Scan1", &property); property = INT_TO_JSVAL(ACS_S3); JS_SetProperty(cx, AlternativeChars, "Scan3", &property); property = INT_TO_JSVAL(ACS_S7); JS_SetProperty(cx, AlternativeChars, "Scan7", &property); property = INT_TO_JSVAL(ACS_S9); JS_SetProperty(cx, AlternativeChars, "Scan9", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); property = INT_TO_JSVAL(ACS_STERLING); JS_SetProperty(cx, AlternativeChars, "Pound", &property); property = INT_TO_JSVAL(ACS_TTEE); JS_SetProperty(cx, AlternativeChars, "TopT", &property); property = INT_TO_JSVAL(ACS_UARROW); JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); property = INT_TO_JSVAL(ACS_ULCORNER); JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); property = INT_TO_JSVAL(ACS_URCORNER); JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); property = INT_TO_JSVAL(ACS_VLINE); JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index 64661da..f36f781 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,52 +1,54 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include "Window_private.h" #include <signal.h> void __Screen_resize (int signum); extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" +extern JSBool Screen_init (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void __Screen_updateSize (JSContext* cx, JSObject* object); void __Screen_updateACS (JSContext* cx); static JSFunctionSpec Screen_methods[] = { + {"init", Screen_init, 0, 0, 0}, {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Screen.js b/src/Screen.js index c43e2ae..a7c6902 100644 --- a/src/Screen.js +++ b/src/Screen.js @@ -1,39 +1,39 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ -Object.extend(ncurses.Screen.prototype, { +Object.extend(ncurses.Screen, { refresh: function () { this.__window.refresh(); }, printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); diff --git a/src/Window.c b/src/Window.c index c9570ee..6282ed2 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,403 +1,417 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { width = INT_TO_JSVAL(0); height = INT_TO_JSVAL(0); x = INT_TO_JSVAL(0); y = INT_TO_JSVAL(0); } WindowInformation* data = JS_malloc(cx, sizeof(WindowInformation)); switch (argc) { case 0: case 1: { data->win = newwin( JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; case 2: { WINDOW* parentWin = ((WindowInformation*)JS_GetPrivate(cx, parent))->win; data->win = subwin(parentWin, JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } break; } JS_SetPrivate(cx, object, data); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (border) { box(data->win, 0, 0); data->border = JS_TRUE; } else { data->border = JS_FALSE; } wrefresh(data->win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WindowInformation* data = JS_GetPrivate(cx, object); if (data) { if (data->win && data->win != stdscr) { delwin(data->win); } } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } JS_ValueToObject(cx, argv[0], &options); jsval width; JS_GetProperty(cx, options, "width", &width); jsval height; JS_GetProperty(cx, options, "height", &height); if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { JS_ReportError(cx, "An option isn't an int."); return JS_FALSE; } + if (!JSVAL_IS_INT(width)) { + JS_GetProperty(cx, object, "Size", &width); + JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Width", &width); + } + + if (!JSVAL_IS_INT(height)) { + JS_GetProperty(cx, object, "Size", &height); + JS_GetProperty(cx, JSVAL_TO_OBJECT(width), "Height", &height); + } + WindowInformation* data = JS_GetPrivate(cx, object); - wresize(data->win, height, width); + if (data->border) { + wborder(data->win, ' ', ' ', ' ',' ',' ',' ',' ',' '); + wresize(data->win, height, width); box(data->win, 0, 0); } + else { + wresize(data->win, height+2, width+2); + } wrefresh(data->win); - __Window_updateSize(cx, object); return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; getmaxyx(win, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/test/panel.js b/test/panel.js index 5ad6ea4..4e0ddf4 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,17 +1,15 @@ #! /usr/bin/env ljs require("ncurses"); -var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); var panels = [] panels.push(new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true})); panels.push(new ncurses.Panel({x: 4, y: 5, width: 30, height: 10, border: true})); -panels[0].printString(panels[0].Size, {x: 1, y: 1}); +panels[0].printString("Width: {Width}, Height: {Height}".format(panels[0].Size), {x: 1, y: 1}); panels[1].printString("PENIS", {x: 10, y: 4}); panels[0].toTop(); panels[0].getChar(); panels[0].below.getChar(); -panels[0].resize({width: 5, height: 5}); -ncurses.Panel.update(); -screen.refresh(); +panels[0].resize({height: 1}); panels[0].getChar(); diff --git a/test/size.js b/test/size.js index 13d02bb..f93ec22 100755 --- a/test/size.js +++ b/test/size.js @@ -1,13 +1,13 @@ #! /usr/bin/env ljs require("ncurses"); -var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); (screen.onResize = function () { screen.printString("Width", {x: 0, y: 0, fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); screen.printString(" : "+screen.Size.Width+" "); screen.printString("Height", {x: 0, y: 1, fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); screen.printString(": "+screen.Size.Height+" "); })(); while (screen.getChar() != ord('q')); diff --git a/test/test.js b/test/test.js index 4da77bb..1f78fbe 100755 --- a/test/test.js +++ b/test/test.js @@ -1,9 +1,9 @@ #! /usr/bin/env ljs require("ncurses"); -var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); screen.printString("LOL", {fg: ncurses.Colors.Red, at:ncurses.Attributes.Standout}); screen.getChar(); screen.printString("OMG", {x: 10, y: 10, bg: ncurses.Colors.Red}); screen.printChar(screen.getChar(), {x: 35, y: 10}); screen.getChar() diff --git a/test/window.js b/test/window.js index 82aad02..03c7467 100755 --- a/test/window.js +++ b/test/window.js @@ -1,8 +1,8 @@ #! /usr/bin/env ljs require("ncurses"); -var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var screen = ncurses.Screen.init({buffering: ncurses.Buffering.Raw}); var win = new ncurses.Window({x: 2, y: 2, width: 40, height: 10, border: true}); win.printString("X: {X}, Y: {Y}".format(win.Position), {x: 10, y: 4, fg: ncurses.Colors.Blue}); win.printChar(win.getChar(), {x: 2, y: 2}) win.getChar();
meh/lulzjs-ncurses
3844d46698d9f58ac2740e4c85840eb0ec62de37
Fixes and changes.
diff --git a/src/Panel.c b/src/Panel.c index e2cef97..a9b3d27 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,199 +1,199 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" extern JSObject** panels; extern int panelsSize; JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); - PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); + PANEL* panel = new_panel(((WindowInformation*)JS_GetPrivate(cx, Window))->win); JS_SetPrivate(cx, object, panel); - + update_panels(); panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); panels[panelsSize-1] = object; JS_DefineProperty( cx, object, "below", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); JS_DefineProperty( cx, object, "above", JSVAL_NULL, (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), NULL, JSPROP_GETTER|JSPROP_READONLY ); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { // Find the object being finalized and remove it from the list int i; for (i = 0; i < panelsSize; i++) { if (object == panels[i]) { break; } } for (i++; i < panelsSize; i++) { panels[i-1] = panels[i]; } panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* above = panel_above(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == above) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); PANEL* below = panel_below(panel); int i; for (i = 0; i < panelsSize; i++) { PANEL* check = JS_GetPrivate(cx, panels[i]); if (check == below) { *rval = OBJECT_TO_JSVAL(panels[i]); break; } } return JS_TRUE; } JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index 90d95ea..c65df20 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,64 +1,65 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" +#include "Window_private.h" JSObject** panels = NULL; int panelsSize = 0; extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Panel.js b/src/Panel.js index 66ec44f..5af48d4 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,39 +1,53 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { refresh: function () { this.__window.refresh(); }, + resize: function (obj) { + this.__window.resize(obj); + }, + printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); + +Object.addGetters(ncurses.Panel, { + Size: function () { + this.__window.Size; + }, + + Position: function () { + this.__window.Position; + } +}); diff --git a/src/Screen.c b/src/Screen.c index b5b8198..89e2642 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,210 +1,301 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, Screen_constructor, 1, NULL, Screen_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); - __updateACS(cx); + __Screen_updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); - JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); + JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window", &property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); - JS_SetPrivate(cx, Window, stdscr); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); + WindowInformation* windowData = JS_malloc(cx, sizeof(WindowInformation)); + windowData->win = stdscr; + windowData->border = JS_FALSE; + JS_SetPrivate(cx, Window, windowData); + if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } +JSBool +Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + jsint val; + + if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + curs_set(val); + + return JS_TRUE; +} + void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } -JSBool -Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +void +__Screen_updateACS (JSContext* cx) { - jsint val; - - if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { - JS_ReportError(cx, "Not enough parameters."); - return JS_FALSE; - } - - curs_set(val); + jsval property; - return JS_TRUE; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); + JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); + JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); + property = INT_TO_JSVAL(ACS_BLOCK); + JS_SetProperty(cx, AlternativeChars, "Block", &property); + property = INT_TO_JSVAL(ACS_BOARD); + JS_SetProperty(cx, AlternativeChars, "Board", &property); + property = INT_TO_JSVAL(ACS_BTEE); + JS_SetProperty(cx, AlternativeChars, "BottomT", &property); + property = INT_TO_JSVAL(ACS_BULLET); + JS_SetProperty(cx, AlternativeChars, "Bullet", &property); + property = INT_TO_JSVAL(ACS_CKBOARD); + JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); + property = INT_TO_JSVAL(ACS_DARROW); + JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); + property = INT_TO_JSVAL(ACS_DEGREE); + JS_SetProperty(cx, AlternativeChars, "Degree", &property); + property = INT_TO_JSVAL(ACS_DIAMOND); + JS_SetProperty(cx, AlternativeChars, "Diamond", &property); + property = INT_TO_JSVAL(ACS_GEQUAL); + JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); + property = INT_TO_JSVAL(ACS_HLINE); + JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); + property = INT_TO_JSVAL(ACS_LANTERN); + JS_SetProperty(cx, AlternativeChars, "Lantern", &property); + property = INT_TO_JSVAL(ACS_LARROW); + JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); + property = INT_TO_JSVAL(ACS_LEQUAL); + JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); + property = INT_TO_JSVAL(ACS_LLCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); + property = INT_TO_JSVAL(ACS_LRCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); + property = INT_TO_JSVAL(ACS_LTEE); + JS_SetProperty(cx, AlternativeChars, "LeftT", &property); + property = INT_TO_JSVAL(ACS_NEQUAL); + JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); + property = INT_TO_JSVAL(ACS_PI); + JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); + property = INT_TO_JSVAL(ACS_PLMINUS); + JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); + property = INT_TO_JSVAL(ACS_PLUS); + JS_SetProperty(cx, AlternativeChars, "Plus", &property); + property = INT_TO_JSVAL(ACS_RARROW); + JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); + property = INT_TO_JSVAL(ACS_RTEE); + JS_SetProperty(cx, AlternativeChars, "RightT", &property); + property = INT_TO_JSVAL(ACS_S1); + JS_SetProperty(cx, AlternativeChars, "Scan1", &property); + property = INT_TO_JSVAL(ACS_S3); + JS_SetProperty(cx, AlternativeChars, "Scan3", &property); + property = INT_TO_JSVAL(ACS_S7); + JS_SetProperty(cx, AlternativeChars, "Scan7", &property); + property = INT_TO_JSVAL(ACS_S9); + JS_SetProperty(cx, AlternativeChars, "Scan9", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); } diff --git a/src/Screen.h b/src/Screen.h index cd97674..64661da 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,50 +1,52 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" +#include "Window_private.h" #include <signal.h> void __Screen_resize (int signum); extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void __Screen_updateSize (JSContext* cx, JSObject* object); +void __Screen_updateACS (JSContext* cx); static JSFunctionSpec Screen_methods[] = { {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window.c b/src/Window.c index 51e897a..c9570ee 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,312 +1,403 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; - if (argc < 1) { - JS_ReportError(cx, "Not enough parameters."); - return JS_FALSE; - } - if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } - jsval val; JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { - JS_ReportError(cx, "An option is missing or isn't an int."); - return JS_FALSE; + width = INT_TO_JSVAL(0); + height = INT_TO_JSVAL(0); + x = INT_TO_JSVAL(0); + y = INT_TO_JSVAL(0); } - WINDOW* win; - if (argc == 2) { - WINDOW* parentWin = JS_GetPrivate(cx, parent); - win = subwin(parentWin, - JSVAL_TO_INT(height), JSVAL_TO_INT(width), - JSVAL_TO_INT(y), JSVAL_TO_INT(x) - ); - } - else { - win = newwin( - JSVAL_TO_INT(height), JSVAL_TO_INT(width), - JSVAL_TO_INT(y), JSVAL_TO_INT(x) - ); + WindowInformation* data = JS_malloc(cx, sizeof(WindowInformation)); + switch (argc) { + case 0: + case 1: { + data->win = newwin( + JSVAL_TO_INT(height), JSVAL_TO_INT(width), + JSVAL_TO_INT(y), JSVAL_TO_INT(x) + ); + } break; + + case 2: { + WINDOW* parentWin = ((WindowInformation*)JS_GetPrivate(cx, parent))->win; + data->win = subwin(parentWin, + JSVAL_TO_INT(height), JSVAL_TO_INT(width), + JSVAL_TO_INT(y), JSVAL_TO_INT(x) + ); + } break; } - JS_SetPrivate(cx, object, win); + JS_SetPrivate(cx, object, data); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (border) { - box(win, 0, 0); + box(data->win, 0, 0); + data->border = JS_TRUE; + } + else { + data->border = JS_FALSE; } - wrefresh(win); + wrefresh(data->win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { - WINDOW* win = JS_GetPrivate(cx, object); + WindowInformation* data = JS_GetPrivate(cx, object); - if (win) { - delwin(win); + if (data) { + if (data->win && data->win != stdscr) { + delwin(data->win); + } } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } +JSBool +Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* options; + + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + JS_ValueToObject(cx, argv[0], &options); + jsval width; JS_GetProperty(cx, options, "width", &width); + jsval height; JS_GetProperty(cx, options, "height", &height); + + if (!JSVAL_IS_INT(width) && !JSVAL_IS_INT(height)) { + JS_ReportError(cx, "An option isn't an int."); + return JS_FALSE; + } + + WindowInformation* data = JS_GetPrivate(cx, object); + wresize(data->win, height, width); + if (data->border) { + box(data->win, 0, 0); + } + wrefresh(data->win); + + + __Window_updateSize(cx, object); + + return JS_TRUE; + +} + JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); - __options(cx, win, options, JS_TRUE); + __Window_options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } - __options(cx, win, options, JS_FALSE); + __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); - __options(cx, win, options, JS_TRUE); + __Window_options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } - __options(cx, win, options, JS_FALSE); + __Window_options(cx, win, options, JS_FALSE); } return JS_TRUE; } +void +__Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) +{ + jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attribute", &jsAttrs); + + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attributes", &jsAttrs); + } + } + + if (JSVAL_IS_INT(jsAttrs)) { + if (apply) { + wattron(win, JSVAL_TO_INT(jsAttrs)); + } + else { + wattroff(win, JSVAL_TO_INT(jsAttrs)); + } + } + + jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); + if (!JSVAL_IS_INT(jsForeground)) { + JS_GetProperty(cx, options, "foreground", &jsForeground); + } + + jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); + if (!JSVAL_IS_INT(jsBackground)) { + JS_GetProperty(cx, options, "background", &jsBackground); + } + + short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; + short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; + + if (fg == -1 && bg == -1) { + return; + } + + char pair[3] = {0}; + sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default + sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 + + short c_pair = atoi(pair); + if (apply) { + init_pair(c_pair, fg, bg); + wattron(win, COLOR_PAIR(c_pair)); + } + else { + wattroff(win, COLOR_PAIR(c_pair)); + } +} + void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; getmaxyx(win, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; - WINDOW* win = JS_GetPrivate(cx, object); + WINDOW* win = ((WindowInformation*)JS_GetPrivate(cx, object))->win; getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/Window.h b/src/Window.h index 6b2aa0c..a507e8d 100644 --- a/src/Window.h +++ b/src/Window.h @@ -1,59 +1,64 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" extern JSBool exec (JSContext* cx); extern JSBool Window_initialize (JSContext* cx); extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Window_finalize (JSContext* cx, JSObject* object); static JSClass Window_class = { "Window", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize }; +#include "Window_private.h" + extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Window_resize (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +void __Window_options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply); void __Window_updateSize (JSContext* cx, JSObject* object); void __Window_updatePosition (JSContext* cx, JSObject* object); static JSFunctionSpec Window_methods[] = { {"refresh", Window_refresh, 0, 0, 0}, {"redraw", Window_redraw, 0, 0, 0}, + {"resize", Window_resize, 0, 0, 0}, {"printChar", Window_printChar, 0, 0, 0}, {"getChar", Window_getChar, 0, 0, 0}, {"printString", Window_printString, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Window_private.h b/src/Window_private.h new file mode 100644 index 0000000..471468c --- /dev/null +++ b/src/Window_private.h @@ -0,0 +1,27 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_WINDOW_PRIVATE +#define _LULZJS_NCURSES_WINDOW_PRIVATE + +typedef struct { + WINDOW* win; + JSBool border; +} WindowInformation; + +#endif diff --git a/src/common.h b/src/common.h index 3eda7b5..7c1a5cf 100644 --- a/src/common.h +++ b/src/common.h @@ -1,167 +1,28 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_COMMON_H #define _LULZJS_NCURSES_COMMON_H #include "lulzjs.h" #include <curses.h> #include <panel.h> #include <form.h> #include <menu.h> -void -__options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) -{ - jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); - if (!JSVAL_IS_INT(jsAttrs)) { - JS_GetProperty(cx, options, "attribute", &jsAttrs); - - if (!JSVAL_IS_INT(jsAttrs)) { - JS_GetProperty(cx, options, "attributes", &jsAttrs); - } - } - - if (JSVAL_IS_INT(jsAttrs)) { - if (apply) { - wattron(win, JSVAL_TO_INT(jsAttrs)); - } - else { - wattroff(win, JSVAL_TO_INT(jsAttrs)); - } - } - - jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); - if (!JSVAL_IS_INT(jsForeground)) { - JS_GetProperty(cx, options, "foreground", &jsForeground); - } - - jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); - if (!JSVAL_IS_INT(jsBackground)) { - JS_GetProperty(cx, options, "background", &jsBackground); - } - - short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; - short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; - - if (fg == -1 && bg == -1) { - return; - } - - char pair[3] = {0}; - sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default - sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 - - short c_pair = atoi(pair); - if (apply) { - init_pair(c_pair, fg, bg); - wattron(win, COLOR_PAIR(c_pair)); - } - else { - wattroff(win, COLOR_PAIR(c_pair)); - } -} - -void -__updateACS (JSContext* cx) -{ - jsval property; - - JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); - JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); - jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); - JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); - property = INT_TO_JSVAL(ACS_BLOCK); - JS_SetProperty(cx, AlternativeChars, "Block", &property); - property = INT_TO_JSVAL(ACS_BOARD); - JS_SetProperty(cx, AlternativeChars, "Board", &property); - property = INT_TO_JSVAL(ACS_BTEE); - JS_SetProperty(cx, AlternativeChars, "BottomT", &property); - property = INT_TO_JSVAL(ACS_BULLET); - JS_SetProperty(cx, AlternativeChars, "Bullet", &property); - property = INT_TO_JSVAL(ACS_CKBOARD); - JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); - property = INT_TO_JSVAL(ACS_DARROW); - JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); - property = INT_TO_JSVAL(ACS_DEGREE); - JS_SetProperty(cx, AlternativeChars, "Degree", &property); - property = INT_TO_JSVAL(ACS_DIAMOND); - JS_SetProperty(cx, AlternativeChars, "Diamond", &property); - property = INT_TO_JSVAL(ACS_GEQUAL); - JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); - property = INT_TO_JSVAL(ACS_HLINE); - JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); - property = INT_TO_JSVAL(ACS_LANTERN); - JS_SetProperty(cx, AlternativeChars, "Lantern", &property); - property = INT_TO_JSVAL(ACS_LARROW); - JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); - property = INT_TO_JSVAL(ACS_LEQUAL); - JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); - property = INT_TO_JSVAL(ACS_LLCORNER); - JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); - property = INT_TO_JSVAL(ACS_LRCORNER); - JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); - property = INT_TO_JSVAL(ACS_LTEE); - JS_SetProperty(cx, AlternativeChars, "LeftT", &property); - property = INT_TO_JSVAL(ACS_NEQUAL); - JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); - property = INT_TO_JSVAL(ACS_PI); - JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); - property = INT_TO_JSVAL(ACS_PLMINUS); - JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); - property = INT_TO_JSVAL(ACS_PLUS); - JS_SetProperty(cx, AlternativeChars, "Plus", &property); - property = INT_TO_JSVAL(ACS_RARROW); - JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); - property = INT_TO_JSVAL(ACS_RTEE); - JS_SetProperty(cx, AlternativeChars, "RightT", &property); - property = INT_TO_JSVAL(ACS_S1); - JS_SetProperty(cx, AlternativeChars, "Scan1", &property); - property = INT_TO_JSVAL(ACS_S3); - JS_SetProperty(cx, AlternativeChars, "Scan3", &property); - property = INT_TO_JSVAL(ACS_S7); - JS_SetProperty(cx, AlternativeChars, "Scan7", &property); - property = INT_TO_JSVAL(ACS_S9); - JS_SetProperty(cx, AlternativeChars, "Scan9", &property); - property = INT_TO_JSVAL(ACS_STERLING); - JS_SetProperty(cx, AlternativeChars, "Pound", &property); - property = INT_TO_JSVAL(ACS_TTEE); - JS_SetProperty(cx, AlternativeChars, "TopT", &property); - property = INT_TO_JSVAL(ACS_UARROW); - JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); - property = INT_TO_JSVAL(ACS_ULCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); - property = INT_TO_JSVAL(ACS_URCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); - property = INT_TO_JSVAL(ACS_VLINE); - JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); - property = INT_TO_JSVAL(ACS_STERLING); - JS_SetProperty(cx, AlternativeChars, "Pound", &property); - property = INT_TO_JSVAL(ACS_TTEE); - JS_SetProperty(cx, AlternativeChars, "TopT", &property); - property = INT_TO_JSVAL(ACS_UARROW); - JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); - property = INT_TO_JSVAL(ACS_ULCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); - property = INT_TO_JSVAL(ACS_URCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); - property = INT_TO_JSVAL(ACS_VLINE); - JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); -} - #endif diff --git a/test/panel.js b/test/panel.js index 3efac5f..5ad6ea4 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,13 +1,17 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); var panels = [] panels.push(new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true})); panels.push(new ncurses.Panel({x: 4, y: 5, width: 30, height: 10, border: true})); -panels[0].printString("LOL", {x: 1, y: 1}); +panels[0].printString(panels[0].Size, {x: 1, y: 1}); panels[1].printString("PENIS", {x: 10, y: 4}); panels[0].toTop(); panels[0].getChar(); panels[0].below.getChar(); +panels[0].resize({width: 5, height: 5}); +ncurses.Panel.update(); +screen.refresh(); +panels[0].getChar(); diff --git a/test/window.js b/test/window.js index ee2d93f..82aad02 100755 --- a/test/window.js +++ b/test/window.js @@ -1,8 +1,8 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); var win = new ncurses.Window({x: 2, y: 2, width: 40, height: 10, border: true}); -win.printString("LOLNIGGERS", {x: 10, y: 4, fg: ncurses.Colors.Blue}); +win.printString("X: {X}, Y: {Y}".format(win.Position), {x: 10, y: 4, fg: ncurses.Colors.Blue}); win.printChar(win.getChar(), {x: 2, y: 2}) win.getChar();
meh/lulzjs-ncurses
c5cd0bb5123420481222482fd4c2d38162560bf1
Panel addons.
diff --git a/src/Panel.c b/src/Panel.c index 3a479e9..e2cef97 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,132 +1,199 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" +extern JSObject** panels; +extern int panelsSize; + JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); + panels = realloc(panels, (++panelsSize)*sizeof(JSObject*)); + panels[panelsSize-1] = object; + + JS_DefineProperty( + cx, object, "below", JSVAL_NULL, + (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_below, 0, 0, NULL, NULL)), + NULL, JSPROP_GETTER|JSPROP_READONLY + ); + JS_DefineProperty( + cx, object, "above", JSVAL_NULL, + (JSPropertyOp) JS_GetFunctionObject(JS_NewFunction(cx, Panel_above, 0, 0, NULL, NULL)), + NULL, JSPROP_GETTER|JSPROP_READONLY + ); + return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { + // Find the object being finalized and remove it from the list + int i; + for (i = 0; i < panelsSize; i++) { + if (object == panels[i]) { + break; + } + } + for (i++; i < panelsSize; i++) { + panels[i-1] = panels[i]; + } + panels = realloc(panels, (--panelsSize)*sizeof(JSObject*)); + del_panel(panel); } } JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); hide_panel(panel); jsval val = JSVAL_TRUE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); show_panel(panel); jsval val = JSVAL_FALSE; JS_SetProperty(cx, object, "hidden", &val); return JS_TRUE; } JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); top_panel(panel); return JS_TRUE; } JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { PANEL* panel = JS_GetPrivate(cx, object); bottom_panel(panel); return JS_TRUE; } +JSBool +Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + PANEL* above = panel_above(panel); + + int i; + for (i = 0; i < panelsSize; i++) { + PANEL* check = JS_GetPrivate(cx, panels[i]); + + if (check == above) { + *rval = OBJECT_TO_JSVAL(panels[i]); + break; + } + } + + return JS_TRUE; +} + +JSBool +Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + PANEL* below = panel_below(panel); + + int i; + for (i = 0; i < panelsSize; i++) { + PANEL* check = JS_GetPrivate(cx, panels[i]); + + if (check == below) { + *rval = OBJECT_TO_JSVAL(panels[i]); + break; + } + } + + return JS_TRUE; +} + JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index 162d4e8..90d95ea 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,58 +1,64 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" +JSObject** panels = NULL; +int panelsSize = 0; + extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Panel_above (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Panel_below (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { {"hide", Panel_hide, 0, 0, 0}, {"show", Panel_show, 0, 0, 0}, {"toTop", Panel_toTop, 0, 0, 0}, {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/test/panel.js b/test/panel.js index 05653ca..3efac5f 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,7 +1,13 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); -var panel = new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true}); -panel.printString("LOL", {x: 1, y: 1}); -panel.getChar(); + +var panels = [] +panels.push(new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true})); +panels.push(new ncurses.Panel({x: 4, y: 5, width: 30, height: 10, border: true})); +panels[0].printString("LOL", {x: 1, y: 1}); +panels[1].printString("PENIS", {x: 10, y: 4}); +panels[0].toTop(); +panels[0].getChar(); +panels[0].below.getChar();
meh/lulzjs-ncurses
313f506743aaf8a70b78c697ffbcbbc834a75730
sleepeh
diff --git a/Makefile b/Makefile index 31ad884..96bb2b4 100644 --- a/Makefile +++ b/Makefile @@ -1,51 +1,54 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" -I/usr/include/js -I./src LDFLAGS = -ljs -llulzjs ifdef DEBUG CFLAGS += -g endif ifdef DDEBUG CFLAGS += -DDEBUG -g endif LIB_DIR = src -LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o +LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o ${LIB_DIR}/Panel.o LIB_CFLAGS = ${CFLAGS} -LIB_LDFLAGS = ${LDFLAGS} -lncurses -lpanel -lform -lmenu +LIB_LDFLAGS = ${LDFLAGS} -lpanel -lform -lmenu -lncurses all: lib lib: $(LIB) $(LIB) : $(LIB:.o=.c) ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js cp -f ${LIB_DIR}/Window.o ${LJS_LIBDIR}/ncurses/Window.so + cp -f ${LIB_DIR}/Window.js ${LJS_LIBDIR}/ncurses/Window.js cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js + cp -f ${LIB_DIR}/Panel.o ${LJS_LIBDIR}/ncurses/Panel.so + cp -f ${LIB_DIR}/Panel.js ${LJS_LIBDIR}/ncurses/Panel.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses lib_uninstall: rm -rf ${LJS_LIBDIR}/ncurses install: lib_install uninstall: lib_uninstall clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Panel.c b/src/Panel.c index 6aefa3a..3a479e9 100644 --- a/src/Panel.c +++ b/src/Panel.c @@ -1,91 +1,132 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Panel.h" JSBool exec (JSContext* cx) { return Panel_initialize(cx); } JSBool Panel_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Panel_class, Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods ); if (object) { - // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSObject* class = JSVAL_TO_OBJECT(property); JS_GetProperty(cx, class, "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); - JSObject* Window = JS_ConstructObject(cx, NULL, proto, NULL); + JSObject* Window = JS_ConstructObject(cx, JS_GET_CLASS(cx, class), proto, NULL); JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); JS_SetPrivate(cx, object, panel); update_panels(); return JS_TRUE; } void Panel_finalize (JSContext* cx, JSObject* object) { PANEL* panel = JS_GetPrivate(cx, object); if (panel) { del_panel(panel); } } +JSBool +Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + hide_panel(panel); + + jsval val = JSVAL_TRUE; + JS_SetProperty(cx, object, "hidden", &val); + + return JS_TRUE; +} + +JSBool +Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + show_panel(panel); + + jsval val = JSVAL_FALSE; + JS_SetProperty(cx, object, "hidden", &val); + + return JS_TRUE; +} + +JSBool +Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + top_panel(panel); + + return JS_TRUE; +} + +JSBool +Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + PANEL* panel = JS_GetPrivate(cx, object); + bottom_panel(panel); + + return JS_TRUE; +} + JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { update_panels(); return JS_TRUE; } diff --git a/src/Panel.h b/src/Panel.h index a2d32c0..162d4e8 100644 --- a/src/Panel.h +++ b/src/Panel.h @@ -1,47 +1,58 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" extern JSBool exec (JSContext* cx); extern JSBool Panel_initialize (JSContext* cx); extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Panel_finalize (JSContext* cx, JSObject* object); static JSClass Panel_class = { "Panel", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize }; +extern JSBool Panel_hide (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Panel_show (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + +extern JSBool Panel_toTop (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Panel_toBottom (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Panel_methods[] = { + {"hide", Panel_hide, 0, 0, 0}, + {"show", Panel_show, 0, 0, 0}, + + {"toTop", Panel_toTop, 0, 0, 0}, + {"toBottom", Panel_toBottom, 0, 0, 0}, {NULL} }; static JSFunctionSpec Panel_static_methods[] = { {"update", Panel_static_update, 0, 0, 0}, {NULL} }; #endif diff --git a/src/Panel.js b/src/Panel.js index 1d17d9c..66ec44f 100644 --- a/src/Panel.js +++ b/src/Panel.js @@ -1,35 +1,39 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Panel.prototype, { + refresh: function () { + this.__window.refresh(); + }, + printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); diff --git a/src/Screen.c b/src/Screen.c index deb2390..b5b8198 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,209 +1,210 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, Screen_constructor, 1, NULL, Screen_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); + __updateACS(cx); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); jsval property; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); JSObject* proto = JSVAL_TO_OBJECT(property); JSObject* Window = JS_NewObject(cx, class, proto, NULL); JS_SetPrivate(cx, Window, stdscr); property = OBJECT_TO_JSVAL(Window); JS_SetProperty(cx, object, "__window", &property); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } curs_set(1); endwin(); JS_free(cx, data); } } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } diff --git a/src/Screen.js b/src/Screen.js index ca6c030..c43e2ae 100644 --- a/src/Screen.js +++ b/src/Screen.js @@ -1,35 +1,39 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Screen.prototype, { + refresh: function () { + this.__window.refresh(); + }, + printChar: function (ch, options) { if (options) this.__window.printChar(ch, options); else this.__window.printChar(ch); }, getChar: function (options) { return (options ? this.__window.getChar(options) : this.__window.getChar()); }, printString: function (str, options) { if (options) this.__window.printString(str, options); else this.__window.printString(str); } }); diff --git a/src/Window.c b/src/Window.c index dbfef75..51e897a 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,312 +1,312 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } jsval val; JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } - WINDOW* win = JS_malloc(cx, sizeof(WINDOW)); + WINDOW* win; if (argc == 2) { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } else { win = newwin( JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); if (border) { box(win, 0, 0); } wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win) { - JS_free(cx, win); + delwin(win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __options(cx, win, options, JS_FALSE); } return JS_TRUE; } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/Window.js b/src/Window.js index 66752a4..67f6509 100644 --- a/src/Window.js +++ b/src/Window.js @@ -1,21 +1,21 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ -Object.extend(Window.prototype, { +Object.extend(ncurses.Window.prototype, { }); diff --git a/src/common.h b/src/common.h index 9ca3142..3eda7b5 100644 --- a/src/common.h +++ b/src/common.h @@ -1,80 +1,167 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_COMMON_H #define _LULZJS_NCURSES_COMMON_H #include "lulzjs.h" #include <curses.h> #include <panel.h> #include <form.h> #include <menu.h> void __options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { wattron(win, JSVAL_TO_INT(jsAttrs)); } else { wattroff(win, JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; if (fg == -1 && bg == -1) { return; } char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); wattron(win, COLOR_PAIR(c_pair)); } else { wattroff(win, COLOR_PAIR(c_pair)); } } +void +__updateACS (JSContext* cx) +{ + jsval property; + + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); + JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); + JS_SetProperty(cx, JSVAL_TO_OBJECT(property), "AlternativeChars", &jsAlternativeChars); + property = INT_TO_JSVAL(ACS_BLOCK); + JS_SetProperty(cx, AlternativeChars, "Block", &property); + property = INT_TO_JSVAL(ACS_BOARD); + JS_SetProperty(cx, AlternativeChars, "Board", &property); + property = INT_TO_JSVAL(ACS_BTEE); + JS_SetProperty(cx, AlternativeChars, "BottomT", &property); + property = INT_TO_JSVAL(ACS_BULLET); + JS_SetProperty(cx, AlternativeChars, "Bullet", &property); + property = INT_TO_JSVAL(ACS_CKBOARD); + JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); + property = INT_TO_JSVAL(ACS_DARROW); + JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); + property = INT_TO_JSVAL(ACS_DEGREE); + JS_SetProperty(cx, AlternativeChars, "Degree", &property); + property = INT_TO_JSVAL(ACS_DIAMOND); + JS_SetProperty(cx, AlternativeChars, "Diamond", &property); + property = INT_TO_JSVAL(ACS_GEQUAL); + JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); + property = INT_TO_JSVAL(ACS_HLINE); + JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); + property = INT_TO_JSVAL(ACS_LANTERN); + JS_SetProperty(cx, AlternativeChars, "Lantern", &property); + property = INT_TO_JSVAL(ACS_LARROW); + JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); + property = INT_TO_JSVAL(ACS_LEQUAL); + JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); + property = INT_TO_JSVAL(ACS_LLCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); + property = INT_TO_JSVAL(ACS_LRCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); + property = INT_TO_JSVAL(ACS_LTEE); + JS_SetProperty(cx, AlternativeChars, "LeftT", &property); + property = INT_TO_JSVAL(ACS_NEQUAL); + JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); + property = INT_TO_JSVAL(ACS_PI); + JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); + property = INT_TO_JSVAL(ACS_PLMINUS); + JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); + property = INT_TO_JSVAL(ACS_PLUS); + JS_SetProperty(cx, AlternativeChars, "Plus", &property); + property = INT_TO_JSVAL(ACS_RARROW); + JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); + property = INT_TO_JSVAL(ACS_RTEE); + JS_SetProperty(cx, AlternativeChars, "RightT", &property); + property = INT_TO_JSVAL(ACS_S1); + JS_SetProperty(cx, AlternativeChars, "Scan1", &property); + property = INT_TO_JSVAL(ACS_S3); + JS_SetProperty(cx, AlternativeChars, "Scan3", &property); + property = INT_TO_JSVAL(ACS_S7); + JS_SetProperty(cx, AlternativeChars, "Scan7", &property); + property = INT_TO_JSVAL(ACS_S9); + JS_SetProperty(cx, AlternativeChars, "Scan9", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); +} + #endif diff --git a/src/init.js b/src/init.js index f850b07..b4f5ffa 100644 --- a/src/init.js +++ b/src/init.js @@ -1,23 +1,24 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ require(["ncurses.so", "ncurses.js"]); require(["Window.so", "Window.js"]); require(["Screen.so", "Screen.js"]); +require(["Panel.so", "Panel.js"]); diff --git a/src/ncurses.c b/src/ncurses.c index 0b96262..267ca9b 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,397 +1,317 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); JS_SetProperty(cx, Keys, "EndOfScreen", &property); property = INT_TO_JSVAL(KEY_EOL); JS_SetProperty(cx, Keys, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SF); JS_SetProperty(cx, Keys, "ScrollForward", &property); property = INT_TO_JSVAL(KEY_SR); JS_SetProperty(cx, Keys, "ScrollBackward", &property); property = INT_TO_JSVAL(KEY_NPAGE); JS_SetProperty(cx, Keys, "NextPage", &property); property = INT_TO_JSVAL(KEY_PPAGE); JS_SetProperty(cx, Keys, "PreviousPage", &property); property = INT_TO_JSVAL(KEY_STAB); JS_SetProperty(cx, Keys, "SetTab", &property); property = INT_TO_JSVAL(KEY_CTAB); JS_SetProperty(cx, Keys, "ClearTab", &property); property = INT_TO_JSVAL(KEY_CATAB); JS_SetProperty(cx, Keys, "ClearAllTabs", &property); property = INT_TO_JSVAL(KEY_ENTER); JS_SetProperty(cx, Keys, "Enter", &property); property = INT_TO_JSVAL(KEY_SRESET); JS_SetProperty(cx, Keys, "SoftReset", &property); property = INT_TO_JSVAL(KEY_RESET); JS_SetProperty(cx, Keys, "Reset", &property); property = INT_TO_JSVAL(KEY_PRINT); JS_SetProperty(cx, Keys, "Print", &property); property = INT_TO_JSVAL(KEY_LL); JS_SetProperty(cx, Keys, "Bottom", &property); property = INT_TO_JSVAL(KEY_A1); JS_SetProperty(cx, Keys, "UpperLeft", &property); property = INT_TO_JSVAL(KEY_A3); JS_SetProperty(cx, Keys, "UpperRight", &property); property = INT_TO_JSVAL(KEY_B2); JS_SetProperty(cx, Keys, "Center", &property); property = INT_TO_JSVAL(KEY_C1); JS_SetProperty(cx, Keys, "LowerLeft", &property); property = INT_TO_JSVAL(KEY_C3); JS_SetProperty(cx, Keys, "LowerRight", &property); property = INT_TO_JSVAL(KEY_BTAB); JS_SetProperty(cx, Keys, "BackTab", &property); property = INT_TO_JSVAL(KEY_BEG); JS_SetProperty(cx, Keys, "Beginning", &property); property = INT_TO_JSVAL(KEY_CANCEL); JS_SetProperty(cx, Keys, "Cancel", &property); property = INT_TO_JSVAL(KEY_CLOSE); JS_SetProperty(cx, Keys, "Close", &property); property = INT_TO_JSVAL(KEY_COMMAND); JS_SetProperty(cx, Keys, "Command", &property); property = INT_TO_JSVAL(KEY_COPY); JS_SetProperty(cx, Keys, "Copy", &property); property = INT_TO_JSVAL(KEY_CREATE); JS_SetProperty(cx, Keys, "Create", &property); property = INT_TO_JSVAL(KEY_END); JS_SetProperty(cx, Keys, "End", &property); property = INT_TO_JSVAL(KEY_EXIT); JS_SetProperty(cx, Keys, "Exit", &property); property = INT_TO_JSVAL(KEY_FIND); JS_SetProperty(cx, Keys, "Find", &property); property = INT_TO_JSVAL(KEY_HELP); JS_SetProperty(cx, Keys, "Help", &property); property = INT_TO_JSVAL(KEY_MARK); JS_SetProperty(cx, Keys, "Mark", &property); property = INT_TO_JSVAL(KEY_MESSAGE); JS_SetProperty(cx, Keys, "Message", &property); property = INT_TO_JSVAL(KEY_MOUSE); JS_SetProperty(cx, Keys, "Mouse", &property); property = INT_TO_JSVAL(KEY_MOVE); JS_SetProperty(cx, Keys, "Move", &property); property = INT_TO_JSVAL(KEY_NEXT); JS_SetProperty(cx, Keys, "Next", &property); property = INT_TO_JSVAL(KEY_OPEN); JS_SetProperty(cx, Keys, "Open", &property); property = INT_TO_JSVAL(KEY_OPTIONS); JS_SetProperty(cx, Keys, "Options", &property); property = INT_TO_JSVAL(KEY_PREVIOUS); JS_SetProperty(cx, Keys, "Previous", &property); property = INT_TO_JSVAL(KEY_REDO); JS_SetProperty(cx, Keys, "Redo", &property); property = INT_TO_JSVAL(KEY_REFERENCE); JS_SetProperty(cx, Keys, "Reference", &property); property = INT_TO_JSVAL(KEY_REFRESH); JS_SetProperty(cx, Keys, "Refresh", &property); property = INT_TO_JSVAL(KEY_REPLACE); JS_SetProperty(cx, Keys, "Replace", &property); property = INT_TO_JSVAL(KEY_RESIZE); JS_SetProperty(cx, Keys, "Resize", &property); property = INT_TO_JSVAL(KEY_RESTART); JS_SetProperty(cx, Keys, "Restart", &property); property = INT_TO_JSVAL(KEY_RESUME); JS_SetProperty(cx, Keys, "Resume", &property); property = INT_TO_JSVAL(KEY_SAVE); JS_SetProperty(cx, Keys, "Save", &property); property = INT_TO_JSVAL(KEY_SELECT); JS_SetProperty(cx, Keys, "Select", &property); property = INT_TO_JSVAL(KEY_SUSPEND); JS_SetProperty(cx, Keys, "Suspend", &property); property = INT_TO_JSVAL(KEY_UNDO); JS_SetProperty(cx, Keys, "Undo", &property); JSObject* Shifted = JS_NewObject(cx, NULL, NULL, NULL); jsval jsShifted = OBJECT_TO_JSVAL(Shifted); JS_SetProperty(cx, Keys, "Shifted", &jsShifted); property = INT_TO_JSVAL(KEY_SBEG); JS_SetProperty(cx, Shifted, "Beginning", &property); property = INT_TO_JSVAL(KEY_SCANCEL); JS_SetProperty(cx, Shifted, "Cancel", &property); property = INT_TO_JSVAL(KEY_SCOMMAND); JS_SetProperty(cx, Shifted, "Command", &property); property = INT_TO_JSVAL(KEY_SCOPY); JS_SetProperty(cx, Shifted, "Copy", &property); property = INT_TO_JSVAL(KEY_SCREATE); JS_SetProperty(cx, Shifted, "Create", &property); property = INT_TO_JSVAL(KEY_SDC); JS_SetProperty(cx, Shifted, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_SDL); JS_SetProperty(cx, Shifted, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_SEND); JS_SetProperty(cx, Shifted, "End", &property); property = INT_TO_JSVAL(KEY_SEOL); JS_SetProperty(cx, Shifted, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SEXIT); JS_SetProperty(cx, Shifted, "Exit", &property); property = INT_TO_JSVAL(KEY_SFIND); JS_SetProperty(cx, Shifted, "Find", &property); property = INT_TO_JSVAL(KEY_SHELP); JS_SetProperty(cx, Shifted, "Help", &property); property = INT_TO_JSVAL(KEY_SHOME); JS_SetProperty(cx, Shifted, "Home", &property); property = INT_TO_JSVAL(KEY_SIC); JS_SetProperty(cx, Shifted, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_SLEFT); JS_SetProperty(cx, Shifted, "Left", &property); property = INT_TO_JSVAL(KEY_SMESSAGE); JS_SetProperty(cx, Shifted, "Message", &property); property = INT_TO_JSVAL(KEY_SMOVE); JS_SetProperty(cx, Shifted, "Move", &property); property = INT_TO_JSVAL(KEY_SNEXT); JS_SetProperty(cx, Shifted, "Next", &property); property = INT_TO_JSVAL(KEY_SOPTIONS); JS_SetProperty(cx, Shifted, "Options", &property); property = INT_TO_JSVAL(KEY_SPREVIOUS); JS_SetProperty(cx, Shifted, "Previous", &property); property = INT_TO_JSVAL(KEY_SPRINT); JS_SetProperty(cx, Shifted, "Print", &property); property = INT_TO_JSVAL(KEY_SREDO); JS_SetProperty(cx, Shifted, "Redo", &property); property = INT_TO_JSVAL(KEY_SREPLACE); JS_SetProperty(cx, Shifted, "Replace", &property); property = INT_TO_JSVAL(KEY_SRIGHT); JS_SetProperty(cx, Shifted, "Right", &property); property = INT_TO_JSVAL(KEY_SRSUME); JS_SetProperty(cx, Shifted, "Resume", &property); property = INT_TO_JSVAL(KEY_SSAVE); JS_SetProperty(cx, Shifted, "Save", &property); property = INT_TO_JSVAL(KEY_SSUSPEND); JS_SetProperty(cx, Shifted, "Suspend", &property); property = INT_TO_JSVAL(KEY_SUNDO); JS_SetProperty(cx, Shifted, "Undo", &property); - JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); - jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); - JS_SetProperty(cx, object, "AlternativeChars", &jsAlternativeChars); - property = INT_TO_JSVAL(ACS_BLOCK); - JS_SetProperty(cx, AlternativeChars, "Block", &property); - property = INT_TO_JSVAL(ACS_BOARD); - JS_SetProperty(cx, AlternativeChars, "Board", &property); - property = INT_TO_JSVAL(ACS_BTEE); - JS_SetProperty(cx, AlternativeChars, "BottomT", &property); - property = INT_TO_JSVAL(ACS_BULLET); - JS_SetProperty(cx, AlternativeChars, "Bullet", &property); - property = INT_TO_JSVAL(ACS_CKBOARD); - JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); - property = INT_TO_JSVAL(ACS_DARROW); - JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); - property = INT_TO_JSVAL(ACS_DEGREE); - JS_SetProperty(cx, AlternativeChars, "Degree", &property); - property = INT_TO_JSVAL(ACS_DIAMOND); - JS_SetProperty(cx, AlternativeChars, "Diamond", &property); - property = INT_TO_JSVAL(ACS_GEQUAL); - JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); - property = INT_TO_JSVAL(ACS_HLINE); - JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); - property = INT_TO_JSVAL(ACS_LANTERN); - JS_SetProperty(cx, AlternativeChars, "Lantern", &property); - property = INT_TO_JSVAL(ACS_LARROW); - JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); - property = INT_TO_JSVAL(ACS_LEQUAL); - JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); - property = INT_TO_JSVAL(ACS_LLCORNER); - JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); - property = INT_TO_JSVAL(ACS_LRCORNER); - JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); - property = INT_TO_JSVAL(ACS_LTEE); - JS_SetProperty(cx, AlternativeChars, "LeftT", &property); - property = INT_TO_JSVAL(ACS_NEQUAL); - JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); - property = INT_TO_JSVAL(ACS_PI); - JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); - property = INT_TO_JSVAL(ACS_PLMINUS); - JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); - property = INT_TO_JSVAL(ACS_PLUS); - JS_SetProperty(cx, AlternativeChars, "Plus", &property); - property = INT_TO_JSVAL(ACS_RARROW); - JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); - property = INT_TO_JSVAL(ACS_RTEE); - JS_SetProperty(cx, AlternativeChars, "RightT", &property); - property = INT_TO_JSVAL(ACS_S1); - JS_SetProperty(cx, AlternativeChars, "Scan1", &property); - property = INT_TO_JSVAL(ACS_S3); - JS_SetProperty(cx, AlternativeChars, "Scan3", &property); - property = INT_TO_JSVAL(ACS_S7); - JS_SetProperty(cx, AlternativeChars, "Scan7", &property); - property = INT_TO_JSVAL(ACS_S9); - JS_SetProperty(cx, AlternativeChars, "Scan9", &property); - property = INT_TO_JSVAL(ACS_STERLING); - JS_SetProperty(cx, AlternativeChars, "Pound", &property); - property = INT_TO_JSVAL(ACS_TTEE); - JS_SetProperty(cx, AlternativeChars, "TopT", &property); - property = INT_TO_JSVAL(ACS_UARROW); - JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); - property = INT_TO_JSVAL(ACS_ULCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); - property = INT_TO_JSVAL(ACS_URCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); - property = INT_TO_JSVAL(ACS_VLINE); - JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); - property = INT_TO_JSVAL(ACS_STERLING); - JS_SetProperty(cx, AlternativeChars, "Pound", &property); - property = INT_TO_JSVAL(ACS_TTEE); - JS_SetProperty(cx, AlternativeChars, "TopT", &property); - property = INT_TO_JSVAL(ACS_UARROW); - JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); - property = INT_TO_JSVAL(ACS_ULCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); - property = INT_TO_JSVAL(ACS_URCORNER); - JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); - property = INT_TO_JSVAL(ACS_VLINE); - JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); - return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); if (n < 0 || n > 63) { JS_ReportError(cx, "Out of range."); return JS_FALSE; } *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; } diff --git a/test/panel.js b/test/panel.js index 9d23b2a..05653ca 100755 --- a/test/panel.js +++ b/test/panel.js @@ -1,8 +1,7 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); -var panel = new ncurses.Panel({x: 0, y: 0, width: 30, height: 10, border: true}); -screen.printString(panel.__window.getChar()); -screen.refresh(); -screen.getChar(); +var panel = new ncurses.Panel({x: 2, y: 2, width: 30, height: 10, border: true}); +panel.printString("LOL", {x: 1, y: 1}); +panel.getChar();
meh/lulzjs-ncurses
a88f2982d1a546ac6f9e5cc6899bdbb518567173
Still not working but meh.
diff --git a/src/Panel.c b/src/Panel.c new file mode 100644 index 0000000..6aefa3a --- /dev/null +++ b/src/Panel.c @@ -0,0 +1,91 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#include "Panel.h" + +JSBool exec (JSContext* cx) { return Panel_initialize(cx); } + +JSBool +Panel_initialize (JSContext* cx) +{ + jsval jsParent; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); + JSObject* parent = JSVAL_TO_OBJECT(jsParent); + + JSObject* object = JS_InitClass( + cx, parent, NULL, &Panel_class, + Panel_constructor, 1, NULL, Panel_methods, NULL, Panel_static_methods + ); + + if (object) { + // Default properties + jsval property; + + return JS_TRUE; + } + + return JS_FALSE; +} + +JSBool +Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + jsval property; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); + JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); + + JSObject* class = JSVAL_TO_OBJECT(property); + JS_GetProperty(cx, class, "prototype", &property); + JSObject* proto = JSVAL_TO_OBJECT(property); + + JSObject* Window = JS_ConstructObject(cx, NULL, proto, NULL); + JS_CallFunctionValue(cx, Window, OBJECT_TO_JSVAL(class), argc, argv, &property); + + property = OBJECT_TO_JSVAL(Window); + JS_SetProperty(cx, object, "__window", &property); + + PANEL* panel = new_panel((WINDOW*)JS_GetPrivate(cx, Window)); + JS_SetPrivate(cx, object, panel); + + update_panels(); + + return JS_TRUE; +} + +void +Panel_finalize (JSContext* cx, JSObject* object) +{ + PANEL* panel = JS_GetPrivate(cx, object); + + if (panel) { + del_panel(panel); + } +} + +JSBool +Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + update_panels(); + return JS_TRUE; +} + diff --git a/src/Panel.h b/src/Panel.h new file mode 100644 index 0000000..a2d32c0 --- /dev/null +++ b/src/Panel.h @@ -0,0 +1,47 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_SCREEN_H +#define _LULZJS_NCURSES_SCREEN_H + +#include "common.h" + +extern JSBool exec (JSContext* cx); +extern JSBool Panel_initialize (JSContext* cx); + +extern JSBool Panel_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern void Panel_finalize (JSContext* cx, JSObject* object); + +static JSClass Panel_class = { + "Panel", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Panel_finalize +}; + +extern JSBool Panel_static_update (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + +static JSFunctionSpec Panel_methods[] = { + {NULL} +}; + +static JSFunctionSpec Panel_static_methods[] = { + {"update", Panel_static_update, 0, 0, 0}, + {NULL} +}; + +#endif diff --git a/src/Panel.js b/src/Panel.js new file mode 100644 index 0000000..1d17d9c --- /dev/null +++ b/src/Panel.js @@ -0,0 +1,35 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +Object.extend(ncurses.Panel.prototype, { + printChar: function (ch, options) { + if (options) this.__window.printChar(ch, options); + else this.__window.printChar(ch); + }, + + getChar: function (options) { + return (options + ? this.__window.getChar(options) + : this.__window.getChar()); + }, + + printString: function (str, options) { + if (options) this.__window.printString(str, options); + else this.__window.printString(str); + } +}); diff --git a/test/panel.js b/test/panel.js new file mode 100755 index 0000000..9d23b2a --- /dev/null +++ b/test/panel.js @@ -0,0 +1,8 @@ +#! /usr/bin/env ljs +require("ncurses"); + +var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var panel = new ncurses.Panel({x: 0, y: 0, width: 30, height: 10, border: true}); +screen.printString(panel.__window.getChar()); +screen.refresh(); +screen.getChar();
meh/lulzjs-ncurses
055c2a8a6af79b73415369e1148a17599ca04aab
Added ACS_*
diff --git a/src/ncurses.c b/src/ncurses.c index 267ca9b..0b96262 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,317 +1,397 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); JS_SetProperty(cx, Keys, "EndOfScreen", &property); property = INT_TO_JSVAL(KEY_EOL); JS_SetProperty(cx, Keys, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SF); JS_SetProperty(cx, Keys, "ScrollForward", &property); property = INT_TO_JSVAL(KEY_SR); JS_SetProperty(cx, Keys, "ScrollBackward", &property); property = INT_TO_JSVAL(KEY_NPAGE); JS_SetProperty(cx, Keys, "NextPage", &property); property = INT_TO_JSVAL(KEY_PPAGE); JS_SetProperty(cx, Keys, "PreviousPage", &property); property = INT_TO_JSVAL(KEY_STAB); JS_SetProperty(cx, Keys, "SetTab", &property); property = INT_TO_JSVAL(KEY_CTAB); JS_SetProperty(cx, Keys, "ClearTab", &property); property = INT_TO_JSVAL(KEY_CATAB); JS_SetProperty(cx, Keys, "ClearAllTabs", &property); property = INT_TO_JSVAL(KEY_ENTER); JS_SetProperty(cx, Keys, "Enter", &property); property = INT_TO_JSVAL(KEY_SRESET); JS_SetProperty(cx, Keys, "SoftReset", &property); property = INT_TO_JSVAL(KEY_RESET); JS_SetProperty(cx, Keys, "Reset", &property); property = INT_TO_JSVAL(KEY_PRINT); JS_SetProperty(cx, Keys, "Print", &property); property = INT_TO_JSVAL(KEY_LL); JS_SetProperty(cx, Keys, "Bottom", &property); property = INT_TO_JSVAL(KEY_A1); JS_SetProperty(cx, Keys, "UpperLeft", &property); property = INT_TO_JSVAL(KEY_A3); JS_SetProperty(cx, Keys, "UpperRight", &property); property = INT_TO_JSVAL(KEY_B2); JS_SetProperty(cx, Keys, "Center", &property); property = INT_TO_JSVAL(KEY_C1); JS_SetProperty(cx, Keys, "LowerLeft", &property); property = INT_TO_JSVAL(KEY_C3); JS_SetProperty(cx, Keys, "LowerRight", &property); property = INT_TO_JSVAL(KEY_BTAB); JS_SetProperty(cx, Keys, "BackTab", &property); property = INT_TO_JSVAL(KEY_BEG); JS_SetProperty(cx, Keys, "Beginning", &property); property = INT_TO_JSVAL(KEY_CANCEL); JS_SetProperty(cx, Keys, "Cancel", &property); property = INT_TO_JSVAL(KEY_CLOSE); JS_SetProperty(cx, Keys, "Close", &property); property = INT_TO_JSVAL(KEY_COMMAND); JS_SetProperty(cx, Keys, "Command", &property); property = INT_TO_JSVAL(KEY_COPY); JS_SetProperty(cx, Keys, "Copy", &property); property = INT_TO_JSVAL(KEY_CREATE); JS_SetProperty(cx, Keys, "Create", &property); property = INT_TO_JSVAL(KEY_END); JS_SetProperty(cx, Keys, "End", &property); property = INT_TO_JSVAL(KEY_EXIT); JS_SetProperty(cx, Keys, "Exit", &property); property = INT_TO_JSVAL(KEY_FIND); JS_SetProperty(cx, Keys, "Find", &property); property = INT_TO_JSVAL(KEY_HELP); JS_SetProperty(cx, Keys, "Help", &property); property = INT_TO_JSVAL(KEY_MARK); JS_SetProperty(cx, Keys, "Mark", &property); property = INT_TO_JSVAL(KEY_MESSAGE); JS_SetProperty(cx, Keys, "Message", &property); property = INT_TO_JSVAL(KEY_MOUSE); JS_SetProperty(cx, Keys, "Mouse", &property); property = INT_TO_JSVAL(KEY_MOVE); JS_SetProperty(cx, Keys, "Move", &property); property = INT_TO_JSVAL(KEY_NEXT); JS_SetProperty(cx, Keys, "Next", &property); property = INT_TO_JSVAL(KEY_OPEN); JS_SetProperty(cx, Keys, "Open", &property); property = INT_TO_JSVAL(KEY_OPTIONS); JS_SetProperty(cx, Keys, "Options", &property); property = INT_TO_JSVAL(KEY_PREVIOUS); JS_SetProperty(cx, Keys, "Previous", &property); property = INT_TO_JSVAL(KEY_REDO); JS_SetProperty(cx, Keys, "Redo", &property); property = INT_TO_JSVAL(KEY_REFERENCE); JS_SetProperty(cx, Keys, "Reference", &property); property = INT_TO_JSVAL(KEY_REFRESH); JS_SetProperty(cx, Keys, "Refresh", &property); property = INT_TO_JSVAL(KEY_REPLACE); JS_SetProperty(cx, Keys, "Replace", &property); property = INT_TO_JSVAL(KEY_RESIZE); JS_SetProperty(cx, Keys, "Resize", &property); property = INT_TO_JSVAL(KEY_RESTART); JS_SetProperty(cx, Keys, "Restart", &property); property = INT_TO_JSVAL(KEY_RESUME); JS_SetProperty(cx, Keys, "Resume", &property); property = INT_TO_JSVAL(KEY_SAVE); JS_SetProperty(cx, Keys, "Save", &property); property = INT_TO_JSVAL(KEY_SELECT); JS_SetProperty(cx, Keys, "Select", &property); property = INT_TO_JSVAL(KEY_SUSPEND); JS_SetProperty(cx, Keys, "Suspend", &property); property = INT_TO_JSVAL(KEY_UNDO); JS_SetProperty(cx, Keys, "Undo", &property); JSObject* Shifted = JS_NewObject(cx, NULL, NULL, NULL); jsval jsShifted = OBJECT_TO_JSVAL(Shifted); JS_SetProperty(cx, Keys, "Shifted", &jsShifted); property = INT_TO_JSVAL(KEY_SBEG); JS_SetProperty(cx, Shifted, "Beginning", &property); property = INT_TO_JSVAL(KEY_SCANCEL); JS_SetProperty(cx, Shifted, "Cancel", &property); property = INT_TO_JSVAL(KEY_SCOMMAND); JS_SetProperty(cx, Shifted, "Command", &property); property = INT_TO_JSVAL(KEY_SCOPY); JS_SetProperty(cx, Shifted, "Copy", &property); property = INT_TO_JSVAL(KEY_SCREATE); JS_SetProperty(cx, Shifted, "Create", &property); property = INT_TO_JSVAL(KEY_SDC); JS_SetProperty(cx, Shifted, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_SDL); JS_SetProperty(cx, Shifted, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_SEND); JS_SetProperty(cx, Shifted, "End", &property); property = INT_TO_JSVAL(KEY_SEOL); JS_SetProperty(cx, Shifted, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SEXIT); JS_SetProperty(cx, Shifted, "Exit", &property); property = INT_TO_JSVAL(KEY_SFIND); JS_SetProperty(cx, Shifted, "Find", &property); property = INT_TO_JSVAL(KEY_SHELP); JS_SetProperty(cx, Shifted, "Help", &property); property = INT_TO_JSVAL(KEY_SHOME); JS_SetProperty(cx, Shifted, "Home", &property); property = INT_TO_JSVAL(KEY_SIC); JS_SetProperty(cx, Shifted, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_SLEFT); JS_SetProperty(cx, Shifted, "Left", &property); property = INT_TO_JSVAL(KEY_SMESSAGE); JS_SetProperty(cx, Shifted, "Message", &property); property = INT_TO_JSVAL(KEY_SMOVE); JS_SetProperty(cx, Shifted, "Move", &property); property = INT_TO_JSVAL(KEY_SNEXT); JS_SetProperty(cx, Shifted, "Next", &property); property = INT_TO_JSVAL(KEY_SOPTIONS); JS_SetProperty(cx, Shifted, "Options", &property); property = INT_TO_JSVAL(KEY_SPREVIOUS); JS_SetProperty(cx, Shifted, "Previous", &property); property = INT_TO_JSVAL(KEY_SPRINT); JS_SetProperty(cx, Shifted, "Print", &property); property = INT_TO_JSVAL(KEY_SREDO); JS_SetProperty(cx, Shifted, "Redo", &property); property = INT_TO_JSVAL(KEY_SREPLACE); JS_SetProperty(cx, Shifted, "Replace", &property); property = INT_TO_JSVAL(KEY_SRIGHT); JS_SetProperty(cx, Shifted, "Right", &property); property = INT_TO_JSVAL(KEY_SRSUME); JS_SetProperty(cx, Shifted, "Resume", &property); property = INT_TO_JSVAL(KEY_SSAVE); JS_SetProperty(cx, Shifted, "Save", &property); property = INT_TO_JSVAL(KEY_SSUSPEND); JS_SetProperty(cx, Shifted, "Suspend", &property); property = INT_TO_JSVAL(KEY_SUNDO); JS_SetProperty(cx, Shifted, "Undo", &property); + JSObject* AlternativeChars = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsAlternativeChars = OBJECT_TO_JSVAL(AlternativeChars); + JS_SetProperty(cx, object, "AlternativeChars", &jsAlternativeChars); + property = INT_TO_JSVAL(ACS_BLOCK); + JS_SetProperty(cx, AlternativeChars, "Block", &property); + property = INT_TO_JSVAL(ACS_BOARD); + JS_SetProperty(cx, AlternativeChars, "Board", &property); + property = INT_TO_JSVAL(ACS_BTEE); + JS_SetProperty(cx, AlternativeChars, "BottomT", &property); + property = INT_TO_JSVAL(ACS_BULLET); + JS_SetProperty(cx, AlternativeChars, "Bullet", &property); + property = INT_TO_JSVAL(ACS_CKBOARD); + JS_SetProperty(cx, AlternativeChars, "CheckerBoard", &property); + property = INT_TO_JSVAL(ACS_DARROW); + JS_SetProperty(cx, AlternativeChars, "DownArrow", &property); + property = INT_TO_JSVAL(ACS_DEGREE); + JS_SetProperty(cx, AlternativeChars, "Degree", &property); + property = INT_TO_JSVAL(ACS_DIAMOND); + JS_SetProperty(cx, AlternativeChars, "Diamond", &property); + property = INT_TO_JSVAL(ACS_GEQUAL); + JS_SetProperty(cx, AlternativeChars, "GreaterEqual", &property); + property = INT_TO_JSVAL(ACS_HLINE); + JS_SetProperty(cx, AlternativeChars, "HorizontalLine", &property); + property = INT_TO_JSVAL(ACS_LANTERN); + JS_SetProperty(cx, AlternativeChars, "Lantern", &property); + property = INT_TO_JSVAL(ACS_LARROW); + JS_SetProperty(cx, AlternativeChars, "LeftArrow", &property); + property = INT_TO_JSVAL(ACS_LEQUAL); + JS_SetProperty(cx, AlternativeChars, "LessEqual", &property); + property = INT_TO_JSVAL(ACS_LLCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerLeftCorner", &property); + property = INT_TO_JSVAL(ACS_LRCORNER); + JS_SetProperty(cx, AlternativeChars, "LowerRightCorner", &property); + property = INT_TO_JSVAL(ACS_LTEE); + JS_SetProperty(cx, AlternativeChars, "LeftT", &property); + property = INT_TO_JSVAL(ACS_NEQUAL); + JS_SetProperty(cx, AlternativeChars, "NotEqual", &property); + property = INT_TO_JSVAL(ACS_PI); + JS_SetProperty(cx, AlternativeChars, "GreekPi", &property); + property = INT_TO_JSVAL(ACS_PLMINUS); + JS_SetProperty(cx, AlternativeChars, "PlusMinus", &property); + property = INT_TO_JSVAL(ACS_PLUS); + JS_SetProperty(cx, AlternativeChars, "Plus", &property); + property = INT_TO_JSVAL(ACS_RARROW); + JS_SetProperty(cx, AlternativeChars, "RightArrow", &property); + property = INT_TO_JSVAL(ACS_RTEE); + JS_SetProperty(cx, AlternativeChars, "RightT", &property); + property = INT_TO_JSVAL(ACS_S1); + JS_SetProperty(cx, AlternativeChars, "Scan1", &property); + property = INT_TO_JSVAL(ACS_S3); + JS_SetProperty(cx, AlternativeChars, "Scan3", &property); + property = INT_TO_JSVAL(ACS_S7); + JS_SetProperty(cx, AlternativeChars, "Scan7", &property); + property = INT_TO_JSVAL(ACS_S9); + JS_SetProperty(cx, AlternativeChars, "Scan9", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); + property = INT_TO_JSVAL(ACS_STERLING); + JS_SetProperty(cx, AlternativeChars, "Pound", &property); + property = INT_TO_JSVAL(ACS_TTEE); + JS_SetProperty(cx, AlternativeChars, "TopT", &property); + property = INT_TO_JSVAL(ACS_UARROW); + JS_SetProperty(cx, AlternativeChars, "UpperArrow", &property); + property = INT_TO_JSVAL(ACS_ULCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperLeftCorner", &property); + property = INT_TO_JSVAL(ACS_URCORNER); + JS_SetProperty(cx, AlternativeChars, "UpperRightCorner", &property); + property = INT_TO_JSVAL(ACS_VLINE); + JS_SetProperty(cx, AlternativeChars, "VerticalLine", &property); + return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); if (n < 0 || n > 63) { JS_ReportError(cx, "Out of range."); return JS_FALSE; } *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; }
meh/lulzjs-ncurses
13a85f4c4f7a128df837bf57e41b2febc185a3bb
Finished adding KEY_*
diff --git a/src/ncurses.c b/src/ncurses.c index 544345a..267ca9b 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,264 +1,317 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); JS_SetProperty(cx, Keys, "EndOfScreen", &property); property = INT_TO_JSVAL(KEY_EOL); JS_SetProperty(cx, Keys, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SF); JS_SetProperty(cx, Keys, "ScrollForward", &property); property = INT_TO_JSVAL(KEY_SR); JS_SetProperty(cx, Keys, "ScrollBackward", &property); property = INT_TO_JSVAL(KEY_NPAGE); JS_SetProperty(cx, Keys, "NextPage", &property); property = INT_TO_JSVAL(KEY_PPAGE); JS_SetProperty(cx, Keys, "PreviousPage", &property); property = INT_TO_JSVAL(KEY_STAB); JS_SetProperty(cx, Keys, "SetTab", &property); property = INT_TO_JSVAL(KEY_CTAB); JS_SetProperty(cx, Keys, "ClearTab", &property); property = INT_TO_JSVAL(KEY_CATAB); JS_SetProperty(cx, Keys, "ClearAllTabs", &property); property = INT_TO_JSVAL(KEY_ENTER); JS_SetProperty(cx, Keys, "Enter", &property); property = INT_TO_JSVAL(KEY_SRESET); JS_SetProperty(cx, Keys, "SoftReset", &property); property = INT_TO_JSVAL(KEY_RESET); JS_SetProperty(cx, Keys, "Reset", &property); property = INT_TO_JSVAL(KEY_PRINT); JS_SetProperty(cx, Keys, "Print", &property); property = INT_TO_JSVAL(KEY_LL); JS_SetProperty(cx, Keys, "Bottom", &property); property = INT_TO_JSVAL(KEY_A1); JS_SetProperty(cx, Keys, "UpperLeft", &property); property = INT_TO_JSVAL(KEY_A3); JS_SetProperty(cx, Keys, "UpperRight", &property); property = INT_TO_JSVAL(KEY_B2); JS_SetProperty(cx, Keys, "Center", &property); property = INT_TO_JSVAL(KEY_C1); JS_SetProperty(cx, Keys, "LowerLeft", &property); property = INT_TO_JSVAL(KEY_C3); JS_SetProperty(cx, Keys, "LowerRight", &property); property = INT_TO_JSVAL(KEY_BTAB); JS_SetProperty(cx, Keys, "BackTab", &property); property = INT_TO_JSVAL(KEY_BEG); JS_SetProperty(cx, Keys, "Beginning", &property); property = INT_TO_JSVAL(KEY_CANCEL); JS_SetProperty(cx, Keys, "Cancel", &property); property = INT_TO_JSVAL(KEY_CLOSE); JS_SetProperty(cx, Keys, "Close", &property); property = INT_TO_JSVAL(KEY_COMMAND); JS_SetProperty(cx, Keys, "Command", &property); property = INT_TO_JSVAL(KEY_COPY); JS_SetProperty(cx, Keys, "Copy", &property); property = INT_TO_JSVAL(KEY_CREATE); JS_SetProperty(cx, Keys, "Create", &property); property = INT_TO_JSVAL(KEY_END); JS_SetProperty(cx, Keys, "End", &property); property = INT_TO_JSVAL(KEY_EXIT); JS_SetProperty(cx, Keys, "Exit", &property); property = INT_TO_JSVAL(KEY_FIND); JS_SetProperty(cx, Keys, "Find", &property); property = INT_TO_JSVAL(KEY_HELP); JS_SetProperty(cx, Keys, "Help", &property); property = INT_TO_JSVAL(KEY_MARK); JS_SetProperty(cx, Keys, "Mark", &property); property = INT_TO_JSVAL(KEY_MESSAGE); JS_SetProperty(cx, Keys, "Message", &property); property = INT_TO_JSVAL(KEY_MOUSE); JS_SetProperty(cx, Keys, "Mouse", &property); property = INT_TO_JSVAL(KEY_MOVE); JS_SetProperty(cx, Keys, "Move", &property); property = INT_TO_JSVAL(KEY_NEXT); JS_SetProperty(cx, Keys, "Next", &property); property = INT_TO_JSVAL(KEY_OPEN); JS_SetProperty(cx, Keys, "Open", &property); property = INT_TO_JSVAL(KEY_OPTIONS); JS_SetProperty(cx, Keys, "Options", &property); property = INT_TO_JSVAL(KEY_PREVIOUS); JS_SetProperty(cx, Keys, "Previous", &property); property = INT_TO_JSVAL(KEY_REDO); JS_SetProperty(cx, Keys, "Redo", &property); property = INT_TO_JSVAL(KEY_REFERENCE); JS_SetProperty(cx, Keys, "Reference", &property); property = INT_TO_JSVAL(KEY_REFRESH); JS_SetProperty(cx, Keys, "Refresh", &property); property = INT_TO_JSVAL(KEY_REPLACE); JS_SetProperty(cx, Keys, "Replace", &property); property = INT_TO_JSVAL(KEY_RESIZE); JS_SetProperty(cx, Keys, "Resize", &property); property = INT_TO_JSVAL(KEY_RESTART); JS_SetProperty(cx, Keys, "Restart", &property); property = INT_TO_JSVAL(KEY_RESUME); JS_SetProperty(cx, Keys, "Resume", &property); property = INT_TO_JSVAL(KEY_SAVE); JS_SetProperty(cx, Keys, "Save", &property); property = INT_TO_JSVAL(KEY_SELECT); JS_SetProperty(cx, Keys, "Select", &property); property = INT_TO_JSVAL(KEY_SUSPEND); JS_SetProperty(cx, Keys, "Suspend", &property); property = INT_TO_JSVAL(KEY_UNDO); JS_SetProperty(cx, Keys, "Undo", &property); JSObject* Shifted = JS_NewObject(cx, NULL, NULL, NULL); jsval jsShifted = OBJECT_TO_JSVAL(Shifted); - JS_SetProperty(cx, Keys, "Shifted", &property); + JS_SetProperty(cx, Keys, "Shifted", &jsShifted); property = INT_TO_JSVAL(KEY_SBEG); JS_SetProperty(cx, Shifted, "Beginning", &property); property = INT_TO_JSVAL(KEY_SCANCEL); + JS_SetProperty(cx, Shifted, "Cancel", &property); + property = INT_TO_JSVAL(KEY_SCOMMAND); + JS_SetProperty(cx, Shifted, "Command", &property); + property = INT_TO_JSVAL(KEY_SCOPY); + JS_SetProperty(cx, Shifted, "Copy", &property); + property = INT_TO_JSVAL(KEY_SCREATE); + JS_SetProperty(cx, Shifted, "Create", &property); + property = INT_TO_JSVAL(KEY_SDC); + JS_SetProperty(cx, Shifted, "DeleteChar", &property); + property = INT_TO_JSVAL(KEY_SDL); + JS_SetProperty(cx, Shifted, "DeleteLine", &property); + property = INT_TO_JSVAL(KEY_SEND); + JS_SetProperty(cx, Shifted, "End", &property); + property = INT_TO_JSVAL(KEY_SEOL); + JS_SetProperty(cx, Shifted, "EndOfLine", &property); + property = INT_TO_JSVAL(KEY_SEXIT); + JS_SetProperty(cx, Shifted, "Exit", &property); + property = INT_TO_JSVAL(KEY_SFIND); + JS_SetProperty(cx, Shifted, "Find", &property); + property = INT_TO_JSVAL(KEY_SHELP); + JS_SetProperty(cx, Shifted, "Help", &property); + property = INT_TO_JSVAL(KEY_SHOME); + JS_SetProperty(cx, Shifted, "Home", &property); + property = INT_TO_JSVAL(KEY_SIC); + JS_SetProperty(cx, Shifted, "EnterInsertMode", &property); + property = INT_TO_JSVAL(KEY_SLEFT); + JS_SetProperty(cx, Shifted, "Left", &property); + property = INT_TO_JSVAL(KEY_SMESSAGE); + JS_SetProperty(cx, Shifted, "Message", &property); + property = INT_TO_JSVAL(KEY_SMOVE); + JS_SetProperty(cx, Shifted, "Move", &property); + property = INT_TO_JSVAL(KEY_SNEXT); + JS_SetProperty(cx, Shifted, "Next", &property); + property = INT_TO_JSVAL(KEY_SOPTIONS); + JS_SetProperty(cx, Shifted, "Options", &property); + property = INT_TO_JSVAL(KEY_SPREVIOUS); + JS_SetProperty(cx, Shifted, "Previous", &property); + property = INT_TO_JSVAL(KEY_SPRINT); + JS_SetProperty(cx, Shifted, "Print", &property); + property = INT_TO_JSVAL(KEY_SREDO); + JS_SetProperty(cx, Shifted, "Redo", &property); + property = INT_TO_JSVAL(KEY_SREPLACE); + JS_SetProperty(cx, Shifted, "Replace", &property); + property = INT_TO_JSVAL(KEY_SRIGHT); + JS_SetProperty(cx, Shifted, "Right", &property); + property = INT_TO_JSVAL(KEY_SRSUME); + JS_SetProperty(cx, Shifted, "Resume", &property); + property = INT_TO_JSVAL(KEY_SSAVE); + JS_SetProperty(cx, Shifted, "Save", &property); + property = INT_TO_JSVAL(KEY_SSUSPEND); + JS_SetProperty(cx, Shifted, "Suspend", &property); + property = INT_TO_JSVAL(KEY_SUNDO); + JS_SetProperty(cx, Shifted, "Undo", &property); return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); if (n < 0 || n > 63) { JS_ReportError(cx, "Out of range."); return JS_FALSE; } *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; }
meh/lulzjs-ncurses
8bb6e96bbe33836943460d143b0c2e4974945a7f
More keys ._. boooring
diff --git a/src/ncurses.c b/src/ncurses.c index 009e815..544345a 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,200 +1,264 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); JS_SetProperty(cx, Keys, "EndOfScreen", &property); property = INT_TO_JSVAL(KEY_EOL); JS_SetProperty(cx, Keys, "EndOfLine", &property); property = INT_TO_JSVAL(KEY_SF); JS_SetProperty(cx, Keys, "ScrollForward", &property); property = INT_TO_JSVAL(KEY_SR); JS_SetProperty(cx, Keys, "ScrollBackward", &property); property = INT_TO_JSVAL(KEY_NPAGE); JS_SetProperty(cx, Keys, "NextPage", &property); property = INT_TO_JSVAL(KEY_PPAGE); JS_SetProperty(cx, Keys, "PreviousPage", &property); property = INT_TO_JSVAL(KEY_STAB); JS_SetProperty(cx, Keys, "SetTab", &property); property = INT_TO_JSVAL(KEY_CTAB); JS_SetProperty(cx, Keys, "ClearTab", &property); property = INT_TO_JSVAL(KEY_CATAB); JS_SetProperty(cx, Keys, "ClearAllTabs", &property); property = INT_TO_JSVAL(KEY_ENTER); JS_SetProperty(cx, Keys, "Enter", &property); property = INT_TO_JSVAL(KEY_SRESET); JS_SetProperty(cx, Keys, "SoftReset", &property); property = INT_TO_JSVAL(KEY_RESET); JS_SetProperty(cx, Keys, "Reset", &property); property = INT_TO_JSVAL(KEY_PRINT); JS_SetProperty(cx, Keys, "Print", &property); property = INT_TO_JSVAL(KEY_LL); JS_SetProperty(cx, Keys, "Bottom", &property); property = INT_TO_JSVAL(KEY_A1); JS_SetProperty(cx, Keys, "UpperLeft", &property); property = INT_TO_JSVAL(KEY_A3); JS_SetProperty(cx, Keys, "UpperRight", &property); property = INT_TO_JSVAL(KEY_B2); JS_SetProperty(cx, Keys, "Center", &property); property = INT_TO_JSVAL(KEY_C1); JS_SetProperty(cx, Keys, "LowerLeft", &property); property = INT_TO_JSVAL(KEY_C3); JS_SetProperty(cx, Keys, "LowerRight", &property); property = INT_TO_JSVAL(KEY_BTAB); JS_SetProperty(cx, Keys, "BackTab", &property); + property = INT_TO_JSVAL(KEY_BEG); + JS_SetProperty(cx, Keys, "Beginning", &property); + property = INT_TO_JSVAL(KEY_CANCEL); + JS_SetProperty(cx, Keys, "Cancel", &property); + property = INT_TO_JSVAL(KEY_CLOSE); + JS_SetProperty(cx, Keys, "Close", &property); + property = INT_TO_JSVAL(KEY_COMMAND); + JS_SetProperty(cx, Keys, "Command", &property); + property = INT_TO_JSVAL(KEY_COPY); + JS_SetProperty(cx, Keys, "Copy", &property); + property = INT_TO_JSVAL(KEY_CREATE); + JS_SetProperty(cx, Keys, "Create", &property); + property = INT_TO_JSVAL(KEY_END); + JS_SetProperty(cx, Keys, "End", &property); + property = INT_TO_JSVAL(KEY_EXIT); + JS_SetProperty(cx, Keys, "Exit", &property); + property = INT_TO_JSVAL(KEY_FIND); + JS_SetProperty(cx, Keys, "Find", &property); + property = INT_TO_JSVAL(KEY_HELP); + JS_SetProperty(cx, Keys, "Help", &property); + property = INT_TO_JSVAL(KEY_MARK); + JS_SetProperty(cx, Keys, "Mark", &property); + property = INT_TO_JSVAL(KEY_MESSAGE); + JS_SetProperty(cx, Keys, "Message", &property); + property = INT_TO_JSVAL(KEY_MOUSE); + JS_SetProperty(cx, Keys, "Mouse", &property); + property = INT_TO_JSVAL(KEY_MOVE); + JS_SetProperty(cx, Keys, "Move", &property); + property = INT_TO_JSVAL(KEY_NEXT); + JS_SetProperty(cx, Keys, "Next", &property); + property = INT_TO_JSVAL(KEY_OPEN); + JS_SetProperty(cx, Keys, "Open", &property); + property = INT_TO_JSVAL(KEY_OPTIONS); + JS_SetProperty(cx, Keys, "Options", &property); + property = INT_TO_JSVAL(KEY_PREVIOUS); + JS_SetProperty(cx, Keys, "Previous", &property); + property = INT_TO_JSVAL(KEY_REDO); + JS_SetProperty(cx, Keys, "Redo", &property); + property = INT_TO_JSVAL(KEY_REFERENCE); + JS_SetProperty(cx, Keys, "Reference", &property); + property = INT_TO_JSVAL(KEY_REFRESH); + JS_SetProperty(cx, Keys, "Refresh", &property); + property = INT_TO_JSVAL(KEY_REPLACE); + JS_SetProperty(cx, Keys, "Replace", &property); + property = INT_TO_JSVAL(KEY_RESIZE); + JS_SetProperty(cx, Keys, "Resize", &property); + property = INT_TO_JSVAL(KEY_RESTART); + JS_SetProperty(cx, Keys, "Restart", &property); + property = INT_TO_JSVAL(KEY_RESUME); + JS_SetProperty(cx, Keys, "Resume", &property); + property = INT_TO_JSVAL(KEY_SAVE); + JS_SetProperty(cx, Keys, "Save", &property); + property = INT_TO_JSVAL(KEY_SELECT); + JS_SetProperty(cx, Keys, "Select", &property); + property = INT_TO_JSVAL(KEY_SUSPEND); + JS_SetProperty(cx, Keys, "Suspend", &property); + property = INT_TO_JSVAL(KEY_UNDO); + JS_SetProperty(cx, Keys, "Undo", &property); + JSObject* Shifted = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsShifted = OBJECT_TO_JSVAL(Shifted); + JS_SetProperty(cx, Keys, "Shifted", &property); + property = INT_TO_JSVAL(KEY_SBEG); + JS_SetProperty(cx, Shifted, "Beginning", &property); + property = INT_TO_JSVAL(KEY_SCANCEL); return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); if (n < 0 || n > 63) { JS_ReportError(cx, "Out of range."); return JS_FALSE; } *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; }
meh/lulzjs-ncurses
c288308e8bbb61c82bc6c763f68fc60aee3d7d41
Adding keys.
diff --git a/src/ncurses.c b/src/ncurses.c index b1644da..009e815 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,156 +1,200 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); jsval jsKeys = OBJECT_TO_JSVAL(Keys); JS_SetProperty(cx, object, "Keys", &jsKeys); property = INT_TO_JSVAL(KEY_BREAK); JS_SetProperty(cx, Keys, "Break", &property); property = INT_TO_JSVAL(KEY_DOWN); JS_SetProperty(cx, Keys, "Down", &property); property = INT_TO_JSVAL(KEY_UP); JS_SetProperty(cx, Keys, "Up", &property); property = INT_TO_JSVAL(KEY_LEFT); JS_SetProperty(cx, Keys, "Left", &property); property = INT_TO_JSVAL(KEY_RIGHT); JS_SetProperty(cx, Keys, "Right", &property); property = INT_TO_JSVAL(KEY_HOME); JS_SetProperty(cx, Keys, "Home", &property); property = INT_TO_JSVAL(KEY_BACKSPACE); JS_SetProperty(cx, Keys, "Backspace", &property); property = OBJECT_TO_JSVAL(JS_GetFunctionObject( JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") )); JS_SetProperty(cx, Keys, "F", &property); property = INT_TO_JSVAL(KEY_DL); - JS_SetProperty(cx, Keys, "DL", &property); + JS_SetProperty(cx, Keys, "DeleteLine", &property); property = INT_TO_JSVAL(KEY_IL); - JS_SetProperty(cx, Keys, "IL", &property); + JS_SetProperty(cx, Keys, "InsertLine", &property); property = INT_TO_JSVAL(KEY_DC); - JS_SetProperty(cx, Keys, "DC", &property); + JS_SetProperty(cx, Keys, "DeleteChar", &property); property = INT_TO_JSVAL(KEY_IC); - JS_SetProperty(cx, Keys, "IC", &property); + JS_SetProperty(cx, Keys, "EnterInsertMode", &property); property = INT_TO_JSVAL(KEY_EIC); - JS_SetProperty(cx, Keys, "EIC", &property); + JS_SetProperty(cx, Keys, "EndInsertMode", &property); property = INT_TO_JSVAL(KEY_CLEAR); JS_SetProperty(cx, Keys, "Clear", &property); property = INT_TO_JSVAL(KEY_EOS); - JS_SetProperty(cx, Keys, "EOS", &property); + JS_SetProperty(cx, Keys, "EndOfScreen", &property); + property = INT_TO_JSVAL(KEY_EOL); + JS_SetProperty(cx, Keys, "EndOfLine", &property); + property = INT_TO_JSVAL(KEY_SF); + JS_SetProperty(cx, Keys, "ScrollForward", &property); + property = INT_TO_JSVAL(KEY_SR); + JS_SetProperty(cx, Keys, "ScrollBackward", &property); + property = INT_TO_JSVAL(KEY_NPAGE); + JS_SetProperty(cx, Keys, "NextPage", &property); + property = INT_TO_JSVAL(KEY_PPAGE); + JS_SetProperty(cx, Keys, "PreviousPage", &property); + property = INT_TO_JSVAL(KEY_STAB); + JS_SetProperty(cx, Keys, "SetTab", &property); + property = INT_TO_JSVAL(KEY_CTAB); + JS_SetProperty(cx, Keys, "ClearTab", &property); + property = INT_TO_JSVAL(KEY_CATAB); + JS_SetProperty(cx, Keys, "ClearAllTabs", &property); + property = INT_TO_JSVAL(KEY_ENTER); + JS_SetProperty(cx, Keys, "Enter", &property); + property = INT_TO_JSVAL(KEY_SRESET); + JS_SetProperty(cx, Keys, "SoftReset", &property); + property = INT_TO_JSVAL(KEY_RESET); + JS_SetProperty(cx, Keys, "Reset", &property); + property = INT_TO_JSVAL(KEY_PRINT); + JS_SetProperty(cx, Keys, "Print", &property); + property = INT_TO_JSVAL(KEY_LL); + JS_SetProperty(cx, Keys, "Bottom", &property); + property = INT_TO_JSVAL(KEY_A1); + JS_SetProperty(cx, Keys, "UpperLeft", &property); + property = INT_TO_JSVAL(KEY_A3); + JS_SetProperty(cx, Keys, "UpperRight", &property); + property = INT_TO_JSVAL(KEY_B2); + JS_SetProperty(cx, Keys, "Center", &property); + property = INT_TO_JSVAL(KEY_C1); + JS_SetProperty(cx, Keys, "LowerLeft", &property); + property = INT_TO_JSVAL(KEY_C3); + JS_SetProperty(cx, Keys, "LowerRight", &property); + property = INT_TO_JSVAL(KEY_BTAB); + JS_SetProperty(cx, Keys, "BackTab", &property); return JS_TRUE; } return JS_FALSE; } JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } jsint n; JS_ValueToInt32(cx, argv[0], &n); + + if (n < 0 || n > 63) { + JS_ReportError(cx, "Out of range."); + return JS_FALSE; + } + *rval = INT_TO_JSVAL(KEY_F(n)); return JS_TRUE; }
meh/lulzjs-ncurses
c92f2d3c37db75d851df2563087dadaf3d6ebe06
Additions.
diff --git a/src/Window.c b/src/Window.c index ad25b65..dbfef75 100644 --- a/src/Window.c +++ b/src/Window.c @@ -1,306 +1,312 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Window.h" JSBool exec (JSContext* cx) { return Window_initialize(cx); } JSBool Window_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Window_class, Window_constructor, 1, NULL, Window_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* parent; JSObject* options; jsval x, y, width, height; jsint offset = 0; if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } if (argc == 2) { JS_ValueToObject(cx, argv[0], &parent); if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { JS_ReportError(cx, "You have to pass a Window object."); return JS_FALSE; } offset = 1; } jsval val; JS_ValueToObject(cx, argv[offset], &options); JS_GetProperty(cx, options, "width", &width); JS_GetProperty(cx, options, "height", &height); JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } WINDOW* win = JS_malloc(cx, sizeof(WINDOW)); if (argc == 2) { WINDOW* parentWin = JS_GetPrivate(cx, parent); win = subwin(parentWin, JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } else { win = newwin( JSVAL_TO_INT(height), JSVAL_TO_INT(width), JSVAL_TO_INT(y), JSVAL_TO_INT(x) ); } JS_SetPrivate(cx, object, win); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Window_updateSize(cx, object); JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); jsval jsPosition = OBJECT_TO_JSVAL(Position); JS_SetProperty(cx, object, "Position", &jsPosition); __Window_updatePosition(cx, object); + jsval jsBorder; JS_GetProperty(cx, options, "border", &jsBorder); + JSBool border; JS_ValueToBoolean(cx, jsBorder, &border); + if (border) { + box(win, 0, 0); + } + wrefresh(win); return JS_TRUE; } void Window_finalize (JSContext* cx, JSObject* object) { WINDOW* win = JS_GetPrivate(cx, object); if (win) { JS_free(cx, win); } } JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { WINDOW* win = JS_GetPrivate(cx, object); wrefresh(win); return JS_TRUE; } JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc != 2 && argc != 0) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); switch (argc) { case 0: { wrefresh(win); } break; case 2: { jsint beg; JS_ValueToInt32(cx, argv[0], &beg); jsint num; JS_ValueToInt32(cx, argv[1], &num); wredrawln(win, beg, num); } break; } return JS_TRUE; } JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); jsint ch; JS_ValueToInt32(cx, argv[0], &ch); if (argc == 1){ waddch(win, ch); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); __options(cx, win, options, JS_TRUE); if (echo) { wechochar(win, ch); } else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { waddch(win, ch); } else { mvwaddch(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, ch ); } __options(cx, win, options, JS_FALSE); } return JS_TRUE; } JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; WINDOW* win = JS_GetPrivate(cx, object); if (argc == 0) { *rval = INT_TO_JSVAL(wgetch(win)); } else { JS_ValueToObject(cx, argv[0], &options); if (!options) { JS_ReportError(cx, "Options isn't a valid object."); return JS_FALSE; } jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { JS_ReportError(cx, "An option is missing or isn't an int."); return JS_FALSE; } *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); } return JS_TRUE; } JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } WINDOW* win = JS_GetPrivate(cx, object); if (argc == 1){ wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else if (argc == 2) { JSObject* options; JS_ValueToObject(cx, argv[1], &options); jsval x, y; JS_GetProperty(cx, options, "x", &x); JS_GetProperty(cx, options, "y", &y); __options(cx, win, options, JS_TRUE); if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } else { mvwprintw(win, JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, JS_GetStringBytes(JS_ValueToString(cx, argv[0])) ); } __options(cx, win, options, JS_FALSE); } return JS_TRUE; } void __Window_updateSize (JSContext* cx, JSObject* object) { int height, width; WINDOW* win = JS_GetPrivate(cx, object); getmaxyx(win, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } void __Window_updatePosition (JSContext* cx, JSObject* object) { int y, x; WINDOW* win = JS_GetPrivate(cx, object); getbegyx(win, y, x); jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); JSObject* Position = JSVAL_TO_OBJECT(jsPosition); jsval property; property = INT_TO_JSVAL(y); JS_SetProperty(cx, Position, "Y", &property); property = INT_TO_JSVAL(x); JS_SetProperty(cx, Position, "X", &property); } diff --git a/src/ncurses.c b/src/ncurses.c index 58ce7d1..b1644da 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,106 +1,156 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); jsval jsCursor = OBJECT_TO_JSVAL(Cursor); JS_SetProperty(cx, object, "Cursor", &jsCursor); property = INT_TO_JSVAL(0); JS_SetProperty(cx, Cursor, "Invisible", &property); property = INT_TO_JSVAL(1); JS_SetProperty(cx, Cursor, "Normal", &property); property = INT_TO_JSVAL(2); JS_SetProperty(cx, Cursor, "Visible", &property); + JSObject* Keys = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsKeys = OBJECT_TO_JSVAL(Keys); + JS_SetProperty(cx, object, "Keys", &jsKeys); + property = INT_TO_JSVAL(KEY_BREAK); + JS_SetProperty(cx, Keys, "Break", &property); + property = INT_TO_JSVAL(KEY_DOWN); + JS_SetProperty(cx, Keys, "Down", &property); + property = INT_TO_JSVAL(KEY_UP); + JS_SetProperty(cx, Keys, "Up", &property); + property = INT_TO_JSVAL(KEY_LEFT); + JS_SetProperty(cx, Keys, "Left", &property); + property = INT_TO_JSVAL(KEY_RIGHT); + JS_SetProperty(cx, Keys, "Right", &property); + property = INT_TO_JSVAL(KEY_HOME); + JS_SetProperty(cx, Keys, "Home", &property); + property = INT_TO_JSVAL(KEY_BACKSPACE); + JS_SetProperty(cx, Keys, "Backspace", &property); + property = OBJECT_TO_JSVAL(JS_GetFunctionObject( + JS_NewFunction(cx, ncurses_KEY_F, 1, 0, NULL, "KEY_F") + )); + JS_SetProperty(cx, Keys, "F", &property); + property = INT_TO_JSVAL(KEY_DL); + JS_SetProperty(cx, Keys, "DL", &property); + property = INT_TO_JSVAL(KEY_IL); + JS_SetProperty(cx, Keys, "IL", &property); + property = INT_TO_JSVAL(KEY_DC); + JS_SetProperty(cx, Keys, "DC", &property); + property = INT_TO_JSVAL(KEY_IC); + JS_SetProperty(cx, Keys, "IC", &property); + property = INT_TO_JSVAL(KEY_EIC); + JS_SetProperty(cx, Keys, "EIC", &property); + property = INT_TO_JSVAL(KEY_CLEAR); + JS_SetProperty(cx, Keys, "Clear", &property); + property = INT_TO_JSVAL(KEY_EOS); + JS_SetProperty(cx, Keys, "EOS", &property); + return JS_TRUE; } return JS_FALSE; } +JSBool +ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + jsint n; JS_ValueToInt32(cx, argv[0], &n); + *rval = INT_TO_JSVAL(KEY_F(n)); + + return JS_TRUE; +} + diff --git a/src/ncurses.h b/src/ncurses.h index d444b20..977af82 100644 --- a/src/ncurses.h +++ b/src/ncurses.h @@ -1,38 +1,40 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_H #define _LULZJS_NCURSES_H #include "common.h" #include "Screen.h" extern JSBool exec (JSContext* cx); extern JSBool ncurses_initialize (JSContext* cx); static JSClass ncurses_class = { "ncurses", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; +extern JSBool ncurses_KEY_F (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + static JSFunctionSpec ncurses_methods[] = { {NULL} }; #endif diff --git a/test/window.js b/test/window.js index cc93657..ee2d93f 100755 --- a/test/window.js +++ b/test/window.js @@ -1,8 +1,8 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); -var win = new ncurses.Window({x: 2, y: 2, width: 40, height: 10}); +var win = new ncurses.Window({x: 2, y: 2, width: 40, height: 10, border: true}); win.printString("LOLNIGGERS", {x: 10, y: 4, fg: ncurses.Colors.Blue}); win.printChar(win.getChar(), {x: 2, y: 2}) win.getChar();
meh/lulzjs-ncurses
7eca075a6cecb34d11a27f7259d0ba36ab43336f
Bawwwww
diff --git a/Makefile b/Makefile index 0802650..31ad884 100644 --- a/Makefile +++ b/Makefile @@ -1,50 +1,51 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" -I/usr/include/js -I./src LDFLAGS = -ljs -llulzjs ifdef DEBUG CFLAGS += -g endif ifdef DDEBUG CFLAGS += -DDEBUG -g endif LIB_DIR = src -LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o +LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o ${LIB_DIR}/Window.o LIB_CFLAGS = ${CFLAGS} LIB_LDFLAGS = ${LDFLAGS} -lncurses -lpanel -lform -lmenu all: lib lib: $(LIB) $(LIB) : $(LIB:.o=.c) ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js + cp -f ${LIB_DIR}/Window.o ${LJS_LIBDIR}/ncurses/Window.so cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses lib_uninstall: rm -rf ${LJS_LIBDIR}/ncurses install: lib_install uninstall: lib_uninstall clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Screen.c b/src/Screen.c index 1c71992..deb2390 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,300 +1,209 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { endwin(); initscr(); refresh(); __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, - Screen_constructor, 1, NULL, Screen_methods, NULL, Screen_static_methods + Screen_constructor, 1, NULL, Screen_methods, NULL, NULL ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { - JS_ReportError(cx, "You can have only one Screen per program."); + JS_ReportError(cx, "You can have only one Screen per program. (At the moment :3)"); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); + jsval property; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &property); + JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "Window",&property); + JSClass* class = JS_GET_CLASS(cx, JSVAL_TO_OBJECT(property)); + JS_GetProperty(cx, JSVAL_TO_OBJECT(property), "prototype", &property); + JSObject* proto = JSVAL_TO_OBJECT(property); + + JSObject* Window = JS_NewObject(cx, class, proto, NULL); + JS_SetPrivate(cx, Window, stdscr); + property = OBJECT_TO_JSVAL(Window); + JS_SetProperty(cx, object, "__window", &property); + if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } + curs_set(1); endwin(); JS_free(cx, data); } } -JSBool -Screen_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) -{ - refresh(); - return JS_TRUE; -} - -JSBool -Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) -{ - *rval = INT_TO_JSVAL(getch()); - return JS_TRUE; -} - -JSBool -Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) -{ - if (argc < 1) { - JS_ReportError(cx, "Not enough parameters."); - return JS_FALSE; - } - - switch (argc) { - case 1: { - printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); - } break; - - case 2: { - JSObject* options; JS_ValueToObject(cx, argv[1], &options); - - __Screen_options(cx, options, JS_TRUE); - printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); - __Screen_options(cx, options, JS_FALSE); - } break; - - case 3: { - jsint x; JS_ValueToInt32(cx, argv[1], &x); - jsint y; JS_ValueToInt32(cx, argv[2], &y); - - mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); - } break; - - case 4: { - JSObject* options; JS_ValueToObject(cx, argv[3], &options); - jsint x; JS_ValueToInt32(cx, argv[1], &x); - jsint y; JS_ValueToInt32(cx, argv[2], &y); - - __Screen_options(cx, options, JS_TRUE); - mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); - __Screen_options(cx, options, JS_FALSE); - } break; - } - - return JS_TRUE; -} - -void -__Screen_options (JSContext* cx, JSObject* options, JSBool apply) -{ - jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); - if (!JSVAL_IS_INT(jsAttrs)) { - JS_GetProperty(cx, options, "attribute", &jsAttrs); - - if (!JSVAL_IS_INT(jsAttrs)) { - JS_GetProperty(cx, options, "attributes", &jsAttrs); - } - } - - if (JSVAL_IS_INT(jsAttrs)) { - if (apply) { - attron(JSVAL_TO_INT(jsAttrs)); - } - else { - attroff(JSVAL_TO_INT(jsAttrs)); - } - } - - jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); - if (!JSVAL_IS_INT(jsForeground)) { - JS_GetProperty(cx, options, "foreground", &jsForeground); - } - - jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); - if (!JSVAL_IS_INT(jsBackground)) { - JS_GetProperty(cx, options, "background", &jsBackground); - } - - short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; - short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; - - char pair[3] = {0}; - sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default - sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 - - short c_pair = atoi(pair); - if (apply) { - init_pair(c_pair, fg, bg); - attron(COLOR_PAIR(c_pair)); - } - else { - attroff(COLOR_PAIR(c_pair)); - } -} - void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } diff --git a/src/Screen.h b/src/Screen.h index 29f1ae9..cd97674 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,66 +1,50 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include <signal.h> void __Screen_resize (int signum); extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" -extern JSBool Screen_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); - -extern JSBool Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); - -extern JSBool Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); -void __Screen_options (JSContext* cx, JSObject* options, JSBool apply); - extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); void __Screen_updateSize (JSContext* cx, JSObject* object); static JSFunctionSpec Screen_methods[] = { - {"refresh", Screen_refresh, 0, 0, 0}, - - {"getChar", Screen_getChar, 0, 0, 0}, - {"print", Screen_print, 0, 0, 0}, - {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; -static JSFunctionSpec Screen_static_methods[] = { - {NULL} -}; - #endif diff --git a/src/Screen.js b/src/Screen.js index e424044..ca6c030 100644 --- a/src/Screen.js +++ b/src/Screen.js @@ -1,28 +1,35 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Screen.prototype, { - printLine: function () { - switch (arguments.length) { - case 1: this.print(arguments[0]+"\n"); break; - case 2: this.print(arguments[0]+"\n", arguments[1]); break; - case 3: this.print(arguments[0]+"\n", arguments[1], arguments[2]); break; - case 4: this.print(arguments[0]+"\n", arguments[1], arguments[2], arguments[3]); break; - } + printChar: function (ch, options) { + if (options) this.__window.printChar(ch, options); + else this.__window.printChar(ch); + }, + + getChar: function (options) { + return (options + ? this.__window.getChar(options) + : this.__window.getChar()); + }, + + printString: function (str, options) { + if (options) this.__window.printString(str, options); + else this.__window.printString(str); } }); diff --git a/src/Window.c b/src/Window.c new file mode 100644 index 0000000..ad25b65 --- /dev/null +++ b/src/Window.c @@ -0,0 +1,306 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#include "Window.h" + +JSBool exec (JSContext* cx) { return Window_initialize(cx); } + +JSBool +Window_initialize (JSContext* cx) +{ + jsval jsParent; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); + JSObject* parent = JSVAL_TO_OBJECT(jsParent); + + JSObject* object = JS_InitClass( + cx, parent, NULL, &Window_class, + Window_constructor, 1, NULL, Window_methods, NULL, NULL + ); + + if (object) { + // Default properties + jsval property; + + return JS_TRUE; + } + + return JS_FALSE; +} + +JSBool +Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* parent; + JSObject* options; + jsval x, y, width, height; + jsint offset = 0; + + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + if (argc == 2) { + JS_ValueToObject(cx, argv[0], &parent); + + if (!JS_OBJECT_IS(cx, OBJECT_TO_JSVAL(parent), "ncurses.Window")) { + JS_ReportError(cx, "You have to pass a Window object."); + return JS_FALSE; + } + + offset = 1; + } + + jsval val; + JS_ValueToObject(cx, argv[offset], &options); + JS_GetProperty(cx, options, "width", &width); + JS_GetProperty(cx, options, "height", &height); + JS_GetProperty(cx, options, "x", &x); + JS_GetProperty(cx, options, "y", &y); + + if (!JSVAL_IS_INT(width) || !JSVAL_IS_INT(height) || !JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { + JS_ReportError(cx, "An option is missing or isn't an int."); + return JS_FALSE; + } + + WINDOW* win = JS_malloc(cx, sizeof(WINDOW)); + if (argc == 2) { + WINDOW* parentWin = JS_GetPrivate(cx, parent); + win = subwin(parentWin, + JSVAL_TO_INT(height), JSVAL_TO_INT(width), + JSVAL_TO_INT(y), JSVAL_TO_INT(x) + ); + } + else { + win = newwin( + JSVAL_TO_INT(height), JSVAL_TO_INT(width), + JSVAL_TO_INT(y), JSVAL_TO_INT(x) + ); + } + JS_SetPrivate(cx, object, win); + + JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsSize = OBJECT_TO_JSVAL(Size); + JS_SetProperty(cx, object, "Size", &jsSize); + __Window_updateSize(cx, object); + + JSObject* Position = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsPosition = OBJECT_TO_JSVAL(Position); + JS_SetProperty(cx, object, "Position", &jsPosition); + __Window_updatePosition(cx, object); + + wrefresh(win); + + return JS_TRUE; +} + +void +Window_finalize (JSContext* cx, JSObject* object) +{ + WINDOW* win = JS_GetPrivate(cx, object); + + if (win) { + JS_free(cx, win); + } +} + +JSBool +Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + WINDOW* win = JS_GetPrivate(cx, object); + + wrefresh(win); + return JS_TRUE; +} + +JSBool +Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + if (argc != 2 && argc != 0) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + WINDOW* win = JS_GetPrivate(cx, object); + + switch (argc) { + case 0: { + wrefresh(win); + } break; + + case 2: { + jsint beg; JS_ValueToInt32(cx, argv[0], &beg); + jsint num; JS_ValueToInt32(cx, argv[1], &num); + + wredrawln(win, beg, num); + } break; + } + + return JS_TRUE; + +} + +JSBool +Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + WINDOW* win = JS_GetPrivate(cx, object); + + jsint ch; JS_ValueToInt32(cx, argv[0], &ch); + + if (argc == 1){ + waddch(win, ch); + } + else if (argc == 2) { + JSObject* options; JS_ValueToObject(cx, argv[1], &options); + + jsval x, y; + JS_GetProperty(cx, options, "x", &x); + JS_GetProperty(cx, options, "y", &y); + + jsval jsEcho; JS_GetProperty(cx, options, "echo", &jsEcho); + JSBool echo; JS_ValueToBoolean(cx, jsEcho, &echo); + + __options(cx, win, options, JS_TRUE); + if (echo) { + wechochar(win, ch); + } + else if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { + waddch(win, ch); + } + else { + mvwaddch(win, + JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, + JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, + ch + ); + } + __options(cx, win, options, JS_FALSE); + } + + return JS_TRUE; +} + +JSBool +Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* options; + + WINDOW* win = JS_GetPrivate(cx, object); + + if (argc == 0) { + *rval = INT_TO_JSVAL(wgetch(win)); + } + else { + JS_ValueToObject(cx, argv[0], &options); + + if (!options) { + JS_ReportError(cx, "Options isn't a valid object."); + return JS_FALSE; + } + + jsval x, y; + JS_GetProperty(cx, options, "x", &x); + JS_GetProperty(cx, options, "y", &y); + + if (!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) { + JS_ReportError(cx, "An option is missing or isn't an int."); + return JS_FALSE; + } + + *rval = INT_TO_JSVAL(mvwgetch(win, JSVAL_TO_INT(y), JSVAL_TO_INT(x))); + } + + return JS_TRUE; +} + +JSBool +Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + WINDOW* win = JS_GetPrivate(cx, object); + + if (argc == 1){ + wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + } + else if (argc == 2) { + JSObject* options; JS_ValueToObject(cx, argv[1], &options); + + jsval x, y; + JS_GetProperty(cx, options, "x", &x); + JS_GetProperty(cx, options, "y", &y); + + __options(cx, win, options, JS_TRUE); + if (!JSVAL_IS_INT(x) && !JSVAL_IS_INT(y)) { + wprintw(win, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + } + else { + mvwprintw(win, + JSVAL_IS_INT(y) ? JSVAL_TO_INT(y) : 0, + JSVAL_IS_INT(x) ? JSVAL_TO_INT(x) : 0, + JS_GetStringBytes(JS_ValueToString(cx, argv[0])) + ); + } + __options(cx, win, options, JS_FALSE); + } + + return JS_TRUE; +} + +void +__Window_updateSize (JSContext* cx, JSObject* object) +{ + int height, width; + WINDOW* win = JS_GetPrivate(cx, object); + getmaxyx(win, height, width); + + jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); + JSObject* Size = JSVAL_TO_OBJECT(jsSize); + + jsval property; + property = INT_TO_JSVAL(height); + JS_SetProperty(cx, Size, "Height", &property); + property = INT_TO_JSVAL(width); + JS_SetProperty(cx, Size, "Width", &property); +} + +void +__Window_updatePosition (JSContext* cx, JSObject* object) +{ + int y, x; + WINDOW* win = JS_GetPrivate(cx, object); + getbegyx(win, y, x); + + jsval jsPosition; JS_GetProperty(cx, object, "Position", &jsPosition); + JSObject* Position = JSVAL_TO_OBJECT(jsPosition); + + jsval property; + property = INT_TO_JSVAL(y); + JS_SetProperty(cx, Position, "Y", &property); + property = INT_TO_JSVAL(x); + JS_SetProperty(cx, Position, "X", &property); +} + diff --git a/src/Window.h b/src/Window.h new file mode 100644 index 0000000..6b2aa0c --- /dev/null +++ b/src/Window.h @@ -0,0 +1,59 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_SCREEN_H +#define _LULZJS_NCURSES_SCREEN_H + +#include "common.h" + +extern JSBool exec (JSContext* cx); +extern JSBool Window_initialize (JSContext* cx); + +extern JSBool Window_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern void Window_finalize (JSContext* cx, JSObject* object); + +static JSClass Window_class = { + "Window", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Window_finalize +}; + +extern JSBool Window_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Window_redraw (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + +extern JSBool Window_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern JSBool Window_printChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + +extern JSBool Window_printString (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + +void __Window_updateSize (JSContext* cx, JSObject* object); +void __Window_updatePosition (JSContext* cx, JSObject* object); + +static JSFunctionSpec Window_methods[] = { + {"refresh", Window_refresh, 0, 0, 0}, + {"redraw", Window_redraw, 0, 0, 0}, + + {"printChar", Window_printChar, 0, 0, 0}, + {"getChar", Window_getChar, 0, 0, 0}, + + {"printString", Window_printString, 0, 0, 0}, + + {NULL} +}; + +#endif diff --git a/src/common.h b/src/common.h index 7c1a5cf..9ca3142 100644 --- a/src/common.h +++ b/src/common.h @@ -1,28 +1,80 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_COMMON_H #define _LULZJS_NCURSES_COMMON_H #include "lulzjs.h" #include <curses.h> #include <panel.h> #include <form.h> #include <menu.h> +void +__options (JSContext* cx, WINDOW* win, JSObject* options, JSBool apply) +{ + jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attribute", &jsAttrs); + + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attributes", &jsAttrs); + } + } + + if (JSVAL_IS_INT(jsAttrs)) { + if (apply) { + wattron(win, JSVAL_TO_INT(jsAttrs)); + } + else { + wattroff(win, JSVAL_TO_INT(jsAttrs)); + } + } + + jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); + if (!JSVAL_IS_INT(jsForeground)) { + JS_GetProperty(cx, options, "foreground", &jsForeground); + } + + jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); + if (!JSVAL_IS_INT(jsBackground)) { + JS_GetProperty(cx, options, "background", &jsBackground); + } + + short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; + short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; + + if (fg == -1 && bg == -1) { + return; + } + + char pair[3] = {0}; + sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default + sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 + + short c_pair = atoi(pair); + if (apply) { + init_pair(c_pair, fg, bg); + wattron(win, COLOR_PAIR(c_pair)); + } + else { + wattroff(win, COLOR_PAIR(c_pair)); + } +} + #endif diff --git a/src/init.js b/src/init.js index eefda01..16732e7 100644 --- a/src/init.js +++ b/src/init.js @@ -1,22 +1,23 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ require(["ncurses.so", "ncurses.js"]); +require("Window.so"); require(["Screen.so", "Screen.js"]); diff --git a/test/size.js b/test/size.js index 4affe07..13d02bb 100755 --- a/test/size.js +++ b/test/size.js @@ -1,13 +1,13 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); (screen.onResize = function () { - screen.printLine("Width: {0}\nHeight: {1}".format([ - screen.Size.Width, screen.Size.Height]), 0, 0, - {fg: ncurses.Colors.Red, at: ncurses.Attributes.Reverse} - ); + screen.printString("Width", {x: 0, y: 0, fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); + screen.printString(" : "+screen.Size.Width+" "); + screen.printString("Height", {x: 0, y: 1, fg: ncurses.Colors.Red, at: ncurses.Attributes.Underline}); + screen.printString(": "+screen.Size.Height+" "); })(); while (screen.getChar() != ord('q')); diff --git a/test/test.js b/test/test.js index 4c74aa5..4da77bb 100755 --- a/test/test.js +++ b/test/test.js @@ -1,9 +1,9 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); -screen.printLine("LOL", {fg: ncurses.Colors.Red, at:ncurses.Attributes.Standout}); +screen.printString("LOL", {fg: ncurses.Colors.Red, at:ncurses.Attributes.Standout}); screen.getChar(); -screen.printLine("OMG", 10, 10, {bg: ncurses.Colors.Red}); -screen.printLine(chr(screen.getChar()), 35, 10); +screen.printString("OMG", {x: 10, y: 10, bg: ncurses.Colors.Red}); +screen.printChar(screen.getChar(), {x: 35, y: 10}); screen.getChar() diff --git a/test/window.js b/test/window.js new file mode 100755 index 0000000..cc93657 --- /dev/null +++ b/test/window.js @@ -0,0 +1,8 @@ +#! /usr/bin/env ljs +require("ncurses"); + +var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); +var win = new ncurses.Window({x: 2, y: 2, width: 40, height: 10}); +win.printString("LOLNIGGERS", {x: 10, y: 4, fg: ncurses.Colors.Blue}); +win.printChar(win.getChar(), {x: 2, y: 2}) +win.getChar();
meh/lulzjs-ncurses
62055a8d2dace2ba56dbdf59f98a1c4034252ac1
Fixed Size bug.
diff --git a/src/Screen.c b/src/Screen.c index 0e2b718..1c71992 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,299 +1,300 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { - endwin(); initscr(); __Screen_updateSize(signalCx, signalObject); + endwin(); initscr(); refresh(); + __Screen_updateSize(signalCx, signalObject); jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); refresh(); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, Screen_constructor, 1, NULL, Screen_methods, NULL, Screen_static_methods ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); JSObject* Size = JS_NewObject(cx, NULL, NULL, NULL); jsval jsSize = OBJECT_TO_JSVAL(Size); JS_SetProperty(cx, object, "Size", &jsSize); __Screen_updateSize(cx, object); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } // Cursor state JS_GetProperty(cx, options, "cursor", &option); curs_set(JS_ParseInt(cx, option, 0)); return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } endwin(); JS_free(cx, data); } } JSBool Screen_refresh (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { refresh(); return JS_TRUE; } JSBool Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { *rval = INT_TO_JSVAL(getch()); return JS_TRUE; } JSBool Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } switch (argc) { case 1: { printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } break; case 2: { JSObject* options; JS_ValueToObject(cx, argv[1], &options); __Screen_options(cx, options, JS_TRUE); printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); __Screen_options(cx, options, JS_FALSE); } break; case 3: { jsint x; JS_ValueToInt32(cx, argv[1], &x); jsint y; JS_ValueToInt32(cx, argv[2], &y); mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } break; case 4: { JSObject* options; JS_ValueToObject(cx, argv[3], &options); jsint x; JS_ValueToInt32(cx, argv[1], &x); jsint y; JS_ValueToInt32(cx, argv[2], &y); __Screen_options(cx, options, JS_TRUE); mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); __Screen_options(cx, options, JS_FALSE); } break; } return JS_TRUE; } void __Screen_options (JSContext* cx, JSObject* options, JSBool apply) { jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attribute", &jsAttrs); if (!JSVAL_IS_INT(jsAttrs)) { JS_GetProperty(cx, options, "attributes", &jsAttrs); } } if (JSVAL_IS_INT(jsAttrs)) { if (apply) { attron(JSVAL_TO_INT(jsAttrs)); } else { attroff(JSVAL_TO_INT(jsAttrs)); } } jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); if (!JSVAL_IS_INT(jsForeground)) { JS_GetProperty(cx, options, "foreground", &jsForeground); } jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); if (!JSVAL_IS_INT(jsBackground)) { JS_GetProperty(cx, options, "background", &jsBackground); } short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; char pair[3] = {0}; sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 short c_pair = atoi(pair); if (apply) { init_pair(c_pair, fg, bg); attron(COLOR_PAIR(c_pair)); } else { attroff(COLOR_PAIR(c_pair)); } } void __Screen_updateSize (JSContext* cx, JSObject* object) { int height, width; getmaxyx(stdscr, height, width); jsval jsSize; JS_GetProperty(cx, object, "Size", &jsSize); JSObject* Size = JSVAL_TO_OBJECT(jsSize); jsval property; property = INT_TO_JSVAL(height); JS_SetProperty(cx, Size, "Height", &property); property = INT_TO_JSVAL(width); JS_SetProperty(cx, Size, "Width", &property); } JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { jsint val; if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } curs_set(val); return JS_TRUE; } diff --git a/test/size.js b/test/size.js index 4757042..4affe07 100755 --- a/test/size.js +++ b/test/size.js @@ -1,14 +1,13 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); (screen.onResize = function () { screen.printLine("Width: {0}\nHeight: {1}".format([ screen.Size.Width, screen.Size.Height]), 0, 0, {fg: ncurses.Colors.Red, at: ncurses.Attributes.Reverse} ); })(); - while (screen.getChar() != ord('q'));
meh/lulzjs-ncurses
92d04be572999da10dfc65ed30ebad196a108eef
Stuff.
diff --git a/Makefile b/Makefile index 47eaf69..0802650 100644 --- a/Makefile +++ b/Makefile @@ -1,45 +1,50 @@ VERSION = 0.1 CC = gcc CXX = g++ BINDIR = /usr/bin LJS_LIBDIR = /usr/lib/lulzjs CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" -I/usr/include/js -I./src LDFLAGS = -ljs -llulzjs ifdef DEBUG CFLAGS += -g endif ifdef DDEBUG CFLAGS += -DDEBUG -g endif LIB_DIR = src LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o LIB_CFLAGS = ${CFLAGS} -LIB_LDFLAGS = ${LDFLAGS} -lncurses +LIB_LDFLAGS = ${LDFLAGS} -lncurses -lpanel -lform -lmenu all: lib lib: $(LIB) $(LIB) : $(LIB:.o=.c) ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc -install: lib_install - lib_install: lib mkdir -p ${LJS_LIBDIR}/ncurses ######## cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so cp -f ${LIB_DIR}/ncurses.js ${LJS_LIBDIR}/ncurses/ncurses.js cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so cp -f ${LIB_DIR}/Screen.js ${LJS_LIBDIR}/ncurses/Screen.js ####### chmod -R a+rx ${LJS_LIBDIR}/ncurses +lib_uninstall: + rm -rf ${LJS_LIBDIR}/ncurses + + +install: lib_install +uninstall: lib_uninstall + clean: find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Screen.c b/src/Screen.c index c3bd5a8..e49501d 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,195 +1,269 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, Screen_constructor, 1, NULL, Screen_methods, NULL, Screen_static_methods ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); if (has_colors()) { start_color(); use_default_colors(); } ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } + // Cursor state + JS_GetProperty(cx, options, "cursor", &option); + curs_set(JS_ParseInt(cx, option, 0)); + return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } endwin(); JS_free(cx, data); } } JSBool Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { *rval = INT_TO_JSVAL(getch()); return JS_TRUE; } JSBool Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { if (argc < 1) { JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } switch (argc) { case 1: { - printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } break; case 2: { - char* string = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); - JSObject* options; JS_ValueToObject(cx, argv[1], &options); - + JSObject* options; JS_ValueToObject(cx, argv[1], &options); + __Screen_options(cx, options, JS_TRUE); + printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + __Screen_options(cx, options, JS_FALSE); } break; case 3: { - char* string = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); - jsint x; JS_ValueToInt32(cx, argv[1], &x); - jsint y; JS_ValueToInt32(cx, argv[2], &y); + jsint x; JS_ValueToInt32(cx, argv[1], &x); + jsint y; JS_ValueToInt32(cx, argv[2], &y); - mvprintw(y, x, string); + mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); } break; case 4: { + JSObject* options; JS_ValueToObject(cx, argv[3], &options); + jsint x; JS_ValueToInt32(cx, argv[1], &x); + jsint y; JS_ValueToInt32(cx, argv[2], &y); + + __Screen_options(cx, options, JS_TRUE); + mvprintw(y, x, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + __Screen_options(cx, options, JS_FALSE); } break; } return JS_TRUE; } +void +__Screen_options (JSContext* cx, JSObject* options, JSBool apply) +{ + jsval jsAttrs; JS_GetProperty(cx, options, "at", &jsAttrs); + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attribute", &jsAttrs); + + if (!JSVAL_IS_INT(jsAttrs)) { + JS_GetProperty(cx, options, "attributes", &jsAttrs); + } + } + + if (JSVAL_IS_INT(jsAttrs)) { + if (apply) { + attron(JSVAL_TO_INT(jsAttrs)); + } + else { + attroff(JSVAL_TO_INT(jsAttrs)); + } + } + + jsval jsForeground; JS_GetProperty(cx, options, "fg", &jsForeground); + if (!JSVAL_IS_INT(jsForeground)) { + JS_GetProperty(cx, options, "foreground", &jsForeground); + } + + jsval jsBackground; JS_GetProperty(cx, options, "bg", &jsBackground); + if (!JSVAL_IS_INT(jsBackground)) { + JS_GetProperty(cx, options, "background", &jsBackground); + } + + short fg = JSVAL_IS_INT(jsForeground) ? JSVAL_TO_INT(jsForeground) : -1; + short bg = JSVAL_IS_INT(jsBackground) ? JSVAL_TO_INT(jsBackground) : -1; + + char pair[3] = {0}; + sprintf(&pair[0], "%1d", (fg<0?0:fg)); // I've to give 0 if it's using the default + sprintf(&pair[1], "%1d", (bg<0?0:bg)); // value because it fucks up with -1 + + short c_pair = atoi(pair); + if (apply) { + init_pair(c_pair, fg, bg); + attron(COLOR_PAIR(c_pair)); + } + else { + attroff(COLOR_PAIR(c_pair)); + } +} + +JSBool +Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + jsint val; + + if (argc < 1 || !JS_ConvertArguments(cx, argc, argv, "i", &val)) { + JS_ReportError(cx, "Not enough parameters."); + return JS_FALSE; + } + + curs_set(val); + + return JS_TRUE; +} + diff --git a/src/Screen.h b/src/Screen.h index dd2f06a..3d1aaf2 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,54 +1,60 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #ifndef _LULZJS_NCURSES_SCREEN_H #define _LULZJS_NCURSES_SCREEN_H #include "common.h" #include <signal.h> void __Screen_resize (int signum); extern JSBool exec (JSContext* cx); extern JSBool Screen_initialize (JSContext* cx); extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); extern void Screen_finalize (JSContext* cx, JSObject* object); static JSClass Screen_class = { "Screen", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize }; #include "Screen_private.h" extern JSBool Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); + extern JSBool Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +void __Screen_options (JSContext* cx, JSObject* options, JSBool apply); + +extern JSBool Screen_cursorMode (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); static JSFunctionSpec Screen_methods[] = { {"getChar", Screen_getChar, 0, 0, 0}, {"print", Screen_print, 0, 0, 0}, + + {"cursorMode", Screen_cursorMode, 0, 0, 0}, {NULL} }; static JSFunctionSpec Screen_static_methods[] = { {NULL} }; #endif diff --git a/src/Screen.js b/src/Screen.js index 363083f..e424044 100644 --- a/src/Screen.js +++ b/src/Screen.js @@ -1,28 +1,28 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ Object.extend(ncurses.Screen.prototype, { - printLine: function (str, x, y) { - if (str && x && y) { - this.print(str+"\n", x, y); - } - else { - this.print(str+"\n"); + printLine: function () { + switch (arguments.length) { + case 1: this.print(arguments[0]+"\n"); break; + case 2: this.print(arguments[0]+"\n", arguments[1]); break; + case 3: this.print(arguments[0]+"\n", arguments[1], arguments[2]); break; + case 4: this.print(arguments[0]+"\n", arguments[1], arguments[2], arguments[3]); break; } } }); diff --git a/src/ncurses.c b/src/ncurses.c index a9736c7..58ce7d1 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,96 +1,106 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); property = INT_TO_JSVAL(Normal); JS_SetProperty(cx, Buffering, "Normal", &property); property = INT_TO_JSVAL(Raw); JS_SetProperty(cx, Buffering, "Raw", &property); property = INT_TO_JSVAL(CBreak); JS_SetProperty(cx, Buffering, "CBreak", &property); JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); jsval jsColors = OBJECT_TO_JSVAL(Colors); JS_SetProperty(cx, object, "Colors", &jsColors); property = INT_TO_JSVAL(-1); JS_SetProperty(cx, Colors, "Normal", &property); property = INT_TO_JSVAL(COLOR_BLACK); JS_SetProperty(cx, Colors, "Black", &property); property = INT_TO_JSVAL(COLOR_RED); JS_SetProperty(cx, Colors, "Red", &property); property = INT_TO_JSVAL(COLOR_GREEN); JS_SetProperty(cx, Colors, "Green", &property); property = INT_TO_JSVAL(COLOR_YELLOW); JS_SetProperty(cx, Colors, "Yellow", &property); property = INT_TO_JSVAL(COLOR_BLUE); JS_SetProperty(cx, Colors, "Blue", &property); property = INT_TO_JSVAL(COLOR_MAGENTA); JS_SetProperty(cx, Colors, "Magenta", &property); property = INT_TO_JSVAL(COLOR_CYAN); JS_SetProperty(cx, Colors, "Cyan", &property); property = INT_TO_JSVAL(COLOR_WHITE); JS_SetProperty(cx, Colors, "White", &property); JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); JS_SetProperty(cx, object, "Attributes", &jsAttributes); property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) JS_SetProperty(cx, Attributes, "Normal", &property); property = INT_TO_JSVAL(A_BLINK); // Blinking JS_SetProperty(cx, Attributes, "Blink", &property); property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold JS_SetProperty(cx, Attributes, "Bold", &property); property = INT_TO_JSVAL(A_DIM); // Half bright JS_SetProperty(cx, Attributes, "Dim", &property); property = INT_TO_JSVAL(A_REVERSE); // Reverse video JS_SetProperty(cx, Attributes, "Reverse", &property); property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. JS_SetProperty(cx, Attributes, "Standout", &property); property = INT_TO_JSVAL(A_UNDERLINE); // Underlining JS_SetProperty(cx, Attributes, "Underline", &property); property = INT_TO_JSVAL(A_PROTECT); // Protected mode JS_SetProperty(cx, Attributes, "Protect", &property); property = INT_TO_JSVAL(A_INVIS); JS_SetProperty(cx, Attributes, "Invisible", &property); + JSObject* Cursor = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsCursor = OBJECT_TO_JSVAL(Cursor); + JS_SetProperty(cx, object, "Cursor", &jsCursor); + property = INT_TO_JSVAL(0); + JS_SetProperty(cx, Cursor, "Invisible", &property); + property = INT_TO_JSVAL(1); + JS_SetProperty(cx, Cursor, "Normal", &property); + property = INT_TO_JSVAL(2); + JS_SetProperty(cx, Cursor, "Visible", &property); + return JS_TRUE; } return JS_FALSE; } diff --git a/test/test.js b/test/test.js index 15a17af..4c74aa5 100755 --- a/test/test.js +++ b/test/test.js @@ -1,9 +1,9 @@ #! /usr/bin/env ljs require("ncurses"); var screen = new ncurses.Screen({buffering: ncurses.Buffering.Raw}); -screen.printLine("LOL"); +screen.printLine("LOL", {fg: ncurses.Colors.Red, at:ncurses.Attributes.Standout}); screen.getChar(); -screen.printLine("OMG", 10, 10); +screen.printLine("OMG", 10, 10, {bg: ncurses.Colors.Red}); screen.printLine(chr(screen.getChar()), 35, 10); screen.getChar()
meh/lulzjs-ncurses
56405b0e324be109a06415c25ff0cb1a95d1bdff
Added colors and attributes.
diff --git a/src/Screen.c b/src/Screen.c index 8bffdf9..c3bd5a8 100644 --- a/src/Screen.c +++ b/src/Screen.c @@ -1,176 +1,195 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "Screen.h" static JSContext* signalCx; static JSObject* signalObject; void __Screen_resize (int signum) { jsval ret; JS_CallFunctionName(signalCx, signalObject, "onResize", 0, NULL, &ret); } JSBool exec (JSContext* cx) { return Screen_initialize(cx); } JSBool Screen_initialize (JSContext* cx) { jsval jsParent; JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); JSObject* parent = JSVAL_TO_OBJECT(jsParent); JSObject* object = JS_InitClass( cx, parent, NULL, &Screen_class, Screen_constructor, 1, NULL, Screen_methods, NULL, Screen_static_methods ); if (object) { // Default properties jsval property; return JS_TRUE; } return JS_FALSE; } JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { JSObject* options; if (stdscr) { JS_ReportError(cx, "You can have only one Screen per program."); return JS_FALSE; } signalCx = cx; signalObject = object; signal(SIGWINCH, __Screen_resize); initscr(); + + if (has_colors()) { + start_color(); + use_default_colors(); + } + ScreenInformation* data = JS_malloc(cx, sizeof(ScreenInformation)); JS_SetPrivate(cx, object, data); if (argc > 0) { JS_ValueToObject(cx, argv[0], &options); } else { options = JS_NewObject(cx, NULL, NULL, NULL); } if (argc > 1 && JS_OBJECT_IS(cx, argv[1], "Function")) { JS_SetProperty(cx, object, "onResize", &argv[1]); } else { jsval jsfunc; JS_GetProperty(cx, JS_GetGlobalObject(cx), "Function", &jsfunc); JS_GetProperty(cx, JSVAL_TO_OBJECT(jsfunc), "empty", &jsfunc); JS_SetProperty(cx, object, "onResize", &jsfunc); } jsval option; // Echoing of inputted keys JS_GetProperty(cx, options, "echo", &option); JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); if (JSVAL_IS_VOID(option) || !js_echo) { noecho(); data->echo = JS_FALSE; } else { echo(); data->echo = JS_TRUE; } // Buffering type JS_GetProperty(cx, options, "buffering", &option); jsint js_buffering = JS_ParseInt(cx, option, 0); switch (js_buffering) { case Raw : raw(); data->buffering = Raw; break; case CBreak: cbreak(); data->buffering = CBreak; break; default : data->buffering = Normal; break; } // Keypad initialization JS_GetProperty(cx, options, "keypad", &option); JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); if (JSVAL_IS_VOID(option) || js_keypad) { keypad(stdscr, TRUE); data->keypad = JS_TRUE; } else { data->keypad = JS_FALSE; } return JS_TRUE; } void Screen_finalize (JSContext* cx, JSObject* object) { ScreenInformation* data = JS_GetPrivate(cx, object); if (data) { switch (data->buffering) { case Raw : noraw(); break; case CBreak: nocbreak(); break; } if (data->keypad) { keypad(stdscr, FALSE); } if (!data->echo) { echo(); } endwin(); JS_free(cx, data); } } JSBool Screen_getChar (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { *rval = INT_TO_JSVAL(getch()); return JS_TRUE; } JSBool Screen_print (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) { - if (argc != 1 && argc != 3) { - JS_ReportError(cx, "Wrong parameters number."); + if (argc < 1) { + JS_ReportError(cx, "Not enough parameters."); return JS_FALSE; } - if (argc == 1) { + switch (argc) { + case 1: { printw(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); - } - else { + } break; + + case 2: { + char* string = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + JSObject* options; JS_ValueToObject(cx, argv[1], &options); + + + } break; + + case 3: { char* string = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); jsint x; JS_ValueToInt32(cx, argv[1], &x); jsint y; JS_ValueToInt32(cx, argv[2], &y); mvprintw(y, x, string); + } break; + + case 4: { + } break; } return JS_TRUE; } diff --git a/src/ncurses.c b/src/ncurses.c index ec74faf..a9736c7 100644 --- a/src/ncurses.c +++ b/src/ncurses.c @@ -1,53 +1,96 @@ /**************************************************************************** * This file is part of lulzJS-ncurses * * Copyleft meh. * * * * lulzJS-ncurses is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * lulzJS-ncurses is distributed in the hope that it will be useful. * * but WITHOUT ANY WARRANTY; without even the implied warranty o. * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "ncurses.h" JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } JSBool ncurses_initialize (JSContext* cx) { JSObject* object = JS_DefineObject( cx, JS_GetGlobalObject(cx), ncurses_class.name, &ncurses_class, NULL, JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE ); if (object) { JS_DefineFunctions(cx, object, ncurses_methods); jsval property; JSObject* Buffering = JS_NewObject(cx, NULL, NULL, NULL); jsval jsBuffering = OBJECT_TO_JSVAL(Buffering); JS_SetProperty(cx, object, "Buffering", &jsBuffering); + property = INT_TO_JSVAL(Normal); + JS_SetProperty(cx, Buffering, "Normal", &property); + property = INT_TO_JSVAL(Raw); + JS_SetProperty(cx, Buffering, "Raw", &property); + property = INT_TO_JSVAL(CBreak); + JS_SetProperty(cx, Buffering, "CBreak", &property); - property = INT_TO_JSVAL(Normal); - JS_SetProperty(cx, Buffering, "Normal", &property); - property = INT_TO_JSVAL(Raw); - JS_SetProperty(cx, Buffering, "Raw", &property); - property = INT_TO_JSVAL(CBreak); - JS_SetProperty(cx, Buffering, "CBreak", &property); + JSObject* Colors = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsColors = OBJECT_TO_JSVAL(Colors); + JS_SetProperty(cx, object, "Colors", &jsColors); + property = INT_TO_JSVAL(-1); + JS_SetProperty(cx, Colors, "Normal", &property); + property = INT_TO_JSVAL(COLOR_BLACK); + JS_SetProperty(cx, Colors, "Black", &property); + property = INT_TO_JSVAL(COLOR_RED); + JS_SetProperty(cx, Colors, "Red", &property); + property = INT_TO_JSVAL(COLOR_GREEN); + JS_SetProperty(cx, Colors, "Green", &property); + property = INT_TO_JSVAL(COLOR_YELLOW); + JS_SetProperty(cx, Colors, "Yellow", &property); + property = INT_TO_JSVAL(COLOR_BLUE); + JS_SetProperty(cx, Colors, "Blue", &property); + property = INT_TO_JSVAL(COLOR_MAGENTA); + JS_SetProperty(cx, Colors, "Magenta", &property); + property = INT_TO_JSVAL(COLOR_CYAN); + JS_SetProperty(cx, Colors, "Cyan", &property); + property = INT_TO_JSVAL(COLOR_WHITE); + JS_SetProperty(cx, Colors, "White", &property); + + JSObject* Attributes = JS_NewObject(cx, NULL, NULL, NULL); + jsval jsAttributes = OBJECT_TO_JSVAL(Attributes); + JS_SetProperty(cx, object, "Attributes", &jsAttributes); + property = INT_TO_JSVAL(A_NORMAL); // Normal display (no highlight) + JS_SetProperty(cx, Attributes, "Normal", &property); + property = INT_TO_JSVAL(A_BLINK); // Blinking + JS_SetProperty(cx, Attributes, "Blink", &property); + property = INT_TO_JSVAL(A_BOLD); // Extra bright or bold + JS_SetProperty(cx, Attributes, "Bold", &property); + property = INT_TO_JSVAL(A_DIM); // Half bright + JS_SetProperty(cx, Attributes, "Dim", &property); + property = INT_TO_JSVAL(A_REVERSE); // Reverse video + JS_SetProperty(cx, Attributes, "Reverse", &property); + property = INT_TO_JSVAL(A_STANDOUT); // Best highlighting mode of the terminal. + JS_SetProperty(cx, Attributes, "Standout", &property); + property = INT_TO_JSVAL(A_UNDERLINE); // Underlining + JS_SetProperty(cx, Attributes, "Underline", &property); + property = INT_TO_JSVAL(A_PROTECT); // Protected mode + JS_SetProperty(cx, Attributes, "Protect", &property); + property = INT_TO_JSVAL(A_INVIS); + JS_SetProperty(cx, Attributes, "Invisible", &property); return JS_TRUE; } return JS_FALSE; }
meh/lulzjs-ncurses
fccf25c39e500adaabba7e21e59d788cd6774c5b
I'm a looser baby so why don't you kill me?
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b2202a9 --- /dev/null +++ b/Makefile @@ -0,0 +1,43 @@ +VERSION = 0.1 + +CC = gcc +CXX = g++ +BINDIR = /usr/bin +LJS_LIBDIR = /usr/lib/lulzjs +CFLAGS = -Os -DXP_UNIX -DJS_THREADSAFE -D__LIB_VERSION__="\"${VERSION}\"" -I/usr/include/js -I./src +LDFLAGS = -ljs -llulzjs + +ifdef DEBUG +CFLAGS += -g +endif + +ifdef DDEBUG +CFLAGS += -DDEBUG -g +endif + +LIB_DIR = src +LIB = ${LIB_DIR}/ncurses.o ${LIB_DIR}/Screen.o +LIB_CFLAGS = ${CFLAGS} +LIB_LDFLAGS = ${LDFLAGS} -lncurses + +all: lib + +lib: $(LIB) + +$(LIB) : $(LIB:.o=.c) + ${CC} ${LIB_CFLAGS} -fPIC -c $*.c -o $*.lo + ${CC} ${LIB_LDFLAGS} -shared -Wl,-soname,`basename $*`.so -o $*.o $*.lo -lc + +install: lib_install + +lib_install: + mkdir -p ${LJS_LIBDIR}/ncurses +######## + cp -f ${LIB_DIR}/init.js ${LJS_LIBDIR}/ncurses/init.js + cp -f ${LIB_DIR}/ncurses.o ${LJS_LIBDIR}/ncurses/ncurses.so + cp -f ${LIB_DIR}/Screen.o ${LJS_LIBDIR}/ncurses/Screen.so +####### + chmod -R a+rx ${LJS_LIBDIR}/ncurses + +clean: + find src|egrep "\.l?o"|xargs rm -f diff --git a/src/Screen.c b/src/Screen.c new file mode 100644 index 0000000..693cea5 --- /dev/null +++ b/src/Screen.c @@ -0,0 +1,102 @@ +/**************************************************************************** +* This file is part of lulzJS * +* Copyleft meh. * +* * +* lulzJS is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#include "Screen.h" + +JSBool exec (JSContext* cx) { return Screen_initialize(cx); } + +JSBool +Screen_initialize (JSContext* cx) +{ + jsval jsParent; + JS_GetProperty(cx, JS_GetGlobalObject(cx), "ncurses", &jsParent); + JSObject* parent = JSVAL_TO_OBJECT(jsParent); + + JSObject* object = JS_InitClass( + cx, parent, NULL, &Screen_class, + Screen_constructor, 1, NULL, Screen_methods, NULL, Screen_static_methods + ); + + if (object) { + // Default properties + jsval property; + + property = INT_TO_JSVAL(EOF); + JS_SetProperty(cx, parent, "EOF", &property); + + return JS_TRUE; + } + + return JS_FALSE; +} + +JSBool +Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval) +{ + JSObject* options; + + if (stdscr) { + JS_ReportError(cx, "You can have only one Screen per program."); + return JS_FALSE; + } + + initscr(); + + if (argc == 1) { + JS_ValueToObject(cx, argv[0], &options); + } + else { + options = JS_NewObject(cx, NULL, NULL, NULL); + } + + jsval option; + + // Echoing of inputted keys + JS_GetProperty(cx, options, "echo", &option); + JSBool js_echo; JS_ValueToBoolean(cx, option, &js_echo); + if (JSVAL_IS_VOID(option) || !js_echo) { + noecho(); + } + else { + echo(); + } + + // Buffering type + JS_GetProperty(cx, options, "buffering", &option); + jsuint js_buffering; JS_ValueToInt32(cx, option, &js_buffering); + switch (js_buffering) { + case RAW : raw(); break; + case CBREAK: cbrea(); break; + } + + // Keypad initialization + JS_GetProperty(cx, options, "keypad", &option); + JSBool js_keypad; JS_ValueToBoolean(cx, option, &js_keypad); + if (JSVAL_IS_VOID(option) || js_keypad) { + keypad(stdscr, TRUE); + } + + return JS_TRUE; +} + +void +Screen_finalize (JSContext* cx, JSObject* object) +{ + echo(); + endwin(); +} diff --git a/src/Screen.h b/src/Screen.h new file mode 100644 index 0000000..9dcb4d3 --- /dev/null +++ b/src/Screen.h @@ -0,0 +1,49 @@ +/**************************************************************************** +* This file is part of lulzJS * +* Copyleft meh. * +* * +* lulzJS is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_SCREEN_H +#define _LULZJS_NCURSES_SCREEN_H + +#include "common.h" + +#define RAW 1 +#define CBREAK 2 + +extern JSBool exec (JSContext* cx); +extern JSBool Screen_initialize (JSContext* cx); + +extern JSBool Screen_constructor (JSContext* cx, JSObject* object, uintN argc, jsval* argv, jsval* rval); +extern void Screen_finalize (JSContext* cx, JSObject* object); + +static JSClass Screen_class = { + "Screen", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, Screen_finalize +}; + +#include "Screen_private.h" + +static JSFunctionSpec Screen_methods[] = { + {NULL} +}; + +static JSFunctionSpec Screen_static_methods[] = { + {NULL} +}; + +#endif diff --git a/src/Screen_private.h b/src/Screen_private.h new file mode 100644 index 0000000..e69de29 diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..7c1a5cf --- /dev/null +++ b/src/common.h @@ -0,0 +1,28 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_COMMON_H +#define _LULZJS_NCURSES_COMMON_H + +#include "lulzjs.h" +#include <curses.h> +#include <panel.h> +#include <form.h> +#include <menu.h> + +#endif diff --git a/src/init.js b/src/init.js new file mode 100644 index 0000000..6f68147 --- /dev/null +++ b/src/init.js @@ -0,0 +1,21 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +require("ncurses.so"); +require("Screen.so"); + diff --git a/src/ncurses.c b/src/ncurses.c new file mode 100644 index 0000000..5315d91 --- /dev/null +++ b/src/ncurses.c @@ -0,0 +1,40 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#include "ncurses.h" + +JSBool exec (JSContext* cx) { return ncurses_initialize(cx); } + +JSBool +ncurses_initialize (JSContext* cx) +{ + JSObject* object = JS_DefineObject( + cx, JS_GetGlobalObject(cx), + ncurses_class.name, &ncurses_class, NULL, + JSPROP_PERMANENT|JSPROP_READONLY|JSPROP_ENUMERATE + ); + + if (object) { + JS_DefineFunctions(cx, object, ncurses_methods); + + return JS_TRUE; + } + + return JS_FALSE; +} + diff --git a/src/ncurses.h b/src/ncurses.h new file mode 100644 index 0000000..7b4e05f --- /dev/null +++ b/src/ncurses.h @@ -0,0 +1,37 @@ +/**************************************************************************** +* This file is part of lulzJS-ncurses * +* Copyleft meh. * +* * +* lulzJS-ncurses is free software: you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation, either version 3 of the License, or * +* (at your option) any later version. * +* * +* lulzJS-ncurses is distributed in the hope that it will be useful. * +* but WITHOUT ANY WARRANTY; without even the implied warranty o. * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th. * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with lulzJS-ncurses. If not, see <http://www.gnu.org/licenses/>. * +****************************************************************************/ + +#ifndef _LULZJS_NCURSES_H +#define _LULZJS_NCURSES_H + +#include "common.h" + +extern JSBool exec (JSContext* cx); +extern JSBool ncurses_initialize (JSContext* cx); + +static JSClass ncurses_class = { + "ncurses", 0, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub +}; + +static JSFunctionSpec ncurses_methods[] = { + {NULL} +}; + +#endif diff --git a/test/test.js b/test/test.js new file mode 100755 index 0000000..c41955a --- /dev/null +++ b/test/test.js @@ -0,0 +1,4 @@ +#! /usr/bin/env ljs +require("ncurses"); + +var screen = new ncurses.Screen;
pingwin/DefaultPasswords
f46c9f5237202a3db0c2b82fa734134af152efa8
last time I hopefully will be touching this, i just wanted to app to use.
diff --git a/AndroidManifest.xml b/AndroidManifest.xml index be831b5..0fb4304 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,24 +1,20 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.foss.defaultpasswords" android:versionCode="1" android:versionName="1.0"> - <application android:icon="@drawable/icon" android:label="@string/app_name"> - <activity android:name=".Default Passwords" + <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="9" android:maxSdkVersion="12"></uses-sdk> + <application android:label="@string/app_name"> + <activity android:name=".DefaultPasswords" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> - - <activity android:name="ServerList"> - -</activity> -<activity android:name="ResolverEdit"></activity> - - - -</application> - <uses-sdk android:minSdkVersion="3" /> + <activity android:name=".ModelListActivity" /> + <activity android:name=".VersionListActivity" /> + <activity android:name=".DetailedViewActivity" /> + + </application> </manifest> diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f429ece --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +SDK := /opt/android-sdk/ +TOOLS := $(SDK)/tools +PLATFORM_TOOLS := $(SDK)/platform-tools + +TARGETS := package build clean uninstall install uninstall-emulator install-emulator run +ADB := $(PLATFORM_TOOLS)/adb +ANT := /usr/share/java/apache-ant/bin/ant +EMULATOR := $(TOOLS)/emulator +ANDROID := $(TOOLS)/android + + +PACKAGE := org.foss.defaultpasswords + +# Assigned by user +AVD := '2.3.3-default' +# other options include release +MODE := debug + + +APK := 'DefaultPasswords-$(MODE).apk' + + + +build: + $(ANDROID) update project --path . + $(ANT) $(MODE) + +uninstall: + $(ADB) uninstall $(PACKAGE) + +install: uninstall build + $(ADB) install bin/$(APK) + +install-emulator: + $(ADB) -e install bin/$(APK) +uninstall-emulator: + $(ADB) uninstall -e $(APK) + +run: + $(EMULATOR) -avd $(AVD) \ No newline at end of file diff --git a/assets/default_passwords.db b/assets/default_passwords.db new file mode 100644 index 0000000..ae63064 Binary files /dev/null and b/assets/default_passwords.db differ diff --git a/coloredlogcat.py b/coloredlogcat.py new file mode 100755 index 0000000..9dc7fde --- /dev/null +++ b/coloredlogcat.py @@ -0,0 +1,158 @@ +#!/usr/bin/python + +''' + Copyright 2009, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +''' + +# script to highlight adb logcat output for console +# written by jeff sharkey, http://jsharkey.org/ +# piping detection and popen() added by other android team members + + +import os, sys, re, StringIO +import fcntl, termios, struct + +# unpack the current terminal width/height +data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') +HEIGHT, WIDTH = struct.unpack('hh',data) + +BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) + +def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False): + # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes + codes = [] + if reset: codes.append("0") + else: + if not fg is None: codes.append("3%d" % (fg)) + if not bg is None: + if not bright: codes.append("4%d" % (bg)) + else: codes.append("10%d" % (bg)) + if bold: codes.append("1") + elif dim: codes.append("2") + else: codes.append("22") + return "\033[%sm" % (";".join(codes)) + + +def indent_wrap(message, indent=0, width=80): + wrap_area = width - indent + messagebuf = StringIO.StringIO() + current = 0 + while current < len(message): + next = min(current + wrap_area, len(message)) + messagebuf.write(message[current:next]) + if next < len(message): + messagebuf.write("\n%s" % (" " * indent)) + current = next + return messagebuf.getvalue() + + +LAST_USED = [RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE] +KNOWN_TAGS = { + "dalvikvm": BLUE, + "Process": BLUE, + "ActivityManager": CYAN, + "ActivityThread": CYAN, +} + +def allocate_color(tag): + # this will allocate a unique format for the given tag + # since we dont have very many colors, we always keep track of the LRU + if not tag in KNOWN_TAGS: + KNOWN_TAGS[tag] = LAST_USED[0] + color = KNOWN_TAGS[tag] + LAST_USED.remove(color) + LAST_USED.append(color) + return color + + +RULES = { + #re.compile(r"([\w\.@]+)=([\w\.@]+)"): r"%s\1%s=%s\2%s" % (format(fg=BLUE), format(fg=GREEN), format(fg=BLUE), format(reset=True)), +} + +TAGTYPE_WIDTH = 3 +TAG_WIDTH = 20 +PROCESS_WIDTH = 8 # 8 or -1 +HEADER_SIZE = TAGTYPE_WIDTH + 1 + TAG_WIDTH + 1 + PROCESS_WIDTH + 1 + +TAGTYPES = { + "V": "%s%s%s " % (format(fg=WHITE, bg=BLACK), "V".center(TAGTYPE_WIDTH), format(reset=True)), + "D": "%s%s%s " % (format(fg=BLACK, bg=BLUE), "D".center(TAGTYPE_WIDTH), format(reset=True)), + "I": "%s%s%s " % (format(fg=BLACK, bg=GREEN), "I".center(TAGTYPE_WIDTH), format(reset=True)), + "W": "%s%s%s " % (format(fg=BLACK, bg=YELLOW), "W".center(TAGTYPE_WIDTH), format(reset=True)), + "E": "%s%s%s " % (format(fg=BLACK, bg=RED), "E".center(TAGTYPE_WIDTH), format(reset=True)), +} + +retag = re.compile("^([A-Z])/([^\(]+)\(([^\)]+)\): (.*)$") + +# to pick up -d or -e +adb_args = ' '.join(sys.argv[1:]) + +# if someone is piping in to us, use stdin as input. if not, invoke adb logcat +if os.isatty(sys.stdin.fileno()): + input = os.popen("adb %s logcat" % adb_args) +else: + input = sys.stdin + +while True: + try: + line = input.readline() + except KeyboardInterrupt: + break + + match = retag.match(line) + if not match is None: + tagtype, tag, owner, message = match.groups() + linebuf = StringIO.StringIO() + + # center process info + if PROCESS_WIDTH > 0: + owner = owner.strip().center(PROCESS_WIDTH) + linebuf.write("%s%s%s " % (format(fg=BLACK, bg=BLACK, bright=True), owner, format(reset=True))) + + # right-align tag title and allocate color if needed + tag = tag.strip() + color = allocate_color(tag) + tag = tag[-TAG_WIDTH:].rjust(TAG_WIDTH) + linebuf.write("%s%s %s" % (format(fg=color, dim=False), tag, format(reset=True))) + + # write out tagtype colored edge + if not tagtype in TAGTYPES: break + linebuf.write(TAGTYPES[tagtype]) + + # insert line wrapping as needed + message = indent_wrap(message, HEADER_SIZE, WIDTH) + + # format tag message using rules + for matcher in RULES: + replace = RULES[matcher] + message = matcher.sub(replace, message) + + linebuf.write(message) + line = linebuf.getvalue() + + print line + if len(line) == 0: break + + + + + + + + + + + + diff --git a/default.properties b/default.properties index a1ef8e9..9a2c9f6 100644 --- a/default.properties +++ b/default.properties @@ -1,13 +1,11 @@ # This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system use, # "build.properties", and override values to adapt the script to your # project structure. -# Indicates whether an apk should be generated for each density. -split.density=false # Project target. -target=android-3 +target=android-9 diff --git a/res/layout/detailed_view.xml b/res/layout/detailed_view.xml new file mode 100644 index 0000000..a0a1a09 --- /dev/null +++ b/res/layout/detailed_view.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="utf-8"?> +<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:stretchColumns="1"> + <TableRow> + <TextView android:text="Vendor:" android:padding="3dip" /> + <TextView android:id="@+id/tv_vendor" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Model:" android:padding="3dip" /> + <TextView android:id="@+id/tv_model" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Version:" android:padding="3dip" /> + <TextView android:id="@+id/tv_version" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Access Type:" android:padding="3dip" /> + <TextView android:id="@+id/tv_ac" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Username:" android:padding="3dip" /> + <TextView android:id="@+id/tv_user" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Password:" android:padding="3dip" /> + <TextView android:id="@+id/tv_pass" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Privileges:" android:padding="3dip" /> + <TextView android:id="@+id/tv_priv" android:gravity="right" android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView android:text="Notes:" android:padding="3dip" /> + <TextView android:id="@+id/tv_notes" android:gravity="right" android:padding="3dip" /> + </TableRow> +</TableLayout> \ No newline at end of file diff --git a/res/layout/main.xml b/res/layout/main.xml deleted file mode 100644 index 0b61636..0000000 --- a/res/layout/main.xml +++ /dev/null @@ -1,60 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" - android:layout_width="fill_parent" android:layout_height="fill_parent" - android:keepScreenOn="true" android:saveEnabled="true"> - <RelativeLayout android:layout_width="fill_parent" - android:layout_height="wrap_content" android:isScrollContainer="true" - android:keepScreenOn="true"> - - <!-- Query TextView and EditText --> - <TextView android:id="@+id/query_pros" android:layout_width="fill_parent" - android:layout_height="wrap_content" android:text="Enter Domain Name:" /> - - <EditText android:id="@+id/query" android:layout_width="fill_parent" - android:layout_height="wrap_content" android:autoText="true" - android:layout_below="@id/query_pros" android:text="comwired.com" - android:saveEnabled="true" android:singleLine="true"> - <requestFocus /> - </EditText> - - <!-- QType TextView and Spinner (Align Left) --> - <TextView android:id="@+id/qtype_pros" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:text="Select Query Type:" - android:layout_below="@id/query" /> - - <Spinner android:id="@+id/qtype" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:drawSelectorOnTop="true" - android:prompt="@string/choose_qtype" android:layout_below="@id/qtype_pros" - android:saveEnabled="true" android:entries="@+array/rr_types" /> - - <!-- Server TextView and Spinner (Align Right) --> - <TextView android:id="@+id/server_pros" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:text="Enter Server To Hit:" - android:layout_alignParentRight="true" android:layout_below="@id/query" /> - - <Spinner android:id="@+id/server_spinner" - android:layout_width="wrap_content" android:layout_height="wrap_content" - android:drawSelectorOnTop="true" android:layout_alignParentRight="true" - android:prompt="@string/choose_server" android:layout_below="@id/server_pros" /> - - <!-- Direct Server Entry, Below the above two --> - <EditText android:id="@+id/server" android:layout_width="fill_parent" - android:layout_height="wrap_content" android:autoText="true" - android:layout_below="@id/server_spinner" android:text="8.20.241.1" - android:bufferType="normal" android:lines="1" - android:scrollHorizontally="false" android:saveEnabled="true" - android:selectAllOnFocus="true" /> - - <!-- Go Button --> - <Button android:id="@+id/go" android:layout_width="wrap_content" - android:layout_height="wrap_content" android:layout_below="@id/server" - android:layout_alignParentRight="true" android:layout_marginLeft="10dip" - android:text="Go" /> - - <!-- Display Results of query --> - <TextView android:id="@+id/result_view" android:layout_width="fill_parent" - android:layout_height="wrap_content" android:layout_below="@id/go" - android:scrollbars="vertical" /> - </RelativeLayout> -</ScrollView> - \ No newline at end of file diff --git a/res/layout/model_list.xml b/res/layout/model_list.xml new file mode 100644 index 0000000..4ad5ce6 --- /dev/null +++ b/res/layout/model_list.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:background="#FF0000" + android:orientation="vertical" + > + <TextView android:id="@+id/vendor_name" + android:layout_height="30dip" + android:layout_width="wrap_content" + /> + <ListView android:id="@android:id/android:list" + android:layout_width="wrap_content" + android:layout_height="wrap_content"/> + <TextView android:id="@id/android:empty" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/no_vendors"/> + +</LinearLayout> \ No newline at end of file diff --git a/res/layout/vendor_list.xml b/res/layout/vendor_list.xml new file mode 100644 index 0000000..cb5d13d --- /dev/null +++ b/res/layout/vendor_list.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:background="#FF0000" + android:orientation="vertical" + > + <ListView android:id="@android:id/android:list" + android:layout_width="wrap_content" + android:layout_height="wrap_content"/> + <TextView android:id="@id/android:empty" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/no_vendors"/> + +</LinearLayout> \ No newline at end of file diff --git a/res/layout/vendor_row.xml b/res/layout/vendor_row.xml new file mode 100644 index 0000000..d641ff9 --- /dev/null +++ b/res/layout/vendor_row.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<TextView android:id="@+id/text1" + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textSize="24dip" + /> \ No newline at end of file diff --git a/res/layout/version_list.xml b/res/layout/version_list.xml new file mode 100644 index 0000000..11d3fff --- /dev/null +++ b/res/layout/version_list.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:background="#FF0000" + android:orientation="vertical" + > + <TextView android:id="@+id/vendor_name" + android:layout_height="30dip" + android:layout_width="wrap_content"/> + + <TextView android:id="@+id/model_name" + android:layout_height="30dip" + android:layout_width="wrap_content"/> + + <ListView android:id="@android:id/android:list" + android:layout_width="wrap_content" + android:layout_height="wrap_content"/> + <TextView android:id="@id/android:empty" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/no_vendors"/> + +</LinearLayout> \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml new file mode 100644 index 0000000..49fb96b --- /dev/null +++ b/res/values/strings.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">DefaultPasswords</string> + <string name="no_vendors">There are no Vendors currently installed</string> + <string name="vendor">Vendor:</string> + <string name="model">Model:</string> + <string name="version">Version:</string> + <string name="access_type">Access Type:</string> + <string name="username">Username:</string> + <string name="password">Password:</string> + <string name="priv">Privileges:</string> + <string name="notes">Notes:</string> +</resources> diff --git a/src/org/foss/defaultpasswords/DefaultPasswords.java b/src/org/foss/defaultpasswords/DefaultPasswords.java index 06abf4e..1d4ad84 100644 --- a/src/org/foss/defaultpasswords/DefaultPasswords.java +++ b/src/org/foss/defaultpasswords/DefaultPasswords.java @@ -1,27 +1,59 @@ package org.foss.defaultpasswords; -import android.app.Activity; -import android.widget.SimpleCursorAdapter; -import android.database.Cursor; +import org.foss.defaultpasswords.R; +import android.app.ListActivity; import android.os.Bundle; +import android.database.Cursor; +import android.util.Log; +import android.widget.SimpleCursorAdapter; +import java.io.IOException; import android.view.View; -import android.widget.Button; -import android.widget.TextView; +import android.widget.ListView; import android.widget.Toast; -import android.widget.ArrayAdapter; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.util.Log; +import android.content.Intent; -public class DefaultPasswords extends Activity { +public class DefaultPasswords extends ListActivity { private static final String TAG = "DefaultPasswords"; - - private Cursor dbCursor; - + private PassDbAdapter mDbHelper; + private Cursor vendorCursor; + /** Called when the activity is first created. */ @Override - public void onCreate(Bundle savedInstanceState) { + public void onCreate(Bundle savedInstanceState) { + Log.d(TAG, "Creating DefaultPasswords"); super.onCreate(savedInstanceState); - setContentView(R.layout.main); - + setContentView(R.layout.vendor_list); + mDbHelper = new PassDbAdapter(this); + try { + mDbHelper.createDataBase(); + } catch (IOException ioe) { + throw new Error("Unable to open / create Database"); + } + mDbHelper.openDataBase(); + fillData(); + } + + private void fillData() { + vendorCursor = mDbHelper.fetchAllVendors(); + Toast.makeText(this,"Found "+vendorCursor.getCount()+" Vendors", Toast.LENGTH_LONG).show(); + + startManagingCursor(vendorCursor); + String[] from = new String[] {PassDbAdapter.VENDOR}; + int[] to = new int[] {R.id.text1}; + // Now create an array adapter and set it to display using our row + SimpleCursorAdapter vendors = + new SimpleCursorAdapter(this, R.layout.vendor_row, vendorCursor, from, to); + setListAdapter(vendors); } -} \ No newline at end of file + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + super.onListItemClick(l, v, position, id); + Cursor c = vendorCursor; + c.moveToPosition(position); + Intent i = new Intent(this, ModelListActivity.class); + i.putExtra(PassDbAdapter.ID, c.getLong(c.getColumnIndexOrThrow(PassDbAdapter.ID))); + i.putExtra(PassDbAdapter.VENDOR, c.getString(c.getColumnIndexOrThrow(PassDbAdapter.VENDOR))); + startActivityForResult(i, 0); + Log.i(TAG, "Hello, we got click!"); + } +} diff --git a/src/org/foss/defaultpasswords/DetailedViewActivity.java b/src/org/foss/defaultpasswords/DetailedViewActivity.java new file mode 100644 index 0000000..c55f298 --- /dev/null +++ b/src/org/foss/defaultpasswords/DetailedViewActivity.java @@ -0,0 +1,51 @@ +package org.foss.defaultpasswords; + +import org.foss.defaultpasswords.R; +import android.os.Bundle; +import android.database.Cursor; +import android.util.Log; +import android.widget.TextView; +import android.widget.Toast; +import android.app.Activity; +import android.content.Intent; + +public class DetailedViewActivity extends Activity { + private static final String TAG = "DetailedViewActivity"; + private PassDbAdapter mDbHelper; + private long rowID; + + @Override + public void onCreate(Bundle savedInstanceState) { + Log.d(TAG, "Creating "+TAG); + super.onCreate(savedInstanceState); + setContentView(R.layout.detailed_view); + mDbHelper = new PassDbAdapter(this); + mDbHelper.openDataBase(); + + Bundle extras = getIntent().getExtras(); + rowID = extras.getLong(PassDbAdapter.ID); + fillData(); + } + + private void fillData() { + Cursor c = mDbHelper.at(rowID); + c.moveToFirst(); + TextView tv = (TextView)findViewById(R.id.tv_vendor); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.VENDOR))); + tv = (TextView)findViewById(R.id.tv_model); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.MODEL))); + tv = (TextView)findViewById(R.id.tv_version); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.VERSION))); + tv = (TextView)findViewById(R.id.tv_ac); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.ACCESSTYPE))); + tv = (TextView)findViewById(R.id.tv_user); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.USERNAME))); + tv = (TextView)findViewById(R.id.tv_pass); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.PASSWORD))); + tv = (TextView)findViewById(R.id.tv_priv); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.PRIVILEGES))); + tv = (TextView)findViewById(R.id.tv_notes); + tv.setText(c.getString(c.getColumnIndexOrThrow(PassDbAdapter.NOTES))); + } + +} diff --git a/src/org/foss/defaultpasswords/ModelListActivity.java b/src/org/foss/defaultpasswords/ModelListActivity.java new file mode 100644 index 0000000..96fcf3e --- /dev/null +++ b/src/org/foss/defaultpasswords/ModelListActivity.java @@ -0,0 +1,77 @@ +package org.foss.defaultpasswords; + +import org.foss.defaultpasswords.R; +import android.app.ListActivity; +import android.os.Bundle; +import android.database.Cursor; +import android.util.Log; +import android.widget.SimpleCursorAdapter; +import java.io.IOException; +import android.view.View; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; +import android.content.Intent; + +public class ModelListActivity extends ListActivity { + private static final String TAG = "ModelListActivity"; + private PassDbAdapter mDbHelper; + private long rowID; + private Cursor modelCursor; + + /** Called when the activity is first created. */ + @Override + public void onCreate(Bundle savedInstanceState) { + Log.d(TAG, "Creating "+TAG); + super.onCreate(savedInstanceState); + setContentView(R.layout.model_list); + mDbHelper = new PassDbAdapter(this); + mDbHelper.openDataBase(); + + Bundle extras = getIntent().getExtras(); + + if (extras != null) { + TextView tvVendorName = (TextView)findViewById(R.id.vendor_name); + tvVendorName.setText(extras.getString(PassDbAdapter.VENDOR)); + rowID = extras.getLong(PassDbAdapter.ID); + } else { + Toast.makeText(this, "Did not deliver to activity", Toast.LENGTH_LONG).show(); + throw new Error("Did not deliver to activity"); + } + + fillData(); + } + + + private void fillData() { + modelCursor = mDbHelper.fetchAllModelsForVendorAt(rowID); + Toast.makeText(this, "Found "+modelCursor.getCount()+" Models", Toast.LENGTH_LONG).show(); + startManagingCursor(modelCursor); + + if (modelCursor.getCount() == 1) { + modelCursor.moveToFirst(); + Intent i = new Intent(this, VersionListActivity.class); + i.putExtra(PassDbAdapter.ID, modelCursor.getLong(modelCursor.getColumnIndexOrThrow(PassDbAdapter.ID))); + i.putExtra(PassDbAdapter.MODEL, modelCursor.getString(modelCursor.getColumnIndexOrThrow(PassDbAdapter.MODEL))); + startActivityForResult(i, 0); + return; + } + + String[] from = new String[] {PassDbAdapter.MODEL}; + int[] to = new int[] {R.id.text1}; + SimpleCursorAdapter models = + new SimpleCursorAdapter(this, R.layout.vendor_row, modelCursor, from, to); + setListAdapter(models); + } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + super.onListItemClick(l, v, position, id); + Cursor c = modelCursor; + c.moveToPosition(position); + Intent i = new Intent(this, VersionListActivity.class); + i.putExtra(PassDbAdapter.ID, c.getLong(c.getColumnIndexOrThrow(PassDbAdapter.ID))); + i.putExtra(PassDbAdapter.MODEL, c.getString(c.getColumnIndexOrThrow(PassDbAdapter.MODEL))); + startActivityForResult(i, 0); + } +} \ No newline at end of file diff --git a/src/org/foss/defaultpasswords/PassDbAdapter.java b/src/org/foss/defaultpasswords/PassDbAdapter.java new file mode 100644 index 0000000..d45e8e1 --- /dev/null +++ b/src/org/foss/defaultpasswords/PassDbAdapter.java @@ -0,0 +1,246 @@ +package org.foss.defaultpasswords; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.FileOutputStream; + +/** + * Simple notes database access helper class. Defines the basic CRUD operations + * for the notepad example, and gives the ability to list all notes as well as + * retrieve or modify a specific note. + * + * This has been improved from the first version of this tutorial through the + * addition of better error handling and also using returning a Cursor instead + * of using a collection of inner classes (which is less scalable and not + * recommended). + */ +public class PassDbAdapter extends SQLiteOpenHelper{ + public static final String ID = "_id"; + public static final String VENDOR = "Vendor"; + public static final String MODEL = "Model"; + public static final String VERSION = "Version"; + public static final String ACCESSTYPE = "Access_Type"; + public static final String USERNAME = "Username"; + public static final String PASSWORD = "Password"; + public static final String PRIVILEGES = "Privileges"; + public static final String NOTES = "Notes"; + + private static final String TAG = "PassDbAdapter"; + //private DatabaseHelper mDbHelper; + private SQLiteDatabase mDb; + private static final String DB_PATH = "/data/data/org.foss.defaultpasswords/databases/"; + + private static final String DATABASE_TABLE = "default_passwords"; + private static final String DATABASE_NAME = DATABASE_TABLE+".db"; + private static final int DATABASE_VERSION = 4; + + private final Context mCtx; + public void createDataBase() throws IOException{ + boolean dbExist = checkDataBase(); + if(dbExist){ + //do nothing - database already exist + }else{ + //By calling this method and empty database will be created into the default system path + //of your application so we are gonna be able to overwrite that database with our database. + this.getReadableDatabase(); + try { + copyDataBase(); + } catch (IOException e) { + throw new Error("Error copying database"); + } + } + } + + /** + * Check if the database already exist to avoid re-copying the file each time you open the application. + * @return true if it exists, false if it doesn't + */ + private boolean checkDataBase(){ + SQLiteDatabase checkDB = null; + try{ + String myPath = DB_PATH + DATABASE_NAME; + checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); + }catch(SQLiteException e){ + //database does't exist yet. + } + if(checkDB != null){ + checkDB.close(); + } + return checkDB != null ? true : false; + } + + /** + * Copies your database from your local assets-folder to the just created empty database in the + * system folder, from where it can be accessed and handled. + * This is done by transfering bytestream. + * */ + private void copyDataBase() throws IOException{ + Log.i(TAG, "Copying new Password database"); + //Open your local db as the input stream + InputStream myInput = mCtx.getAssets().open(DATABASE_NAME); + // Path to the just created empty db + String outFileName = DB_PATH + DATABASE_NAME; + //Open the empty db as the output stream + OutputStream myOutput = new FileOutputStream(outFileName); + //transfer bytes from the inputfile to the outputfile + byte[] buffer = new byte[1024]; + int length; + while ((length = myInput.read(buffer))>0){ + myOutput.write(buffer, 0, length); + } + //Close the streams + myOutput.flush(); + myOutput.close(); + myInput.close(); + } + + public void openDataBase() throws SQLException{ + //Open the database + String myPath = DB_PATH + DATABASE_NAME; + mDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); + } + + /** + * Constructor - takes the context to allow the database to be + * opened/created + * + * @param ctx the Context within which to work + */ + public PassDbAdapter(Context ctx) { + super(ctx, DATABASE_TABLE, null, 1); + this.mCtx = ctx; + } + + /** + * Create a new note using the title and body provided. If the note is + * successfully created return the new rowId for that note, otherwise return + * a -1 to indicate failure. + * + * @param title the title of the note + * @param body the body of the note + * @return rowId or -1 if failed + * / + public long createNote(String title, String body) { + ContentValues initialValues = new ContentValues(); + initialValues.put(KEY_TITLE, title); + initialValues.put(KEY_BODY, body); + + return mDb.insert(DATABASE_TABLE, null, initialValues); + } + + /** + * Return a Cursor over the list of all notes in the database + * + * @return Cursor over all notes + */ + public Cursor fetchAllVendors() { + Log.w(TAG, "Fetching list of Vendors"); + Cursor C = mDb.query(DATABASE_TABLE, new String[] {ID, VENDOR}, null, + null, VENDOR, null, VENDOR+" ASC", null); + Log.w(TAG, "Got vendors " + C.getCount()); + return C; + } + + public String vendorNameAt(long rowID) { + Log.w(TAG, "Grab vendor name at rowId: "+String.valueOf(rowID)); + Cursor c = mDb.query(DATABASE_TABLE, new String[] {VENDOR}, + ID+" = ?", new String[] {String.valueOf(rowID)}, null, null, null, null); + if (c.isFirst() == false) + c.moveToFirst(); + + if (c.isNull(0)) { + return "UNKNOWN"; + } + return c.getString(0); + } + + public Cursor fetchAllModelsForVendorAt(long rowID) { + Log.w(TAG, "Fetching all Models for Vendor Matching at row "+rowID); + + Cursor c = mDb.query(DATABASE_TABLE, new String[] {ID, MODEL}, + VENDOR+" = ?", new String[] {vendorNameAt(rowID)}, + MODEL, null, MODEL+" ASC", null); + Log.w(TAG, "Got models "+c.getCount()); + return c; + } + + public Cursor at(long rowID) { + Log.w(TAG, "Grab everything at rowID: "+String.valueOf(rowID)); + Cursor c = mDb.query(DATABASE_TABLE, new String[] { + VENDOR, MODEL, VERSION, ACCESSTYPE, USERNAME, PASSWORD, PRIVILEGES, NOTES + }, ID+" = ?", new String[] {String.valueOf(rowID)}, null, null, null, null); + return c; + } + + public String modelNameAt(long rowID) { + Log.w(TAG, "Grab model name at rowId: "+String.valueOf(rowID)); + Cursor c = mDb.query(DATABASE_TABLE, new String[] {MODEL}, + ID+" = ?", new String[] {String.valueOf(rowID)}, null, null, null, null); + if (c.isFirst() == false) + c.moveToFirst(); + + if (c.isNull(0)) { + return "UNKNOWN"; + } + return c.getString(0); + } + + public Cursor fetchAllVersionsForModelAt(long rowID) { + Log.w(TAG, "Fetching all Versions for Model Matching at row "+rowID); + Cursor c = mDb.query(DATABASE_TABLE, new String[] {ID, VERSION}, + MODEL+" = ?", new String[] {modelNameAt(rowID)}, + VERSION, null, VERSION+" ASC", null); + Log.w(TAG, "Got versions "+c.getCount()); + return c; + } + + /** + * Return a Cursor positioned at the note that matches the given rowId + * + * @param rowId id of note to retrieve + * @return Cursor positioned to matching note, if found + * @throws SQLException if note could not be found/retrieved + * / + public Cursor fetchAllRecord(long rowId) throws SQLException { + Cursor mCursor = + mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, + KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null, + null, null, null, null); + if (mCursor != null) { + mCursor.moveToFirst(); + } + return mCursor; + + } + */ + @Override + public synchronized void close() { + + if(mDb != null) + mDb.close(); + + super.close(); + + } + + @Override + public void onCreate(SQLiteDatabase db) { + + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + } + +} + \ No newline at end of file diff --git a/src/org/foss/defaultpasswords/VersionListActivity.java b/src/org/foss/defaultpasswords/VersionListActivity.java new file mode 100644 index 0000000..6e311c8 --- /dev/null +++ b/src/org/foss/defaultpasswords/VersionListActivity.java @@ -0,0 +1,79 @@ +package org.foss.defaultpasswords; + +import org.foss.defaultpasswords.R; +import android.app.ListActivity; +import android.os.Bundle; +import android.database.Cursor; +import android.util.Log; +import android.widget.SimpleCursorAdapter; +import java.io.IOException; +import android.view.View; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; +import android.content.Intent; + +public class VersionListActivity extends ListActivity { + private static final String TAG = "VersionListActivity"; + private PassDbAdapter mDbHelper; + private long rowID; + private Cursor versionCursor; + + /** Called when the activity is first created. */ + @Override + public void onCreate(Bundle savedInstanceState) { + Log.d(TAG, "Creating "+TAG); + super.onCreate(savedInstanceState); + setContentView(R.layout.version_list); + mDbHelper = new PassDbAdapter(this); + mDbHelper.openDataBase(); + + Bundle extras = getIntent().getExtras(); + + if (extras != null) { + rowID = extras.getLong(PassDbAdapter.ID); + TextView tvVendorName = (TextView)findViewById(R.id.vendor_name); + tvVendorName.setText(mDbHelper.vendorNameAt(rowID)); + + TextView tvModelName = (TextView)findViewById(R.id.model_name); + tvModelName.setText(extras.getString(PassDbAdapter.MODEL)); + + } else { + Toast.makeText(this, "Did not deliver to activity", Toast.LENGTH_LONG).show(); + throw new Error("Did not deliver to activity"); + } + + fillData(); + } + + + private void fillData() { + versionCursor = mDbHelper.fetchAllVersionsForModelAt(rowID); + Toast.makeText(this, "Found "+versionCursor.getCount()+" Models", Toast.LENGTH_LONG).show(); + startManagingCursor(versionCursor); + + if (versionCursor.getCount() == 1) { + versionCursor.moveToFirst(); + Intent i = new Intent(this, DetailedViewActivity.class); + i.putExtra(PassDbAdapter.ID, versionCursor.getLong(versionCursor.getColumnIndexOrThrow(PassDbAdapter.ID))); + startActivityForResult(i, 0); + return; + } + + String[] from = new String[] {PassDbAdapter.VERSION}; + int[] to = new int[] {R.id.text1}; + SimpleCursorAdapter versions = + new SimpleCursorAdapter(this, R.layout.vendor_row, versionCursor, from, to); + setListAdapter(versions); + } + + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + super.onListItemClick(l, v, position, id); + Cursor c = versionCursor; + c.moveToPosition(position); + Intent i = new Intent(this, DetailedViewActivity.class); + i.putExtra(PassDbAdapter.ID, c.getLong(c.getColumnIndexOrThrow(PassDbAdapter.ID))); + startActivityForResult(i, 0); + } +} \ No newline at end of file
pingwin/DefaultPasswords
32ee6736c751ecd89da591c91de92859fe629870
cleaning up the code slightly, dropping the tables and creating the android_metadata table.
diff --git a/tools/password_list_generator.py b/tools/password_list_generator.py old mode 100644 new mode 100755 index e869ee0..b8f694b --- a/tools/password_list_generator.py +++ b/tools/password_list_generator.py @@ -1,37 +1,46 @@ +#!/usr/bin/env python2 + import xml.dom.minidom, urllib2 def main(): url = 'http://www.phenoelit-us.org/dpl/dpl.html' try: contents = open("/tmp/deleted_dpl.html").read() except: contents = urllib2.urlopen(url).read() open("/tmp/deleted_dpl.html", 'w').write(contents) dom = xml.dom.minidom.parseString(contents) mapit = [] count = 0 - print "CREATE TABLE default_passwords (" + print "drop table android_metadata;" + print "drop table default_passwords;" + print "CREATE TABLE android_metadata (locale TEXT DEFAULT 'en_US');" + print "INSERT INTO android_metadata VALUES ('en_US');" + print "CREATE TABLE default_passwords (_id integer primary key autoincrement, " for row in dom.getElementsByTagName('tr'): if not count: for itm in row.getElementsByTagName('td'): - mapit.append("`%s`" % itm.lastChild.lastChild.data) + mapit.append("`%s`" % itm.lastChild.lastChild.data.replace(' ', '_')) print ",".join(["%s varchar(64)" % it for it in mapit]) print "); " count += 1 continue - print "INSERT INTO default_passwords (" - print ",".join(mapit) - print ") VALUES " - tmpRow = [] - print "(" - for itm in row.getElementsByTagName('td'): - if not itm.lastChild: - tmpRow.append("NULL") - continue - tmpRow.append('"%s"' % itm.lastChild.data) - print ",".join(tmpRow) - print ");" + try: + ins = "INSERT INTO default_passwords (" + ins += ",".join(mapit) + ins += ") VALUES (" + tmpRow = [] + for itm in row.getElementsByTagName('td'): + if not itm.lastChild: + tmpRow.append("NULL") + continue + tmpRow.append('"%s"' % itm.lastChild.data) + ins += ",".join(tmpRow) + ins += ");" + print ins + except Exception, inst: + pass print ";" if __name__ == "__main__": main()
pingwin/DefaultPasswords
ef87f6416f7d75284b96a54c17f6d5ae98128c00
borrowed some files from DNSQuery to build up the structure, am going to try to build this app without the Eclipse SDK, we'll see how that goes tho :)
diff --git a/AndroidManifest.xml b/AndroidManifest.xml new file mode 100644 index 0000000..be831b5 --- /dev/null +++ b/AndroidManifest.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="org.foss.defaultpasswords" + android:versionCode="1" + android:versionName="1.0"> + <application android:icon="@drawable/icon" android:label="@string/app_name"> + <activity android:name=".Default Passwords" + android:label="@string/app_name"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + + <activity android:name="ServerList"> + +</activity> +<activity android:name="ResolverEdit"></activity> + + + +</application> + <uses-sdk android:minSdkVersion="3" /> +</manifest> diff --git a/default.properties b/default.properties new file mode 100644 index 0000000..a1ef8e9 --- /dev/null +++ b/default.properties @@ -0,0 +1,13 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "build.properties", and override values to adapt the script to your +# project structure. + +# Indicates whether an apk should be generated for each density. +split.density=false +# Project target. +target=android-3 diff --git a/res/layout/main.xml b/res/layout/main.xml new file mode 100644 index 0000000..0b61636 --- /dev/null +++ b/res/layout/main.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="utf-8"?> +<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" android:layout_height="fill_parent" + android:keepScreenOn="true" android:saveEnabled="true"> + <RelativeLayout android:layout_width="fill_parent" + android:layout_height="wrap_content" android:isScrollContainer="true" + android:keepScreenOn="true"> + + <!-- Query TextView and EditText --> + <TextView android:id="@+id/query_pros" android:layout_width="fill_parent" + android:layout_height="wrap_content" android:text="Enter Domain Name:" /> + + <EditText android:id="@+id/query" android:layout_width="fill_parent" + android:layout_height="wrap_content" android:autoText="true" + android:layout_below="@id/query_pros" android:text="comwired.com" + android:saveEnabled="true" android:singleLine="true"> + <requestFocus /> + </EditText> + + <!-- QType TextView and Spinner (Align Left) --> + <TextView android:id="@+id/qtype_pros" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:text="Select Query Type:" + android:layout_below="@id/query" /> + + <Spinner android:id="@+id/qtype" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:drawSelectorOnTop="true" + android:prompt="@string/choose_qtype" android:layout_below="@id/qtype_pros" + android:saveEnabled="true" android:entries="@+array/rr_types" /> + + <!-- Server TextView and Spinner (Align Right) --> + <TextView android:id="@+id/server_pros" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:text="Enter Server To Hit:" + android:layout_alignParentRight="true" android:layout_below="@id/query" /> + + <Spinner android:id="@+id/server_spinner" + android:layout_width="wrap_content" android:layout_height="wrap_content" + android:drawSelectorOnTop="true" android:layout_alignParentRight="true" + android:prompt="@string/choose_server" android:layout_below="@id/server_pros" /> + + <!-- Direct Server Entry, Below the above two --> + <EditText android:id="@+id/server" android:layout_width="fill_parent" + android:layout_height="wrap_content" android:autoText="true" + android:layout_below="@id/server_spinner" android:text="8.20.241.1" + android:bufferType="normal" android:lines="1" + android:scrollHorizontally="false" android:saveEnabled="true" + android:selectAllOnFocus="true" /> + + <!-- Go Button --> + <Button android:id="@+id/go" android:layout_width="wrap_content" + android:layout_height="wrap_content" android:layout_below="@id/server" + android:layout_alignParentRight="true" android:layout_marginLeft="10dip" + android:text="Go" /> + + <!-- Display Results of query --> + <TextView android:id="@+id/result_view" android:layout_width="fill_parent" + android:layout_height="wrap_content" android:layout_below="@id/go" + android:scrollbars="vertical" /> + </RelativeLayout> +</ScrollView> + \ No newline at end of file diff --git a/src/org/foss/defaultpasswords/DefaultPasswords.java b/src/org/foss/defaultpasswords/DefaultPasswords.java new file mode 100644 index 0000000..06abf4e --- /dev/null +++ b/src/org/foss/defaultpasswords/DefaultPasswords.java @@ -0,0 +1,27 @@ +package org.foss.defaultpasswords; + +import android.app.Activity; +import android.widget.SimpleCursorAdapter; +import android.database.Cursor; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; +import android.widget.ArrayAdapter; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.util.Log; + +public class DefaultPasswords extends Activity { + private static final String TAG = "DefaultPasswords"; + + private Cursor dbCursor; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + } +} \ No newline at end of file diff --git a/tools/password_list_generator.py b/tools/password_list_generator.py new file mode 100644 index 0000000..e869ee0 --- /dev/null +++ b/tools/password_list_generator.py @@ -0,0 +1,37 @@ +import xml.dom.minidom, urllib2 + +def main(): + url = 'http://www.phenoelit-us.org/dpl/dpl.html' + try: + contents = open("/tmp/deleted_dpl.html").read() + except: + contents = urllib2.urlopen(url).read() + open("/tmp/deleted_dpl.html", 'w').write(contents) + dom = xml.dom.minidom.parseString(contents) + mapit = [] + count = 0 + print "CREATE TABLE default_passwords (" + for row in dom.getElementsByTagName('tr'): + if not count: + for itm in row.getElementsByTagName('td'): + mapit.append("`%s`" % itm.lastChild.lastChild.data) + print ",".join(["%s varchar(64)" % it for it in mapit]) + print "); " + count += 1 + continue + print "INSERT INTO default_passwords (" + print ",".join(mapit) + print ") VALUES " + tmpRow = [] + print "(" + for itm in row.getElementsByTagName('td'): + if not itm.lastChild: + tmpRow.append("NULL") + continue + tmpRow.append('"%s"' % itm.lastChild.data) + print ",".join(tmpRow) + print ");" + print ";" + +if __name__ == "__main__": + main()
pingwin/DefaultPasswords
a1d177345b0b3111d94de6ffb6fc82ca59a9c65a
Adding the README file
diff --git a/README b/README new file mode 100644 index 0000000..e1154d4 --- /dev/null +++ b/README @@ -0,0 +1 @@ +Will start on this when I get home. Already have the DB and importor from 1 source, will need more as the project progresses.
gbarr/MojoX-Renderer-YAML
59690ff8280472904f55f1a34d2ac388e35eca09
Initial version
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7756be0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +Makefile +blib +pm_to_blib +.*.swp +*.bak diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..80fbe6d --- /dev/null +++ b/MANIFEST @@ -0,0 +1,18 @@ +.gitignore +inc/Module/AutoInstall.pm +inc/Module/Install.pm +inc/Module/Install/AutoInstall.pm +inc/Module/Install/Base.pm +inc/Module/Install/Can.pm +inc/Module/Install/Fetch.pm +inc/Module/Install/Include.pm +inc/Module/Install/Makefile.pm +inc/Module/Install/Metadata.pm +inc/Module/Install/Win32.pm +inc/Module/Install/WriteAll.pm +lib/MojoX/Renderer/YAML.pm +Makefile.PL +MANIFEST This list of files +META.yml +SIGNATURE +t/00-load.t diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..8b55a12 --- /dev/null +++ b/META.yml @@ -0,0 +1,22 @@ +--- +abstract: 'YAML renderer for Mojo' +author: + - 'Graham Barr <[email protected]>' +distribution_type: module +generated_by: 'Module::Install version 0.75' +license: perl +meta-spec: + url: http://module-build.sourceforge.net/META-spec-v1.3.html + version: 1.3 +module_name: MojoX::Renderer::YAML +name: MojoX-Renderer-YAML +no_index: + directory: + - inc + - t +requires: + YAML::Syck: 0 + perl: 5.8.8 +resources: + repository: http://git.goingon.net/?p=MojoX-Renderer-YAML.git +version: 0.10 diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..505f6ec --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,18 @@ +# -*- perl -*- + +use inc::Module::Install; + +perl_version 5.008008; + +module_name 'MojoX::Renderer::YAML'; +all_from 'lib/MojoX/Renderer/YAML.pm'; + +resources repository => 'http://git.goingon.net/?p=MojoX-Renderer-YAML.git'; + +requires 'YAML::Syck'; + +auto_install; + +WriteAll( + sign => 1 +); diff --git a/SIGNATURE b/SIGNATURE new file mode 100644 index 0000000..73c2215 --- /dev/null +++ b/SIGNATURE @@ -0,0 +1,40 @@ +This file contains message digests of all files listed in MANIFEST, +signed via the Module::Signature module, version 0.55. + +To verify the content in this distribution, first make sure you have +Module::Signature installed, then type: + + % cpansign -v + +It will check each file's integrity, as well as the signature's +validity. If "==> Signature verified OK! <==" is not displayed, +the distribution may already have been compromised, and you should +not run its Makefile.PL or Build.PL. + +-----BEGIN PGP SIGNED MESSAGE----- +Hash: SHA1 + +SHA1 953a5ae4b639e8ec05d47860235538da901afd22 .gitignore +SHA1 f32b86a8446adae8e1dc17df415c8debdfe66cf6 MANIFEST +SHA1 8fec11b7344481b378e4150c818ad31bb2f863cd META.yml +SHA1 be15cb1635aac3f503b704a1d6996df56e990f84 Makefile.PL +SHA1 603bb9de29fb8cba7f13409c546750972eff645d inc/Module/AutoInstall.pm +SHA1 f0577f8f88a6703e9bca2d10196cfd293f3d6f2f inc/Module/Install.pm +SHA1 b2a2c9b6cb4b1bcd119825acc707f45946d8b126 inc/Module/Install/AutoInstall.pm +SHA1 5d574849849860b8cf06035cc6f1a306c66cb326 inc/Module/Install/Base.pm +SHA1 c30f50bc2a1542dff17f84a54d9316f3c3c6299e inc/Module/Install/Can.pm +SHA1 9b618efcd783f6ed4bab84fa22b31886fcc38d57 inc/Module/Install/Fetch.pm +SHA1 808d4b2d764185a34c89e675bb4eaad18c075b14 inc/Module/Install/Include.pm +SHA1 cd14c8de2a67b0f14df9bc20c27f3edabd359d1b inc/Module/Install/Makefile.pm +SHA1 a2162aec678d21988fce47ab805cf01773196292 inc/Module/Install/Metadata.pm +SHA1 4ae5d56e11e640bd9520634dde6d563926f6d98a inc/Module/Install/Win32.pm +SHA1 587cc94b52b640fe2d4972253b6369aa951e2210 inc/Module/Install/WriteAll.pm +SHA1 767863ea46a07929141852ca905f02a18d0e7b9a lib/MojoX/Renderer/YAML.pm +SHA1 7a725f8ea106715bf89ab395f2c71176a11c820d t/00-load.t +-----BEGIN PGP SIGNATURE----- +Version: GnuPG v1.4.9 (Darwin) + +iEYEARECAAYFAkkvX5AACgkQR0BL4gbYw3Qj8QCfdybAF/fO8kxu8MwOE2UFxd1/ +uJAAoIuWx5BJH7vDBfEgEfpSvkDJhXyu +=jQFt +-----END PGP SIGNATURE----- diff --git a/inc/Module/AutoInstall.pm b/inc/Module/AutoInstall.pm new file mode 100644 index 0000000..7efc552 --- /dev/null +++ b/inc/Module/AutoInstall.pm @@ -0,0 +1,768 @@ +#line 1 +package Module::AutoInstall; + +use strict; +use Cwd (); +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION}; +BEGIN { + $VERSION = '1.03'; +} + +# special map on pre-defined feature sets +my %FeatureMap = ( + '' => 'Core Features', # XXX: deprecated + '-core' => 'Core Features', +); + +# various lexical flags +my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS ); +my ( $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly ); +my ( $PostambleActions, $PostambleUsed ); + +# See if it's a testing or non-interactive session +_accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN ); +_init(); + +sub _accept_default { + $AcceptDefault = shift; +} + +sub missing_modules { + return @Missing; +} + +sub do_install { + __PACKAGE__->install( + [ + $Config + ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + : () + ], + @Missing, + ); +} + +# initialize various flags, and/or perform install +sub _init { + foreach my $arg ( + @ARGV, + split( + /[\s\t]+/, + $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || '' + ) + ) + { + if ( $arg =~ /^--config=(.*)$/ ) { + $Config = [ split( ',', $1 ) ]; + } + elsif ( $arg =~ /^--installdeps=(.*)$/ ) { + __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) ); + exit 0; + } + elsif ( $arg =~ /^--default(?:deps)?$/ ) { + $AcceptDefault = 1; + } + elsif ( $arg =~ /^--check(?:deps)?$/ ) { + $CheckOnly = 1; + } + elsif ( $arg =~ /^--skip(?:deps)?$/ ) { + $SkipInstall = 1; + } + elsif ( $arg =~ /^--test(?:only)?$/ ) { + $TestOnly = 1; + } + } +} + +# overrides MakeMaker's prompt() to automatically accept the default choice +sub _prompt { + goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault; + + my ( $prompt, $default ) = @_; + my $y = ( $default =~ /^[Yy]/ ); + + print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] '; + print "$default\n"; + return $default; +} + +# the workhorse +sub import { + my $class = shift; + my @args = @_ or return; + my $core_all; + + print "*** $class version " . $class->VERSION . "\n"; + print "*** Checking for Perl dependencies...\n"; + + my $cwd = Cwd::cwd(); + + $Config = []; + + my $maxlen = length( + ( + sort { length($b) <=> length($a) } + grep { /^[^\-]/ } + map { + ref($_) + ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} ) + : '' + } + map { +{@args}->{$_} } + grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} } + )[0] + ); + + while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) { + my ( @required, @tests, @skiptests ); + my $default = 1; + my $conflict = 0; + + if ( $feature =~ m/^-(\w+)$/ ) { + my $option = lc($1); + + # check for a newer version of myself + _update_to( $modules, @_ ) and return if $option eq 'version'; + + # sets CPAN configuration options + $Config = $modules if $option eq 'config'; + + # promote every features to core status + $core_all = ( $modules =~ /^all$/i ) and next + if $option eq 'core'; + + next unless $option eq 'core'; + } + + print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n"; + + $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' ); + + unshift @$modules, -default => &{ shift(@$modules) } + if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability + + while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) { + if ( $mod =~ m/^-(\w+)$/ ) { + my $option = lc($1); + + $default = $arg if ( $option eq 'default' ); + $conflict = $arg if ( $option eq 'conflict' ); + @tests = @{$arg} if ( $option eq 'tests' ); + @skiptests = @{$arg} if ( $option eq 'skiptests' ); + + next; + } + + printf( "- %-${maxlen}s ...", $mod ); + + if ( $arg and $arg =~ /^\D/ ) { + unshift @$modules, $arg; + $arg = 0; + } + + # XXX: check for conflicts and uninstalls(!) them. + if ( + defined( my $cur = _version_check( _load($mod), $arg ||= 0 ) ) ) + { + print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n"; + push @Existing, $mod => $arg; + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + else { + print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n"; + push @required, $mod => $arg; + } + } + + next unless @required; + + my $mandatory = ( $feature eq '-core' or $core_all ); + + if ( + !$SkipInstall + and ( + $CheckOnly + or _prompt( + qq{==> Auto-install the } + . ( @required / 2 ) + . ( $mandatory ? ' mandatory' : ' optional' ) + . qq{ module(s) from CPAN?}, + $default ? 'y' : 'n', + ) =~ /^[Yy]/ + ) + ) + { + push( @Missing, @required ); + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + + elsif ( !$SkipInstall + and $default + and $mandatory + and + _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', ) + =~ /^[Nn]/ ) + { + push( @Missing, @required ); + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + + else { + $DisabledTests{$_} = 1 for map { glob($_) } @tests; + } + } + + $UnderCPAN = _check_lock(); # check for $UnderCPAN + + if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) { + require Config; + print +"*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n"; + + # make an educated guess of whether we'll need root permission. + print " (You may need to do that as the 'root' user.)\n" + if eval '$>'; + } + print "*** $class configuration finished.\n"; + + chdir $cwd; + + # import to main:: + no strict 'refs'; + *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main'; +} + +# Check to see if we are currently running under CPAN.pm and/or CPANPLUS; +# if we are, then we simply let it taking care of our dependencies +sub _check_lock { + return unless @Missing; + + if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) { + print <<'END_MESSAGE'; + +*** Since we're running under CPANPLUS, I'll just let it take care + of the dependency's installation later. +END_MESSAGE + return 1; + } + + _load_cpan(); + + # Find the CPAN lock-file + my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" ); + return unless -f $lock; + + # Check the lock + local *LOCK; + return unless open(LOCK, $lock); + + if ( + ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() ) + and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore' + ) { + print <<'END_MESSAGE'; + +*** Since we're running under CPAN, I'll just let it take care + of the dependency's installation later. +END_MESSAGE + return 1; + } + + close LOCK; + return; +} + +sub install { + my $class = shift; + + my $i; # used below to strip leading '-' from config keys + my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } ); + + my ( @modules, @installed ); + while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) { + + # grep out those already installed + if ( defined( _version_check( _load($pkg), $ver ) ) ) { + push @installed, $pkg; + } + else { + push @modules, $pkg, $ver; + } + } + + return @installed unless @modules; # nothing to do + return @installed if _check_lock(); # defer to the CPAN shell + + print "*** Installing dependencies...\n"; + + return unless _connected_to('cpan.org'); + + my %args = @config; + my %failed; + local *FAILED; + if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) { + while (<FAILED>) { chomp; $failed{$_}++ } + close FAILED; + + my @newmod; + while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) { + push @newmod, ( $k => $v ) unless $failed{$k}; + } + @modules = @newmod; + } + + if ( _has_cpanplus() ) { + _install_cpanplus( \@modules, \@config ); + } else { + _install_cpan( \@modules, \@config ); + } + + print "*** $class installation finished.\n"; + + # see if we have successfully installed them + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + if ( defined( _version_check( _load($pkg), $ver ) ) ) { + push @installed, $pkg; + } + elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) { + print FAILED "$pkg\n"; + } + } + + close FAILED if $args{do_once}; + + return @installed; +} + +sub _install_cpanplus { + my @modules = @{ +shift }; + my @config = _cpanplus_config( @{ +shift } ); + my $installed = 0; + + require CPANPLUS::Backend; + my $cp = CPANPLUS::Backend->new; + my $conf = $cp->configure_object; + + return unless $conf->can('conf') # 0.05x+ with "sudo" support + or _can_write($conf->_get_build('base')); # 0.04x + + # if we're root, set UNINST=1 to avoid trouble unless user asked for it. + my $makeflags = $conf->get_conf('makeflags') || ''; + if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) { + # 0.03+ uses a hashref here + $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST}; + + } else { + # 0.02 and below uses a scalar + $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) + if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); + + } + $conf->set_conf( makeflags => $makeflags ); + $conf->set_conf( prereqs => 1 ); + + + + while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) { + $conf->set_conf( $key, $val ); + } + + my $modtree = $cp->module_tree; + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + print "*** Installing $pkg...\n"; + + MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; + + my $success; + my $obj = $modtree->{$pkg}; + + if ( $obj and defined( _version_check( $obj->{version}, $ver ) ) ) { + my $pathname = $pkg; + $pathname =~ s/::/\\W/; + + foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { + delete $INC{$inc}; + } + + my $rv = $cp->install( modules => [ $obj->{module} ] ); + + if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) { + print "*** $pkg successfully installed.\n"; + $success = 1; + } else { + print "*** $pkg installation cancelled.\n"; + $success = 0; + } + + $installed += $success; + } else { + print << "."; +*** Could not find a version $ver or above for $pkg; skipping. +. + } + + MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; + } + + return $installed; +} + +sub _cpanplus_config { + my @config = (); + while ( @_ ) { + my ($key, $value) = (shift(), shift()); + if ( $key eq 'prerequisites_policy' ) { + if ( $value eq 'follow' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL(); + } elsif ( $value eq 'ask' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_ASK(); + } elsif ( $value eq 'ignore' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE(); + } else { + die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n"; + } + } else { + die "*** Cannot convert option $key to CPANPLUS version.\n"; + } + } + return @config; +} + +sub _install_cpan { + my @modules = @{ +shift }; + my @config = @{ +shift }; + my $installed = 0; + my %args; + + _load_cpan(); + require Config; + + if (CPAN->VERSION < 1.80) { + # no "sudo" support, probe for writableness + return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) ) + and _can_write( $Config::Config{sitelib} ); + } + + # if we're root, set UNINST=1 to avoid trouble unless user asked for it. + my $makeflags = $CPAN::Config->{make_install_arg} || ''; + $CPAN::Config->{make_install_arg} = + join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) + if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); + + # don't show start-up info + $CPAN::Config->{inhibit_startup_message} = 1; + + # set additional options + while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) { + ( $args{$opt} = $arg, next ) + if $opt =~ /^force$/; # pseudo-option + $CPAN::Config->{$opt} = $arg; + } + + local $CPAN::Config->{prerequisites_policy} = 'follow'; + + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; + + print "*** Installing $pkg...\n"; + + my $obj = CPAN::Shell->expand( Module => $pkg ); + my $success = 0; + + if ( $obj and defined( _version_check( $obj->cpan_version, $ver ) ) ) { + my $pathname = $pkg; + $pathname =~ s/::/\\W/; + + foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { + delete $INC{$inc}; + } + + my $rv = $args{force} ? CPAN::Shell->force( install => $pkg ) + : CPAN::Shell->install($pkg); + $rv ||= eval { + $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, ) + ->{install} + if $CPAN::META; + }; + + if ( $rv eq 'YES' ) { + print "*** $pkg successfully installed.\n"; + $success = 1; + } + else { + print "*** $pkg installation failed.\n"; + $success = 0; + } + + $installed += $success; + } + else { + print << "."; +*** Could not find a version $ver or above for $pkg; skipping. +. + } + + MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; + } + + return $installed; +} + +sub _has_cpanplus { + return ( + $HasCPANPLUS = ( + $INC{'CPANPLUS/Config.pm'} + or _load('CPANPLUS::Shell::Default') + ) + ); +} + +# make guesses on whether we're under the CPAN installation directory +sub _under_cpan { + require Cwd; + require File::Spec; + + my $cwd = File::Spec->canonpath( Cwd::cwd() ); + my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} ); + + return ( index( $cwd, $cpan ) > -1 ); +} + +sub _update_to { + my $class = __PACKAGE__; + my $ver = shift; + + return + if defined( _version_check( _load($class), $ver ) ); # no need to upgrade + + if ( + _prompt( "==> A newer version of $class ($ver) is required. Install?", + 'y' ) =~ /^[Nn]/ + ) + { + die "*** Please install $class $ver manually.\n"; + } + + print << "."; +*** Trying to fetch it from CPAN... +. + + # install ourselves + _load($class) and return $class->import(@_) + if $class->install( [], $class, $ver ); + + print << '.'; exit 1; + +*** Cannot bootstrap myself. :-( Installation terminated. +. +} + +# check if we're connected to some host, using inet_aton +sub _connected_to { + my $site = shift; + + return ( + ( _load('Socket') and Socket::inet_aton($site) ) or _prompt( + qq( +*** Your host cannot resolve the domain name '$site', which + probably means the Internet connections are unavailable. +==> Should we try to install the required module(s) anyway?), 'n' + ) =~ /^[Yy]/ + ); +} + +# check if a directory is writable; may create it on demand +sub _can_write { + my $path = shift; + mkdir( $path, 0755 ) unless -e $path; + + return 1 if -w $path; + + print << "."; +*** You are not allowed to write to the directory '$path'; + the installation may fail due to insufficient permissions. +. + + if ( + eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt( + qq( +==> Should we try to re-execute the autoinstall process with 'sudo'?), + ((-t STDIN) ? 'y' : 'n') + ) =~ /^[Yy]/ + ) + { + + # try to bootstrap ourselves from sudo + print << "."; +*** Trying to re-execute the autoinstall process with 'sudo'... +. + my $missing = join( ',', @Missing ); + my $config = join( ',', + UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + if $Config; + + return + unless system( 'sudo', $^X, $0, "--config=$config", + "--installdeps=$missing" ); + + print << "."; +*** The 'sudo' command exited with error! Resuming... +. + } + + return _prompt( + qq( +==> Should we try to install the required module(s) anyway?), 'n' + ) =~ /^[Yy]/; +} + +# load a module and return the version it reports +sub _load { + my $mod = pop; # class/instance doesn't matter + my $file = $mod; + + $file =~ s|::|/|g; + $file .= '.pm'; + + local $@; + return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 ); +} + +# Load CPAN.pm and it's configuration +sub _load_cpan { + return if $CPAN::VERSION; + require CPAN; + if ( $CPAN::HandleConfig::VERSION ) { + # Newer versions of CPAN have a HandleConfig module + CPAN::HandleConfig->load; + } else { + # Older versions had the load method in Config directly + CPAN::Config->load; + } +} + +# compare two versions, either use Sort::Versions or plain comparison +sub _version_check { + my ( $cur, $min ) = @_; + return unless defined $cur; + + $cur =~ s/\s+$//; + + # check for version numbers that are not in decimal format + if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) { + if ( ( $version::VERSION or defined( _load('version') )) and + version->can('new') + ) { + + # use version.pm if it is installed. + return ( + ( version->new($cur) >= version->new($min) ) ? $cur : undef ); + } + elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) ) + { + + # use Sort::Versions as the sorting algorithm for a.b.c versions + return ( ( Sort::Versions::versioncmp( $cur, $min ) != -1 ) + ? $cur + : undef ); + } + + warn "Cannot reliably compare non-decimal formatted versions.\n" + . "Please install version.pm or Sort::Versions.\n"; + } + + # plain comparison + local $^W = 0; # shuts off 'not numeric' bugs + return ( $cur >= $min ? $cur : undef ); +} + +# nothing; this usage is deprecated. +sub main::PREREQ_PM { return {}; } + +sub _make_args { + my %args = @_; + + $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing } + if $UnderCPAN or $TestOnly; + + if ( $args{EXE_FILES} and -e 'MANIFEST' ) { + require ExtUtils::Manifest; + my $manifest = ExtUtils::Manifest::maniread('MANIFEST'); + + $args{EXE_FILES} = + [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ]; + } + + $args{test}{TESTS} ||= 't/*.t'; + $args{test}{TESTS} = join( ' ', + grep { !exists( $DisabledTests{$_} ) } + map { glob($_) } split( /\s+/, $args{test}{TESTS} ) ); + + my $missing = join( ',', @Missing ); + my $config = + join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + if $Config; + + $PostambleActions = ( + $missing + ? "\$(PERL) $0 --config=$config --installdeps=$missing" + : "\$(NOECHO) \$(NOOP)" + ); + + return %args; +} + +# a wrapper to ExtUtils::MakeMaker::WriteMakefile +sub Write { + require Carp; + Carp::croak "WriteMakefile: Need even number of args" if @_ % 2; + + if ($CheckOnly) { + print << "."; +*** Makefile not written in check-only mode. +. + return; + } + + my %args = _make_args(@_); + + no strict 'refs'; + + $PostambleUsed = 0; + local *MY::postamble = \&postamble unless defined &MY::postamble; + ExtUtils::MakeMaker::WriteMakefile(%args); + + print << "." unless $PostambleUsed; +*** WARNING: Makefile written with customized MY::postamble() without + including contents from Module::AutoInstall::postamble() -- + auto installation features disabled. Please contact the author. +. + + return 1; +} + +sub postamble { + $PostambleUsed = 1; + + return << "."; + +config :: installdeps +\t\$(NOECHO) \$(NOOP) + +checkdeps :: +\t\$(PERL) $0 --checkdeps + +installdeps :: +\t$PostambleActions + +. + +} + +1; + +__END__ + +#line 1003 diff --git a/inc/Module/Install.pm b/inc/Module/Install.pm new file mode 100644 index 0000000..8fb6b20 --- /dev/null +++ b/inc/Module/Install.pm @@ -0,0 +1,353 @@ +#line 1 +package Module::Install; + +# For any maintainers: +# The load order for Module::Install is a bit magic. +# It goes something like this... +# +# IF ( host has Module::Install installed, creating author mode ) { +# 1. Makefile.PL calls "use inc::Module::Install" +# 2. $INC{inc/Module/Install.pm} set to installed version of inc::Module::Install +# 3. The installed version of inc::Module::Install loads +# 4. inc::Module::Install calls "require Module::Install" +# 5. The ./inc/ version of Module::Install loads +# } ELSE { +# 1. Makefile.PL calls "use inc::Module::Install" +# 2. $INC{inc/Module/Install.pm} set to ./inc/ version of Module::Install +# 3. The ./inc/ version of Module::Install loads +# } + +BEGIN { + require 5.004; +} +use strict 'vars'; + +use vars qw{$VERSION}; +BEGIN { + # All Module::Install core packages now require synchronised versions. + # This will be used to ensure we don't accidentally load old or + # different versions of modules. + # This is not enforced yet, but will be some time in the next few + # releases once we can make sure it won't clash with custom + # Module::Install extensions. + $VERSION = '0.75'; + + *inc::Module::Install::VERSION = *VERSION; + @inc::Module::Install::ISA = __PACKAGE__; + +} + + + + + +# Whether or not inc::Module::Install is actually loaded, the +# $INC{inc/Module/Install.pm} is what will still get set as long as +# the caller loaded module this in the documented manner. +# If not set, the caller may NOT have loaded the bundled version, and thus +# they may not have a MI version that works with the Makefile.PL. This would +# result in false errors or unexpected behaviour. And we don't want that. +my $file = join( '/', 'inc', split /::/, __PACKAGE__ ) . '.pm'; +unless ( $INC{$file} ) { die <<"END_DIE" } + +Please invoke ${\__PACKAGE__} with: + + use inc::${\__PACKAGE__}; + +not: + + use ${\__PACKAGE__}; + +END_DIE + + + + + +# If the script that is loading Module::Install is from the future, +# then make will detect this and cause it to re-run over and over +# again. This is bad. Rather than taking action to touch it (which +# is unreliable on some platforms and requires write permissions) +# for now we should catch this and refuse to run. +if ( -f $0 and (stat($0))[9] > time ) { die <<"END_DIE" } + +Your installer $0 has a modification time in the future. + +This is known to create infinite loops in make. + +Please correct this, then run $0 again. + +END_DIE + + + + + +# Build.PL was formerly supported, but no longer is due to excessive +# difficulty in implementing every single feature twice. +if ( $0 =~ /Build.PL$/i ) { die <<"END_DIE" } + +Module::Install no longer supports Build.PL. + +It was impossible to maintain duel backends, and has been deprecated. + +Please remove all Build.PL files and only use the Makefile.PL installer. + +END_DIE + + + + + +# To save some more typing in Module::Install installers, every... +# use inc::Module::Install +# ...also acts as an implicit use strict. +$^H |= strict::bits(qw(refs subs vars)); + + + + + +use Cwd (); +use File::Find (); +use File::Path (); +use FindBin; + +sub autoload { + my $self = shift; + my $who = $self->_caller; + my $cwd = Cwd::cwd(); + my $sym = "${who}::AUTOLOAD"; + $sym->{$cwd} = sub { + my $pwd = Cwd::cwd(); + if ( my $code = $sym->{$pwd} ) { + # delegate back to parent dirs + goto &$code unless $cwd eq $pwd; + } + $$sym =~ /([^:]+)$/ or die "Cannot autoload $who - $sym"; + unshift @_, ( $self, $1 ); + goto &{$self->can('call')} unless uc($1) eq $1; + }; +} + +sub import { + my $class = shift; + my $self = $class->new(@_); + my $who = $self->_caller; + + unless ( -f $self->{file} ) { + require "$self->{path}/$self->{dispatch}.pm"; + File::Path::mkpath("$self->{prefix}/$self->{author}"); + $self->{admin} = "$self->{name}::$self->{dispatch}"->new( _top => $self ); + $self->{admin}->init; + @_ = ($class, _self => $self); + goto &{"$self->{name}::import"}; + } + + *{"${who}::AUTOLOAD"} = $self->autoload; + $self->preload; + + # Unregister loader and worker packages so subdirs can use them again + delete $INC{"$self->{file}"}; + delete $INC{"$self->{path}.pm"}; + + return 1; +} + +sub preload { + my $self = shift; + unless ( $self->{extensions} ) { + $self->load_extensions( + "$self->{prefix}/$self->{path}", $self + ); + } + + my @exts = @{$self->{extensions}}; + unless ( @exts ) { + my $admin = $self->{admin}; + @exts = $admin->load_all_extensions; + } + + my %seen; + foreach my $obj ( @exts ) { + while (my ($method, $glob) = each %{ref($obj) . '::'}) { + next unless $obj->can($method); + next if $method =~ /^_/; + next if $method eq uc($method); + $seen{$method}++; + } + } + + my $who = $self->_caller; + foreach my $name ( sort keys %seen ) { + *{"${who}::$name"} = sub { + ${"${who}::AUTOLOAD"} = "${who}::$name"; + goto &{"${who}::AUTOLOAD"}; + }; + } +} + +sub new { + my ($class, %args) = @_; + + # ignore the prefix on extension modules built from top level. + my $base_path = Cwd::abs_path($FindBin::Bin); + unless ( Cwd::abs_path(Cwd::cwd()) eq $base_path ) { + delete $args{prefix}; + } + + return $args{_self} if $args{_self}; + + $args{dispatch} ||= 'Admin'; + $args{prefix} ||= 'inc'; + $args{author} ||= ($^O eq 'VMS' ? '_author' : '.author'); + $args{bundle} ||= 'inc/BUNDLES'; + $args{base} ||= $base_path; + $class =~ s/^\Q$args{prefix}\E:://; + $args{name} ||= $class; + $args{version} ||= $class->VERSION; + unless ( $args{path} ) { + $args{path} = $args{name}; + $args{path} =~ s!::!/!g; + } + $args{file} ||= "$args{base}/$args{prefix}/$args{path}.pm"; + $args{wrote} = 0; + + bless( \%args, $class ); +} + +sub call { + my ($self, $method) = @_; + my $obj = $self->load($method) or return; + splice(@_, 0, 2, $obj); + goto &{$obj->can($method)}; +} + +sub load { + my ($self, $method) = @_; + + $self->load_extensions( + "$self->{prefix}/$self->{path}", $self + ) unless $self->{extensions}; + + foreach my $obj (@{$self->{extensions}}) { + return $obj if $obj->can($method); + } + + my $admin = $self->{admin} or die <<"END_DIE"; +The '$method' method does not exist in the '$self->{prefix}' path! +Please remove the '$self->{prefix}' directory and run $0 again to load it. +END_DIE + + my $obj = $admin->load($method, 1); + push @{$self->{extensions}}, $obj; + + $obj; +} + +sub load_extensions { + my ($self, $path, $top) = @_; + + unless ( grep { lc $_ eq lc $self->{prefix} } @INC ) { + unshift @INC, $self->{prefix}; + } + + foreach my $rv ( $self->find_extensions($path) ) { + my ($file, $pkg) = @{$rv}; + next if $self->{pathnames}{$pkg}; + + local $@; + my $new = eval { require $file; $pkg->can('new') }; + unless ( $new ) { + warn $@ if $@; + next; + } + $self->{pathnames}{$pkg} = delete $INC{$file}; + push @{$self->{extensions}}, &{$new}($pkg, _top => $top ); + } + + $self->{extensions} ||= []; +} + +sub find_extensions { + my ($self, $path) = @_; + + my @found; + File::Find::find( sub { + my $file = $File::Find::name; + return unless $file =~ m!^\Q$path\E/(.+)\.pm\Z!is; + my $subpath = $1; + return if lc($subpath) eq lc($self->{dispatch}); + + $file = "$self->{path}/$subpath.pm"; + my $pkg = "$self->{name}::$subpath"; + $pkg =~ s!/!::!g; + + # If we have a mixed-case package name, assume case has been preserved + # correctly. Otherwise, root through the file to locate the case-preserved + # version of the package name. + if ( $subpath eq lc($subpath) || $subpath eq uc($subpath) ) { + my $content = Module::Install::_read($subpath . '.pm'); + my $in_pod = 0; + foreach ( split //, $content ) { + $in_pod = 1 if /^=\w/; + $in_pod = 0 if /^=cut/; + next if ($in_pod || /^=cut/); # skip pod text + next if /^\s*#/; # and comments + if ( m/^\s*package\s+($pkg)\s*;/i ) { + $pkg = $1; + last; + } + } + } + + push @found, [ $file, $pkg ]; + }, $path ) if -d $path; + + @found; +} + + + + + +##################################################################### +# Utility Functions + +sub _caller { + my $depth = 0; + my $call = caller($depth); + while ( $call eq __PACKAGE__ ) { + $depth++; + $call = caller($depth); + } + return $call; +} + +sub _read { + local *FH; + open FH, "< $_[0]" or die "open($_[0]): $!"; + my $str = do { local $/; <FH> }; + close FH or die "close($_[0]): $!"; + return $str; +} + +sub _write { + local *FH; + open FH, "> $_[0]" or die "open($_[0]): $!"; + foreach ( 1 .. $#_ ) { print FH $_[$_] or die "print($_[0]): $!" } + close FH or die "close($_[0]): $!"; +} + +sub _version { + my $s = shift || 0; + $s =~ s/^(\d+)\.?//; + my $l = $1 || 0; + my @v = map { $_ . '0' x (3 - length $_) } $s =~ /(\d{1,3})\D?/g; + $l = $l . '.' . join '', @v if @v; + return $l + 0; +} + +1; + +# Copyright 2008 Adam Kennedy. diff --git a/inc/Module/Install/AutoInstall.pm b/inc/Module/Install/AutoInstall.pm new file mode 100644 index 0000000..3055ec1 --- /dev/null +++ b/inc/Module/Install/AutoInstall.pm @@ -0,0 +1,61 @@ +#line 1 +package Module::Install::AutoInstall; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub AutoInstall { $_[0] } + +sub run { + my $self = shift; + $self->auto_install_now(@_); +} + +sub write { + my $self = shift; + $self->auto_install(@_); +} + +sub auto_install { + my $self = shift; + return if $self->{done}++; + + # Flatten array of arrays into a single array + my @core = map @$_, map @$_, grep ref, + $self->build_requires, $self->requires; + + my @config = @_; + + # We'll need Module::AutoInstall + $self->include('Module::AutoInstall'); + require Module::AutoInstall; + + Module::AutoInstall->import( + (@config ? (-config => \@config) : ()), + (@core ? (-core => \@core) : ()), + $self->features, + ); + + $self->makemaker_args( Module::AutoInstall::_make_args() ); + + my $class = ref($self); + $self->postamble( + "# --- $class section:\n" . + Module::AutoInstall::postamble() + ); +} + +sub auto_install_now { + my $self = shift; + $self->auto_install(@_); + Module::AutoInstall::do_install(); +} + +1; diff --git a/inc/Module/Install/Base.pm b/inc/Module/Install/Base.pm new file mode 100644 index 0000000..bd12f2b --- /dev/null +++ b/inc/Module/Install/Base.pm @@ -0,0 +1,70 @@ +#line 1 +package Module::Install::Base; + +$VERSION = '0.75'; + +# Suspend handler for "redefined" warnings +BEGIN { + my $w = $SIG{__WARN__}; + $SIG{__WARN__} = sub { $w }; +} + +### This is the ONLY module that shouldn't have strict on +# use strict; + +#line 41 + +sub new { + my ($class, %args) = @_; + + foreach my $method ( qw(call load) ) { + *{"$class\::$method"} = sub { + shift()->_top->$method(@_); + } unless defined &{"$class\::$method"}; + } + + bless( \%args, $class ); +} + +#line 61 + +sub AUTOLOAD { + my $self = shift; + local $@; + my $autoload = eval { $self->_top->autoload } or return; + goto &$autoload; +} + +#line 76 + +sub _top { $_[0]->{_top} } + +#line 89 + +sub admin { + $_[0]->_top->{admin} or Module::Install::Base::FakeAdmin->new; +} + +sub is_admin { + $_[0]->admin->VERSION; +} + +sub DESTROY {} + +package Module::Install::Base::FakeAdmin; + +my $Fake; +sub new { $Fake ||= bless(\@_, $_[0]) } + +sub AUTOLOAD {} + +sub DESTROY {} + +# Restore warning handler +BEGIN { + $SIG{__WARN__} = $SIG{__WARN__}->(); +} + +1; + +#line 138 diff --git a/inc/Module/Install/Can.pm b/inc/Module/Install/Can.pm new file mode 100644 index 0000000..3f436c7 --- /dev/null +++ b/inc/Module/Install/Can.pm @@ -0,0 +1,82 @@ +#line 1 +package Module::Install::Can; + +use strict; +use Module::Install::Base; +use Config (); +### This adds a 5.005 Perl version dependency. +### This is a bug and will be fixed. +use File::Spec (); +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +# check if we can load some module +### Upgrade this to not have to load the module if possible +sub can_use { + my ($self, $mod, $ver) = @_; + $mod =~ s{::|\\}{/}g; + $mod .= '.pm' unless $mod =~ /\.pm$/i; + + my $pkg = $mod; + $pkg =~ s{/}{::}g; + $pkg =~ s{\.pm$}{}i; + + local $@; + eval { require $mod; $pkg->VERSION($ver || 0); 1 }; +} + +# check if we can run some command +sub can_run { + my ($self, $cmd) = @_; + + my $_cmd = $cmd; + return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd)); + + for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') { + my $abs = File::Spec->catfile($dir, $_[1]); + return $abs if (-x $abs or $abs = MM->maybe_command($abs)); + } + + return; +} + +# can we locate a (the) C compiler +sub can_cc { + my $self = shift; + my @chunks = split(/ /, $Config::Config{cc}) or return; + + # $Config{cc} may contain args; try to find out the program part + while (@chunks) { + return $self->can_run("@chunks") || (pop(@chunks), next); + } + + return; +} + +# Fix Cygwin bug on maybe_command(); +if ( $^O eq 'cygwin' ) { + require ExtUtils::MM_Cygwin; + require ExtUtils::MM_Win32; + if ( ! defined(&ExtUtils::MM_Cygwin::maybe_command) ) { + *ExtUtils::MM_Cygwin::maybe_command = sub { + my ($self, $file) = @_; + if ($file =~ m{^/cygdrive/}i and ExtUtils::MM_Win32->can('maybe_command')) { + ExtUtils::MM_Win32->maybe_command($file); + } else { + ExtUtils::MM_Unix->maybe_command($file); + } + } + } +} + +1; + +__END__ + +#line 157 diff --git a/inc/Module/Install/Fetch.pm b/inc/Module/Install/Fetch.pm new file mode 100644 index 0000000..1327f35 --- /dev/null +++ b/inc/Module/Install/Fetch.pm @@ -0,0 +1,93 @@ +#line 1 +package Module::Install::Fetch; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub get_file { + my ($self, %args) = @_; + my ($scheme, $host, $path, $file) = + $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; + + if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) { + $args{url} = $args{ftp_url} + or (warn("LWP support unavailable!\n"), return); + ($scheme, $host, $path, $file) = + $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; + } + + $|++; + print "Fetching '$file' from $host... "; + + unless (eval { require Socket; Socket::inet_aton($host) }) { + warn "'$host' resolve failed!\n"; + return; + } + + return unless $scheme eq 'ftp' or $scheme eq 'http'; + + require Cwd; + my $dir = Cwd::getcwd(); + chdir $args{local_dir} or return if exists $args{local_dir}; + + if (eval { require LWP::Simple; 1 }) { + LWP::Simple::mirror($args{url}, $file); + } + elsif (eval { require Net::FTP; 1 }) { eval { + # use Net::FTP to get past firewall + my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600); + $ftp->login("anonymous", '[email protected]'); + $ftp->cwd($path); + $ftp->binary; + $ftp->get($file) or (warn("$!\n"), return); + $ftp->quit; + } } + elsif (my $ftp = $self->can_run('ftp')) { eval { + # no Net::FTP, fallback to ftp.exe + require FileHandle; + my $fh = FileHandle->new; + + local $SIG{CHLD} = 'IGNORE'; + unless ($fh->open("|$ftp -n")) { + warn "Couldn't open ftp: $!\n"; + chdir $dir; return; + } + + my @dialog = split(/\n/, <<"END_FTP"); +open $host +user anonymous anonymous\@example.com +cd $path +binary +get $file $file +quit +END_FTP + foreach (@dialog) { $fh->print("$_\n") } + $fh->close; + } } + else { + warn "No working 'ftp' program available!\n"; + chdir $dir; return; + } + + unless (-f $file) { + warn "Fetching failed: $@\n"; + chdir $dir; return; + } + + return if exists $args{size} and -s $file != $args{size}; + system($args{run}) if exists $args{run}; + unlink($file) if $args{remove}; + + print(((!exists $args{check_for} or -e $args{check_for}) + ? "done!" : "failed! ($!)"), "\n"); + chdir $dir; return !$?; +} + +1; diff --git a/inc/Module/Install/Include.pm b/inc/Module/Install/Include.pm new file mode 100644 index 0000000..d0fd7f8 --- /dev/null +++ b/inc/Module/Install/Include.pm @@ -0,0 +1,34 @@ +#line 1 +package Module::Install::Include; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub include { + shift()->admin->include(@_); +} + +sub include_deps { + shift()->admin->include_deps(@_); +} + +sub auto_include { + shift()->admin->auto_include(@_); +} + +sub auto_include_deps { + shift()->admin->auto_include_deps(@_); +} + +sub auto_include_dependent_dists { + shift()->admin->auto_include_dependent_dists(@_); +} + +1; diff --git a/inc/Module/Install/Makefile.pm b/inc/Module/Install/Makefile.pm new file mode 100644 index 0000000..b7c2ba9 --- /dev/null +++ b/inc/Module/Install/Makefile.pm @@ -0,0 +1,245 @@ +#line 1 +package Module::Install::Makefile; + +use strict 'vars'; +use Module::Install::Base; +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub Makefile { $_[0] } + +my %seen = (); + +sub prompt { + shift; + + # Infinite loop protection + my @c = caller(); + if ( ++$seen{"$c[1]|$c[2]|$_[0]"} > 3 ) { + die "Caught an potential prompt infinite loop ($c[1]|$c[2]|$_[0])"; + } + + # In automated testing, always use defaults + if ( $ENV{AUTOMATED_TESTING} and ! $ENV{PERL_MM_USE_DEFAULT} ) { + local $ENV{PERL_MM_USE_DEFAULT} = 1; + goto &ExtUtils::MakeMaker::prompt; + } else { + goto &ExtUtils::MakeMaker::prompt; + } +} + +sub makemaker_args { + my $self = shift; + my $args = ($self->{makemaker_args} ||= {}); + %$args = ( %$args, @_ ) if @_; + $args; +} + +# For mm args that take multiple space-seperated args, +# append an argument to the current list. +sub makemaker_append { + my $self = sShift; + my $name = shift; + my $args = $self->makemaker_args; + $args->{name} = defined $args->{$name} + ? join( ' ', $args->{name}, @_ ) + : join( ' ', @_ ); +} + +sub build_subdirs { + my $self = shift; + my $subdirs = $self->makemaker_args->{DIR} ||= []; + for my $subdir (@_) { + push @$subdirs, $subdir; + } +} + +sub clean_files { + my $self = shift; + my $clean = $self->makemaker_args->{clean} ||= {}; + %$clean = ( + %$clean, + FILES => join ' ', grep { length $_ } ($clean->{FILES} || (), @_), + ); +} + +sub realclean_files { + my $self = shift; + my $realclean = $self->makemaker_args->{realclean} ||= {}; + %$realclean = ( + %$realclean, + FILES => join ' ', grep { length $_ } ($realclean->{FILES} || (), @_), + ); +} + +sub libs { + my $self = shift; + my $libs = ref $_[0] ? shift : [ shift ]; + $self->makemaker_args( LIBS => $libs ); +} + +sub inc { + my $self = shift; + $self->makemaker_args( INC => shift ); +} + +my %test_dir = (); + +sub _wanted_t { + /\.t$/ and -f $_ and $test_dir{$File::Find::dir} = 1; +} + +sub tests_recursive { + my $self = shift; + if ( $self->tests ) { + die "tests_recursive will not work if tests are already defined"; + } + my $dir = shift || 't'; + unless ( -d $dir ) { + die "tests_recursive dir '$dir' does not exist"; + } + %test_dir = (); + require File::Find; + File::Find::find( \&_wanted_t, $dir ); + $self->tests( join ' ', map { "$_/*.t" } sort keys %test_dir ); +} + +sub write { + my $self = shift; + die "&Makefile->write() takes no arguments\n" if @_; + + # Make sure we have a new enough + require ExtUtils::MakeMaker; + $self->configure_requires( 'ExtUtils::MakeMaker' => $ExtUtils::MakeMaker::VERSION ); + + # Generate the + my $args = $self->makemaker_args; + $args->{DISTNAME} = $self->name; + $args->{NAME} = $self->module_name || $self->name; + $args->{VERSION} = $self->version; + $args->{NAME} =~ s/-/::/g; + if ( $self->tests ) { + $args->{test} = { TESTS => $self->tests }; + } + if ($] >= 5.005) { + $args->{ABSTRACT} = $self->abstract; + $args->{AUTHOR} = $self->author; + } + if ( eval($ExtUtils::MakeMaker::VERSION) >= 6.10 ) { + $args->{NO_META} = 1; + } + if ( eval($ExtUtils::MakeMaker::VERSION) > 6.17 and $self->sign ) { + $args->{SIGN} = 1; + } + unless ( $self->is_admin ) { + delete $args->{SIGN}; + } + + # merge both kinds of requires into prereq_pm + my $prereq = ($args->{PREREQ_PM} ||= {}); + %$prereq = ( %$prereq, + map { @$_ } + map { @$_ } + grep $_, + ($self->configure_requires, $self->build_requires, $self->requires) + ); + + # Remove any reference to perl, PREREQ_PM doesn't support it + delete $args->{PREREQ_PM}->{perl}; + + # merge both kinds of requires into prereq_pm + my $subdirs = ($args->{DIR} ||= []); + if ($self->bundles) { + foreach my $bundle (@{ $self->bundles }) { + my ($file, $dir) = @$bundle; + push @$subdirs, $dir if -d $dir; + delete $prereq->{$file}; + } + } + + if ( my $perl_version = $self->perl_version ) { + eval "use $perl_version; 1" + or die "ERROR: perl: Version $] is installed, " + . "but we need version >= $perl_version"; + } + + $args->{INSTALLDIRS} = $self->installdirs; + + my %args = map { ( $_ => $args->{$_} ) } grep {defined($args->{$_})} keys %$args; + + my $user_preop = delete $args{dist}->{PREOP}; + if (my $preop = $self->admin->preop($user_preop)) { + $args{dist} = $preop; + } + + my $mm = ExtUtils::MakeMaker::WriteMakefile(%args); + $self->fix_up_makefile($mm->{FIRST_MAKEFILE} || 'Makefile'); +} + +sub fix_up_makefile { + my $self = shift; + my $makefile_name = shift; + my $top_class = ref($self->_top) || ''; + my $top_version = $self->_top->VERSION || ''; + + my $preamble = $self->preamble + ? "# Preamble by $top_class $top_version\n" + . $self->preamble + : ''; + my $postamble = "# Postamble by $top_class $top_version\n" + . ($self->postamble || ''); + + local *MAKEFILE; + open MAKEFILE, "< $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; + my $makefile = do { local $/; <MAKEFILE> }; + close MAKEFILE or die $!; + + $makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /; + $makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g; + $makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g; + $makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m; + $makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m; + + # Module::Install will never be used to build the Core Perl + # Sometimes PERL_LIB and PERL_ARCHLIB get written anyway, which breaks + # PREFIX/PERL5LIB, and thus, install_share. Blank them if they exist + $makefile =~ s/^PERL_LIB = .+/PERL_LIB =/m; + #$makefile =~ s/^PERL_ARCHLIB = .+/PERL_ARCHLIB =/m; + + # Perl 5.005 mentions PERL_LIB explicitly, so we have to remove that as well. + $makefile =~ s/(\"?)-I\$\(PERL_LIB\)\1//g; + + # XXX - This is currently unused; not sure if it breaks other MM-users + # $makefile =~ s/^pm_to_blib\s+:\s+/pm_to_blib :: /mg; + + open MAKEFILE, "> $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; + print MAKEFILE "$preamble$makefile$postamble" or die $!; + close MAKEFILE or die $!; + + 1; +} + +sub preamble { + my ($self, $text) = @_; + $self->{preamble} = $text . $self->{preamble} if defined $text; + $self->{preamble}; +} + +sub postamble { + my ($self, $text) = @_; + $self->{postamble} ||= $self->admin->postamble; + $self->{postamble} .= $text if defined $text; + $self->{postamble} +} + +1; + +__END__ + +#line 371 diff --git a/inc/Module/Install/Metadata.pm b/inc/Module/Install/Metadata.pm new file mode 100644 index 0000000..ce26bf6 --- /dev/null +++ b/inc/Module/Install/Metadata.pm @@ -0,0 +1,407 @@ +#line 1 +package Module::Install::Metadata; + +use strict 'vars'; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.75'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +my @scalar_keys = qw{ + name + module_name + abstract + author + version + license + distribution_type + perl_version + tests + installdirs +}; + +my @tuple_keys = qw{ + configure_requires + build_requires + requires + recommends + bundles + resources +}; + +sub Meta { shift } +sub Meta_ScalarKeys { @scalar_keys } +sub Meta_TupleKeys { @tuple_keys } + +foreach my $key (@scalar_keys) { + *$key = sub { + my $self = shift; + return $self->{values}{$key} if defined wantarray and !@_; + $self->{values}{$key} = shift; + return $self; + }; +} + +sub requires { + my $self = shift; + while ( @_ ) { + my $module = shift or last; + my $version = shift || 0; + push @{ $self->{values}->{requires} }, [ $module, $version ]; + } + $self->{values}{requires}; +} + +sub build_requires { + my $self = shift; + while ( @_ ) { + my $module = shift or last; + my $version = shift || 0; + push @{ $self->{values}->{build_requires} }, [ $module, $version ]; + } + $self->{values}{build_requires}; +} + +sub configure_requires { + my $self = shift; + while ( @_ ) { + my $module = shift or last; + my $version = shift || 0; + push @{ $self->{values}->{configure_requires} }, [ $module, $version ]; + } + $self->{values}->{configure_requires}; +} + +sub recommends { + my $self = shift; + while ( @_ ) { + my $module = shift or last; + my $version = shift || 0; + push @{ $self->{values}->{recommends} }, [ $module, $version ]; + } + $self->{values}->{recommends}; +} + +sub bundles { + my $self = shift; + while ( @_ ) { + my $module = shift or last; + my $version = shift || 0; + push @{ $self->{values}->{bundles} }, [ $module, $version ]; + } + $self->{values}->{bundles}; +} + +# Resource handling +sub resources { + my $self = shift; + while ( @_ ) { + my $resource = shift or last; + my $value = shift or next; + push @{ $self->{values}->{resources} }, [ $resource, $value ]; + } + $self->{values}->{resources}; +} + +sub repository { + my $self = shift; + $self->resources( repository => shift ); + return 1; +} + +# Aliases for build_requires that will have alternative +# meanings in some future version of META.yml. +sub test_requires { shift->build_requires(@_) } +sub install_requires { shift->build_requires(@_) } + +# Aliases for installdirs options +sub install_as_core { $_[0]->installdirs('perl') } +sub install_as_cpan { $_[0]->installdirs('site') } +sub install_as_site { $_[0]->installdirs('site') } +sub install_as_vendor { $_[0]->installdirs('vendor') } + +sub sign { + my $self = shift; + return $self->{'values'}{'sign'} if defined wantarray and ! @_; + $self->{'values'}{'sign'} = ( @_ ? $_[0] : 1 ); + return $self; +} + +sub dynamic_config { + my $self = shift; + unless ( @_ ) { + warn "You MUST provide an explicit true/false value to dynamic_config, skipping\n"; + return $self; + } + $self->{values}{dynamic_config} = $_[0] ? 1 : 0; + return $self; +} + +sub all_from { + my ( $self, $file ) = @_; + + unless ( defined($file) ) { + my $name = $self->name + or die "all_from called with no args without setting name() first"; + $file = join('/', 'lib', split(/-/, $name)) . '.pm'; + $file =~ s{.*/}{} unless -e $file; + die "all_from: cannot find $file from $name" unless -e $file; + } + + # Some methods pull from POD instead of code. + # If there is a matching .pod, use that instead + my $pod = $file; + $pod =~ s/\.pm$/.pod/i; + $pod = $file unless -e $pod; + + # Pull the different values + $self->name_from($file) unless $self->name; + $self->version_from($file) unless $self->version; + $self->perl_version_from($file) unless $self->perl_version; + $self->author_from($pod) unless $self->author; + $self->license_from($pod) unless $self->license; + $self->abstract_from($pod) unless $self->abstract; + + return 1; +} + +sub provides { + my $self = shift; + my $provides = ( $self->{values}{provides} ||= {} ); + %$provides = (%$provides, @_) if @_; + return $provides; +} + +sub auto_provides { + my $self = shift; + return $self unless $self->is_admin; + unless (-e 'MANIFEST') { + warn "Cannot deduce auto_provides without a MANIFEST, skipping\n"; + return $self; + } + # Avoid spurious warnings as we are not checking manifest here. + local $SIG{__WARN__} = sub {1}; + require ExtUtils::Manifest; + local *ExtUtils::Manifest::manicheck = sub { return }; + + require Module::Build; + my $build = Module::Build->new( + dist_name => $self->name, + dist_version => $self->version, + license => $self->license, + ); + $self->provides( %{ $build->find_dist_packages || {} } ); +} + +sub feature { + my $self = shift; + my $name = shift; + my $features = ( $self->{values}{features} ||= [] ); + my $mods; + + if ( @_ == 1 and ref( $_[0] ) ) { + # The user used ->feature like ->features by passing in the second + # argument as a reference. Accomodate for that. + $mods = $_[0]; + } else { + $mods = \@_; + } + + my $count = 0; + push @$features, ( + $name => [ + map { + ref($_) ? ( ref($_) eq 'HASH' ) ? %$_ : @$_ : $_ + } @$mods + ] + ); + + return @$features; +} + +sub features { + my $self = shift; + while ( my ( $name, $mods ) = splice( @_, 0, 2 ) ) { + $self->feature( $name, @$mods ); + } + return $self->{values}->{features} + ? @{ $self->{values}->{features} } + : (); +} + +sub no_index { + my $self = shift; + my $type = shift; + push @{ $self->{values}{no_index}{$type} }, @_ if $type; + return $self->{values}{no_index}; +} + +sub read { + my $self = shift; + $self->include_deps( 'YAML::Tiny', 0 ); + + require YAML::Tiny; + my $data = YAML::Tiny::LoadFile('META.yml'); + + # Call methods explicitly in case user has already set some values. + while ( my ( $key, $value ) = each %$data ) { + next unless $self->can($key); + if ( ref $value eq 'HASH' ) { + while ( my ( $module, $version ) = each %$value ) { + $self->can($key)->($self, $module => $version ); + } + } else { + $self->can($key)->($self, $value); + } + } + return $self; +} + +sub write { + my $self = shift; + return $self unless $self->is_admin; + $self->admin->write_meta; + return $self; +} + +sub version_from { + require ExtUtils::MM_Unix; + my ( $self, $file ) = @_; + $self->version( ExtUtils::MM_Unix->parse_version($file) ); +} + +sub abstract_from { + require ExtUtils::MM_Unix; + my ( $self, $file ) = @_; + $self->abstract( + bless( + { DISTNAME => $self->name }, + 'ExtUtils::MM_Unix' + )->parse_abstract($file) + ); +} + +# Add both distribution and module name +sub name_from { + my ($self, $file) = @_; + if ( + Module::Install::_read($file) =~ m/ + ^ \s* + package \s* + ([\w:]+) + \s* ; + /ixms + ) { + my ($name, $module_name) = ($1, $1); + $name =~ s{::}{-}g; + $self->name($name); + unless ( $self->module_name ) { + $self->module_name($module_name); + } + } else { + die "Cannot determine name from $file\n"; + } +} + +sub perl_version_from { + my $self = shift; + if ( + Module::Install::_read($_[0]) =~ m/ + ^ + (?:use|require) \s* + v? + ([\d_\.]+) + \s* ; + /ixms + ) { + my $perl_version = $1; + $perl_version =~ s{_}{}g; + $self->perl_version($perl_version); + } else { + warn "Cannot determine perl version info from $_[0]\n"; + return; + } +} + +sub author_from { + my $self = shift; + my $content = Module::Install::_read($_[0]); + if ($content =~ m/ + =head \d \s+ (?:authors?)\b \s* + ([^\n]*) + | + =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b \s* + .*? copyright .*? \d\d\d[\d.]+ \s* (?:\bby\b)? \s* + ([^\n]*) + /ixms) { + my $author = $1 || $2; + $author =~ s{E<lt>}{<}g; + $author =~ s{E<gt>}{>}g; + $self->author($author); + } else { + warn "Cannot determine author info from $_[0]\n"; + } +} + +sub license_from { + my $self = shift; + if ( + Module::Install::_read($_[0]) =~ m/ + ( + =head \d \s+ + (?:licen[cs]e|licensing|copyright|legal)\b + .*? + ) + (=head\\d.*|=cut.*|) + \z + /ixms ) { + my $license_text = $1; + my @phrases = ( + 'under the same (?:terms|license) as perl itself' => 'perl', 1, + 'GNU public license' => 'gpl', 1, + 'GNU lesser public license' => 'lgpl', 1, + 'BSD license' => 'bsd', 1, + 'Artistic license' => 'artistic', 1, + 'GPL' => 'gpl', 1, + 'LGPL' => 'lgpl', 1, + 'BSD' => 'bsd', 1, + 'Artistic' => 'artistic', 1, + 'MIT' => 'mit', 1, + 'proprietary' => 'proprietary', 0, + ); + while ( my ($pattern, $license, $osi) = splice(@phrases, 0, 3) ) { + $pattern =~ s{\s+}{\\s+}g; + if ( $license_text =~ /\b$pattern\b/i ) { + if ( $osi and $license_text =~ /All rights reserved/i ) { + print "WARNING: 'All rights reserved' in copyright may invalidate Open Source license.\n"; + } + $self->license($license); + return 1; + } + } + } + + warn "Cannot determine license info from $_[0]\n"; + return 'unknown'; +} + +sub install_script { + my $self = shift; + my $args = $self->makemaker_args; + my $exe = $args->{EXE_FILES} ||= []; + foreach ( @_ ) { + if ( -f $_ ) { + push @$exe, $_; + } elsif ( -d 'script' and -f "script/$_" ) { + push @$exe, "script/$_"; + } else { + die "Cannot find script '$_'"; + } + } +} + +1; diff --git a/inc/Module/Install/Win32.pm b/inc/Module/Install/Win32.pm new file mode 100644 index 0000000..c97701b --- /dev/null +++ b/inc/Module/Install/Win32.pm @@ -0,0 +1,64 @@ +#line 1 +package Module::Install::Win32; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION @ISA $ISCORE}; +BEGIN { + $VERSION = '0.75'; + @ISA = qw{Module::Install::Base}; + $ISCORE = 1; +} + +# determine if the user needs nmake, and download it if needed +sub check_nmake { + my $self = shift; + $self->load('can_run'); + $self->load('get_file'); + + require Config; + return unless ( + $^O eq 'MSWin32' and + $Config::Config{make} and + $Config::Config{make} =~ /^nmake\b/i and + ! $self->can_run('nmake') + ); + + print "The required 'nmake' executable not found, fetching it...\n"; + + require File::Basename; + my $rv = $self->get_file( + url => 'http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe', + ftp_url => 'ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe', + local_dir => File::Basename::dirname($^X), + size => 51928, + run => 'Nmake15.exe /o > nul', + check_for => 'Nmake.exe', + remove => 1, + ); + + die <<'END_MESSAGE' unless $rv; + +------------------------------------------------------------------------------- + +Since you are using Microsoft Windows, you will need the 'nmake' utility +before installation. It's available at: + + http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe + or + ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe + +Please download the file manually, save it to a directory in %PATH% (e.g. +C:\WINDOWS\COMMAND\), then launch the MS-DOS command line shell, "cd" to +that directory, and run "Nmake15.exe" from there; that will create the +'nmake.exe' file needed by this module. + +You may then resume the installation process described in README. + +------------------------------------------------------------------------------- +END_MESSAGE + +} + +1; diff --git a/inc/Module/Install/WriteAll.pm b/inc/Module/Install/WriteAll.pm new file mode 100644 index 0000000..e80deb8 --- /dev/null +++ b/inc/Module/Install/WriteAll.pm @@ -0,0 +1,40 @@ +#line 1 +package Module::Install::WriteAll; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION @ISA $ISCORE}; +BEGIN { + $VERSION = '0.75'; + @ISA = qw{Module::Install::Base}; + $ISCORE = 1; +} + +sub WriteAll { + my $self = shift; + my %args = ( + meta => 1, + sign => 0, + inline => 0, + check_nmake => 1, + @_, + ); + + $self->sign(1) if $args{sign}; + $self->Meta->write if $args{meta}; + $self->admin->WriteAll(%args) if $self->is_admin; + + $self->check_nmake if $args{check_nmake}; + unless ( $self->makemaker_args->{PL_FILES} ) { + $self->makemaker_args( PL_FILES => {} ); + } + + if ( $args{inline} ) { + $self->Inline->write; + } else { + $self->Makefile->write; + } +} + +1; diff --git a/lib/MojoX/Renderer/YAML.pm b/lib/MojoX/Renderer/YAML.pm new file mode 100644 index 0000000..b18b9b9 --- /dev/null +++ b/lib/MojoX/Renderer/YAML.pm @@ -0,0 +1,120 @@ +package MojoX::Renderer::YAML; + +use strict; +use warnings; + +require YAML::Syck; + +our $VERSION = '0.10'; + +sub build { + shift; # ignore + my %opt = @_; + + return sub { + my ($mojo, $ctx, $output) = @_; + + local $YAML::Syck::Headless = $opt{Headless} if exists $opt{Headless}; + local $YAML::Syck::SortKeys = $opt{SortKeys} if exists $opt{SortKeys}; + local $YAML::Syck::SingleQuote = $opt{SingleQuote} if exists $opt{SingleQuote}; + local $YAML::Syck::ImplicitTyping = $opt{ImplicitTyping} if exists $opt{ImplicitTyping}; + local $YAML::Syck::ImplicitUnicode = $opt{ImplicitUnicode} if exists $opt{ImplicitUnicode}; + local $YAML::Syck::ImplicitBinary = $opt{ImplicitBinary} if exists $opt{ImplicitBinary}; + local $YAML::Syck::UseCode = $opt{UseCode} if exists $opt{UseCode}; + local $YAML::Syck::LoadCode = $opt{LoadCode} if exists $opt{LoadCode}; + local $YAML::Syck::DumpCode = $opt{DumpCode} if exists $opt{DumpCode}; + + $$output = YAML::Syck::Dump($ctx->stash->{result}); + + return 1; + }; +} + +1; + +__END__ + +=encoding utf-8 + +=head1 NAME + +MojoX::Renderer::YAML - YAML renderer for Mojo + +=head1 SYNOPSIS + + use MojoX::Renderer::YAML; + + sub startup { + my $self = shift; + + $self->types->type(yml => 'application/x-yaml'); + + my $render = MojoX::Renderer::YAML->build( + Headless => 1, + SortKeys => 1, + ); + + $self->renderer->add_handler(yml => $render); + } + +=head1 DESCRIPTION + +Once added this renderer will be called by L<MojoX::Renderer> for any given template +where the suffix of the specified template matches the suffix used in the C<add_handler> +method. + +This renderer converts the C<result> element in the stash to YAML using the given options. +The template name is ignored. + +=head1 METHODS + +=head2 build + +This method returns a handler for the Mojo renderer. + +Supported parameters are names of variables used by L<YAML::Syck>. See L<YAML::Syck> for their definitions + +=over 4 + +=item * Headless + +=item * SortKeys + +=item * SingleQuote + +=item * ImplicitTyping + +=item * ImplicitUnicode + +=item * ImplicitBinary + +=item * UseCode + +=item * LoadCode + +=item * DumpCode + +=back + +=head1 AUTHOR + +Graham Barr <[email protected]> + +=head1 BUGS + +Please report any bugs or feature requests to C<bug-mojox-renderer-yaml at rt.cpan.org>, or through +the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MojoX-Renderer-YAML>. +I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. + +=head1 SEE ALSO + +L<YAML::Syck>, L<MojoX::Renderer> + +=head1 COPYRIGHT & LICENSE + +Copyright (C) 2008 Graham Barr + +This program is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut diff --git a/t/00-load.t b/t/00-load.t new file mode 100644 index 0000000..54bcc8e --- /dev/null +++ b/t/00-load.t @@ -0,0 +1,9 @@ +#!perl -T + +use Test::More tests => 1; + +BEGIN { + use_ok( 'MojoX::Renderer::YAML' ); +} + +diag( "Testing MojoX::Renderer::YAML $MojoX::Renderer::YAML::VERSION, Perl $], $^X" );
emacsattic/write-subdirs-el
539b265aa31cc540995e86a7933b777c67d33eb2
Thu Dec 3 19:23:34 CET 2009 update
diff --git a/write-subdirs-el.el b/write-subdirs-el.el new file mode 100644 index 0000000..6ff70b5 --- /dev/null +++ b/write-subdirs-el.el @@ -0,0 +1,636 @@ +;;; write-subdirs-el.el --- Create subdirs.el files + +;; Copyright (C) 2000 by Tom Breton + +;; Author: Tom Breton <[email protected]> +;; Keywords: local +;; Version 1.2 + +;; This file is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation; either version 2, or (at your option) +;; any later version. + +;; This file is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with GNU Emacs; see the file COPYING. If not, write to +;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330, +;; Boston, MA 02111-1307, USA. + +;;; Commentary: + +;; This code creates subdirs.el files for directory trees. + +;;; Motivation + +;; Why do that, you ask? By way of explanation, subdirectories of +;; site-lisp automatically become part of the load-path when you start +;; Emacs. That makes site-lisp an appealing place to put Elisp +;; packages. + +;; But there is more subdirs.el could do for you. For instance, it +;; could set up Info-default-directory-list and autoloads. + +;; As I write this, package maintainers generally don't use +;; subdirs.el. Perhaps they mostly don't know about it. I hope +;; write-subdirs-el will help change that. + +;; I have a vision of a thousand elisp packages that require no more +;; setup than being placed in site-lisp. (And sometimes a +;; command-line "make"). And I imagine a thousand package maintainers +;; who can provide easy installation for their users with little or no +;; more work then typing M-x tehom-wse-entry. + +;;; Installation: + +;; Place write-subdirs-el anywhere in your load-path + +;; IMPORTANT: Replace your existing site-lisp/subdirs.el with +;; new-subdirs-el.el. That is, put site-lisp/subdirs.el somewhere +;; safe and rename new-subdirs-el.el to that. If you use the old +;; version and build subdirs.els with this package, some directory +;; trees (those that have no Elisp code in their root directories, but +;; do have Elisp in their subdirectories) will be unexpectedly omitted +;; from load-path. + +;; If you can't load a subdirs.el that's not hanging off site-lisp, +;; it's a known bug that's fixed by new-subdirs-el.el + +;;; Customizations: + +;; If you want it to generate autoloads, customize +;; tehom-wse-do-autoloads-p to t. + +;; WARNING: If the autoloads don't work, emacs won't start. That's +;; not under my control, it's up to the maintainers of the individual +;; packages, + +;;; Entry points: + +;; IMPORTANT: You will need to have read and write permissions to all +;; the directories in question. If not, nothing will happen. + +;; tehom-wse-do-all-dirs-in-site-lisp will tackle every single +;; directory in site-lisp in one command. You'll probably want to run +;; this exactly once. + +;; tehom-wse-make-subdirs-el will make subdirs.el for any given +;; directory tree. + +;; tehom-wse-entry will make a subdirs.el for a directory in your +;; load-path. It's a little more convenient than navigating your +;; load-path manually. + +;;; Testing + +;; This has not been easy to test. Testing it properly requires +;; dealing with a whole test directory structure. The standard elisp +;; distribution directory could perhaps be used, but mine is +;; non-standard. I could create a whole directory tree, but that's a +;; lot of work just to test one part of this. Testing it properly +;; also requires starting emacs a lot of times. I've done that to a +;; degree, but obviously automated testing was out of the question. + +;; So while I've given it what testing I could, there's a bit of a +;; cross-your-fingers-and-hope factor. PLEASE inspect any subdirs.el +;; it writes and if there are obvious problems, don't use it. (ie, +;; move it somewhere out of your load-path) + +;; IMPORTANT: At worst, your system can be restored to the way it was +;; by restoring your old site-lisp/subdirs.el and erasing any +;; subdirs.el and .nosearch files in site-lisp's subdirectories. I +;; don't think that will ever be neccessary, but I wanted to point it +;; out just in case. + +;;; Non-features: + +;; If a subdirectory being examined itself contains a subdirs.el, that +;; directory could be handled by a call to that file, nothing more. +;; NB we'd have to exclude the directory tree root from this, +;; otherwise we could possibly call our file itself in an infinite +;; loop. This probably isn't worth doing, because no packages are so +;; deep they would get any use out of nested subdirs.el's + +;; Changelog: + +;; Version 1.2: Provided code in new-subdirs-el.el to get around +;; startup's inability to handle working from directories that aren't +;; already in load-path. + +;; Version 1.1: Fixed the bug where Info-path was sometimes missed. +;; Changed the output to add some appropriate local variables +;; including no-update-autoloads. + +;;; Code: + +(require 'cl) +(require 'autoload) + +;;;; + +(defcustom tehom-wse-do-autoloads-p nil + "Do autoloads" + :type 'boolean) + + +;;;; Constants + +(defconst tehom-wse-filename "subdirs.el" "" ) +(defconst tehom-directory-meanings-alist + '( + ("lisp" . lisp) + ("contrib" . lisp) + ("info" . info) + ("texi" . info) + ("texinfo" . info)) + "The meanings of canonical directory names." ) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;Helper functions: + +;;Helpers for entry points + +(defun tehom-wse-get-load-path-matching (regex) + "Return a list of names in load-path that match REGEX." + + (loop + for dir-name in load-path + if + (string-match regex dir-name) + collect dir-name)) + +;;Helpers for command functions + +(defun tehom-force-file-to-exist (filename) + "" + + (unless + (file-exists-p filename) + (write-region "" nil filename))) + + +(defun tehom-remove-file-if-exists (filename) + "" + (if + (file-exists-p filename) + (delete-file filename))) + + +;;Helpers for collector functions. + +(defun tehom-filter-strings-matching (string-list regex) + "Return a list of strings in STRING-LIST matching REGEX." + + (loop + for string in string-list + if + (string-match regex string) + collect string)) + + +(defun tehom-any-elisp (filename-list) + "Return non-nil if any names in FILENAME-LIST look like Elisp executables. + +subdirs.el itself doesn't count." + + (let* + ;;Don't let subdirs.el make a directory look like it has Elisp. + ((filename-list-1 + (remove* "subdirs.el" filename-list :test #'string= ))) + + (tehom-filter-strings-matching filename-list-1 "\\.elc?\\'"))) + +;;Finding info files is iffy, but we do our best. +(defun tehom-any-info-files (filename-list) + "Return non-nil if any names in FILENAME-LIST look like info files." + (or + (tehom-filter-strings-matching filename-list "\\.info?\\'") + (tehom-filter-strings-matching filename-list "\\-[0-9]+\\'"))) + + +;;Used to collect source files for autoloads +(defun tehom-collect-elisp-sources (filename-list) + "Return the names from FILENAME-LIST that look like Elisp source code." + + (let* + ;;Don't treat subdirs.el like normal source, nor the temp files + ;;emacs makes for the open subdirs.el files. + ((filename-list-1 + (remove* "subdirs.el$" filename-list :test #'string-match ))) + + (tehom-filter-strings-matching filename-list-1 "\\.el\\'"))) + + +;;Borrowed from startup.el and encapsulated. +(defun tehom-wse-name-is-nice-directory (name) + "Return non-nil if NAME looks like a nice directory. + +Nice here means that its name strts with an alphanumeric character and +it doesn't look like Elisp code." + + (and + (string-match "\\`[a-zA-Z0-9]" name) + ;; Avoid doing a `stat' when it isn't necessary + ;; because that can cause trouble when an NFS server + ;; is down. + (not (string-match "\\.elc?\\'" name)) + (file-directory-p name))) + + +;;tehom-wse-name-is-nice-directory needs to test base-names, but +;;tehom-wse-collect-nice-subdirectories needs to return multi-component +;;relative names. So be very careful about how we treat expansion. +(defun tehom-wse-collect-nice-subdirectories (directory) + "Collect all \"nice\" subdirectories of DIRECTORY. + +DIRECTORY is relative to default-directory." + + (let* + ( + ;;Generate base-names. + (filename-list (directory-files directory nil nil t)) + ;;Still all base-names + (stripped-list + (remove-if-not #'tehom-wse-name-is-nice-directory filename-list))) + + (mapcar + ;;Expand each name wrt DIRECTORY, then make it relative to the + ;;top directory. + #'(lambda (base-name) + (file-relative-name (expand-file-name base-name directory))) + + stripped-list))) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;Path collector functions + +(defun tehom-wse-examine-homogeneous-subdirectories (directory type) + "Examine DIRECTORY and its subdirectories, treating TYPE as unchanging." + + (dolist + (subdirectory + (tehom-wse-collect-nice-subdirectories directory)) + + (tehom-wse-examine-directory subdirectory type))) + +(defun tehom-wse-examine-directory (directory type) + "Examine DIRECTORY and its subdirectories, according to TYPE." + + + (let + ((filename-list (directory-files directory))) + (declare (special add-to-load-path add-to-info-path)) + + (case type + + ('lisp + (push directory add-to-load-path) + ;;Treat all its subdirectories as lisp. + (tehom-wse-examine-homogeneous-subdirectories directory 'lisp)) + + + ('info + (push directory add-to-info-path) + ;;Treat all its subdirectories as info. + (tehom-wse-examine-homogeneous-subdirectories directory 'info)) + + + ('unclassified + + ;;Try all the possibilities. More than one can be used. + (if + (tehom-any-elisp filename-list) + (push directory add-to-load-path)) + + (if + (tehom-any-info-files filename-list) + (push directory add-to-info-path)) + + ;;Recurse into each subdirectory. + (dolist + (subdirectory + (tehom-wse-collect-nice-subdirectories directory)) + + (let + ;;Classify the subdirectory if possible. + ((subdirectory-type + (or + (cdr-safe + (assoc subdirectory + tehom-directory-meanings-alist)) + 'unclassified))) + + (tehom-wse-examine-directory subdirectory subdirectory-type))) + + )))) + + +;;Manages the special variables add-to-load-path and add-to-info-path +(defun tehom-wse-examine-directory-tree () + "Return what directories to add to load-path and to info path." + + (let + ( + (add-to-load-path '()) + (add-to-info-path '())) + + (declare (special add-to-load-path add-to-info-path)) + + (tehom-wse-examine-directory "." 'unclassified) + + (values add-to-load-path add-to-info-path))) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;Output functions + +(defun tehom-wse-insert-all + (add-to-load-path add-to-info-path make-autoloads-list) + "" + + (insert + + ";; +;; subdirs.el +;; Generated on " + (format-time-string "%a %e %b, %Y %l:%M %p") + " by " + (user-full-name) + " +;; By write-subdirs-el, written by Tehom (Tom Breton) +;; + +" + + + ) + + (if + (not + (or + add-to-load-path add-to-info-path make-autoloads-list)) + (insert ";;Nothing to do\n") + (progn + (tehom-wse-insert-load-path add-to-load-path) + (tehom-wse-insert-info-path add-to-info-path) + (tehom-wse-insert-autoloads make-autoloads-list))) + + (insert + " +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; End: +" + )) + + + + + +(defun tehom-wse-insert-load-path (add-to-load-path) + "Insert Elisp code to add the list ADD-TO-LOAD-PATH to load-path." + + (when add-to-load-path + (pp + `(normal-top-level-add-to-load-path ',add-to-load-path) + (current-buffer)))) + +(defun tehom-wse-insert-info-path (add-to-info-path) + "insert Elisp code to add the list ADD-TO-INFO-PATH to info path." + + (dolist (path add-to-info-path) + (pp + `(add-to-list 'Info-default-directory-list + (expand-file-name ,path)) + (current-buffer)))) + +(defun tehom-wse-insert-autoloads (add-to-load-path) + "Insert autoloads." + + (dolist + (path add-to-load-path) + + (let* + ((expanded (expand-file-name path))) + (dolist + (source-file + (tehom-collect-elisp-sources + (directory-files expanded))) + + (generate-file-autoloads + (expand-file-name source-file expanded)))))) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;Managing function + + +(defun tehom-wse-write-subdirs-el () + "Write subdirs.el code into the current buffer. + +Also manage the existence of `.nosearch'." + + (multiple-value-bind + (add-to-load-path add-to-info-path) + (tehom-wse-examine-directory-tree) + + (let + ( + (nosearch-filename ".nosearch") + (loads-own-directory-p + (find "." add-to-load-path :test #'string=)) + + (make-autoloads-list + (if tehom-wse-do-autoloads-p + add-to-load-path + nil))) + + ;;.nosearch, not subdirs.el, will indicate whether to put this + ;;directory itself on load-path. So we remove "." if it was + ;;there, and in either case we set .nosearch accordingly. + ;;But we mustn't omit that from autoloads. + (if + loads-own-directory-p + (progn + (setq add-to-load-path + (remove* "." add-to-load-path :test #'string= )) + (tehom-remove-file-if-exists nosearch-filename)) + (tehom-force-file-to-exist nosearch-filename)) + + (erase-buffer) + (tehom-wse-insert-all + add-to-load-path add-to-info-path make-autoloads-list)))) + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;Entry points + +;;;###autoload +(defun tehom-wse-make-subdirs-el + (directory &optional force-autoloads force) + "Make a subdirs.el file for the given directory tree." + + (interactive "DMake subdirs.el in which directory? \nP") + + (unless + (string= directory "") + + (let* + ( (default-directory directory) + (tehom-wse-do-autoloads-p + (or tehom-wse-do-autoloads-p force-autoloads)) + (proceed + (or + force + (not (file-exists-p tehom-wse-filename))))) + + (save-excursion + (when + proceed + (find-file tehom-wse-filename) + (tehom-wse-write-subdirs-el) + (save-buffer)))))) + + +;;;###autoload +(defun tehom-wse-make-subdirs-el-force (directory &optional force-autoloads) + "" + (interactive "DMake subdirs.el in which directory? \nP") + (tehom-wse-make-subdirs-el directory force-autoloads t)) + +;;;###autoload +(defun tehom-wse-entry (&optional force-autoloads) + "Call tehom-wse-make-subdirs-el with a directory from load-path." + + (interactive "P") + (let* + ((directory + (completing-read "Pick one: " + (mapcar #'list load-path)))) + + (unless + (string= directory "") + + (tehom-wse-make-subdirs-el directory force-autoloads)))) + + + +;; It wouldn't be hard to make another entry point to pick exactly +;; subdirectories of site-lisp, if that proves more useful than +;; tehom-wse-entry. Just use completing-read on: +;; (tehom-wse-get-load-path-matching "site-lisp\.[^/]+$") + + +(defun tehom-wse-do-all-dirs-in-site-lisp (&optional force) + "Make subdirs.el for every immediate subdirectory of site-lisp. +If there is more than one */site-lisp in load-path, prompt for which +one to use. + +This calls tehom-wse-make-subdirs-el on every immediate subdirectory +of site-lisp." + + (interactive "P") + (let* + ( + (potential-site-lisp-roots + (tehom-wse-get-load-path-matching "site-lisp$")) + + (site-lisp-root + (case (length potential-site-lisp-roots) + (0 "") + (1 (car potential-site-lisp-roots)) + (t + (completing-read "Which site-lisp: " + (mapcar #'list potential-site-lisp-roots)))))) + + (unless (string= site-lisp-root "") + + (let* + ( ;;Important: Bind default-directory around this list-form + (default-directory site-lisp-root) + (directories + (tehom-wse-collect-nice-subdirectories "."))) + + (dolist + (base-directory-name directories) + + (let + ((directory + (expand-file-name base-directory-name))) + + (tehom-wse-make-subdirs-el directory force))))))) + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Design notes: + +;;Overview + +;;First stage: Crawl thru directories, collecting paths +;;Second stage: Output what we have. +;;Third stage: When emacs starts up, the subdirs.els will get run. + +;;;; +;;What we look for when examining directories + +;;Directories are classified either according to their contents or +;;according to their name. + +;;Look for .el and .elc files. If seen, the directory contains Elisp +;;(and maybe more) + +;;Look for files ending in .info or -[0-9]+ and consider them info +;;files. If seen, the directory contains info (and maybe more) + +;;Look for a "lisp" or "contrib" subdirectories and treat them as +;;containing all Elisp + +;;Look for "info", "texi", "texinfo" subdirectories and treat them as +;;containing all info + +;;Simply recurse into other directories. + +;;;;;;; + +;;The returned paths should always be relative to the starting +;;directory. That way the directory-tree can be moved around without +;;consequence, and maintainers can generate a subdirs.el without +;;knowing the layout of the target directory structure. + +;;;;;;; +;;What to write in subdirs.el + +;;Write additions to load-path. +;;Write additions to Info-default-directory-list +;;Make autoloads for all .el files in any directory we're adding to +;;load-path. + +;;;;;;; +;;normal-top-level-add-subdirs-to-load-path (Not here, but important) + +;; normal-top-level-add-subdirs-to-load-path adds dirs as they come +;; off the pending list. dirs with subdirs.el could +;; a) add themselves, but not be pending. Wrong, because they +;; themselves may not want to be part of load-path. + +;; b) execute the subdirs.el directly. This may cause subdirs.el to +;; be executed twice, once by this, once when found in load-path. + +;; c) execute it only if it's not going to be executed later, meaning +;; if it's not being put in load-path. Trust subdirs.el to not cause +;; itself problems by (wrong if .nosearch exists) putting its own +;; directory in load-path. + +;;End design notes +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + +;;; write-subdirs-el.el ends here \ No newline at end of file
briang/MooseX-PrivateSetters
80ee8d588054aa6e01a12aeafe0cb3e28a493066
ignore more build cruft
diff --git a/.gitignore b/.gitignore index dedf2aa..c6886b4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,16 @@ *~ *.bak blib/ Build _build/ cover_db/ Makefile Makefile.PL MANIFEST MANIFEST.SKIP META.yml MooseX-PrivateSetters-* MYMETA.yml +META.json +MYMETA.json
briang/MooseX-PrivateSetters
da229a38ecaf10ae27318231a5d2a1982e71f72a
version bump
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 21153d1..6bfade2 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,117 +1,117 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.07'; +our $VERSION = '0.08'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); $metaroles{role_metaroles} = { applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], } if $Moose::VERSION >= 1.9900; Moose::Exporter->setup_import_methods(%metaroles); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you declare an attribute with a leading underscore, then the set method will start with "_set" (i.e. C<has '_foo'> will get a setter called C<_set_foo>. Note that if you have attributes C<foo> and C<_foo>, they will both get a setter called C<_set_foo>, so don't do that. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 34737f0..3ef32d7 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.07'; +our $VERSION = '0.08'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
5d2a3a50051812fee4bb4aaa4001ccd47263ce55
Sync README and POD
diff --git a/README b/README index 914674e..154e05d 100644 --- a/README +++ b/README @@ -1,72 +1,73 @@ NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with "_set_". - If you declare an attribute with a leading underscore, then the - set method will start with "_set" (i.e. C<<has '_foo'>> will get a - setter called '_set_foo'. + If you declare an attribute with a leading underscore, then the set + method will start with "_set" (i.e. "has '_foo'" will get a setter + called "_set_foo". Note that if you have attributes "foo" and "_foo", + they will both get a setter called "_set_foo", so don't do that. If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be "use"d after Moose. SEE ALSO There are a number of similar modules on the CPAN. Moose The original. A single mutator method is generated with the same name as the attribute itself. MooseX::Accessors::ReadWritePrivate Changes the parsing of the "is" clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you "_get_baz()" and "_set_baz". MooseX::FollowPBP Names accessors in the style recommended by *Perl Best Practices*: "get_size" and "set_size". MooseX::SemiAffordanceAccessor Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with "set_". AUTHOR brian greenfield "<[email protected]>" BUGS Please report any bugs or feature requests to "[email protected]", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
4c19dd7346f8c8291d9ea163e246b6a93da7f401
Clarify (again) setter for _foo
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index e8ab71d..21153d1 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,114 +1,117 @@ package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.07'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); $metaroles{role_metaroles} = { applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], } if $Moose::VERSION >= 1.9900; Moose::Exporter->setup_import_methods(%metaroles); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you declare an attribute with a leading underscore, then the set -method will start with C<_set_>. +method will start with "_set" (i.e. C<has '_foo'> will get a setter +called C<_set_foo>. Note that if you have attributes C<foo> and +C<_foo>, they will both get a setter called C<_set_foo>, so don't do +that. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
briang/MooseX-PrivateSetters
bbbab66911b82644b276dd85f21cf31547a2b688
fix another typo & clarify setter for _attr
diff --git a/CHANGES b/CHANGES index 2bf3b23..b4dfa2f 100644 --- a/CHANGES +++ b/CHANGES @@ -1,28 +1,33 @@ +0.07 2011-08-28 + - Fix silly spelling of declare. Reported by confound via IRC. + - Clarified prefix used when attribute is declared with a + leading underscore. Reported by confound via IRC. + 0.06 2011-08-28 - Fix silly spelling of SemiAffordanceAccessors (RT#70560). Reported by Shawn H. Corey. Thanks! 0.05 2011-05-09 - Fix minimum perl version (RT#67749). Now requires perl 5.8.3 0.04 2011-04-04 - Make compatable with upcoming Moose 2.0 (code provided my Dave Rolsky). See http://blog.moose.perl.org/2011/03/changes-to-moosex-modules-with-moose-20.html for details. 0.03 2010-07-25 - Minor documentation changes 0.02 2010-07-24 - Update TODO - Improve documentation - Modernise by using class_metaroles in Moose::Exporter->setup_import_methods - Add tests for attributes starting with double underscore - Bump Moose prereq to 0.94, add repository - add TODO.org 0.01 2010-07-15 - Initial release - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05 diff --git a/README b/README index 01aa866..914674e 100644 --- a/README +++ b/README @@ -1,71 +1,72 @@ NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with "_set_". - If you deckare an attribute with a leading underscore, then the set - method will start with "_set_". + If you declare an attribute with a leading underscore, then the + set method will start with "_set" (i.e. C<<has '_foo'>> will get a + setter called '_set_foo'. If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be "use"d after Moose. SEE ALSO There are a number of similar modules on the CPAN. Moose The original. A single mutator method is generated with the same name as the attribute itself. MooseX::Accessors::ReadWritePrivate Changes the parsing of the "is" clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you "_get_baz()" and "_set_baz". MooseX::FollowPBP Names accessors in the style recommended by *Perl Best Practices*: "get_size" and "set_size". MooseX::SemiAffordanceAccessor Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with "set_". AUTHOR brian greenfield "<[email protected]>" BUGS Please report any bugs or feature requests to "[email protected]", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 8226f8b..e8ab71d 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,114 +1,114 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.06'; +our $VERSION = '0.07'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); $metaroles{role_metaroles} = { applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], } if $Moose::VERSION >= 1.9900; Moose::Exporter->setup_import_methods(%metaroles); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. -If you deckare an attribute with a leading underscore, then the set +If you declare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 5bc0366..34737f0 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.06'; +our $VERSION = '0.07'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
ac5bda0f89b399991725fae13303b86aed54e269
Fix spelling of SemiAffordanceAccessor
diff --git a/CHANGES b/CHANGES index b95f583..2bf3b23 100644 --- a/CHANGES +++ b/CHANGES @@ -1,24 +1,28 @@ +0.06 2011-08-28 + - Fix silly spelling of SemiAffordanceAccessors + (RT#70560). Reported by Shawn H. Corey. Thanks! + 0.05 2011-05-09 - Fix minimum perl version (RT#67749). Now requires perl 5.8.3 0.04 2011-04-04 - Make compatable with upcoming Moose 2.0 (code provided my Dave Rolsky). See http://blog.moose.perl.org/2011/03/changes-to-moosex-modules-with-moose-20.html for details. 0.03 2010-07-25 - Minor documentation changes 0.02 2010-07-24 - Update TODO - Improve documentation - Modernise by using class_metaroles in Moose::Exporter->setup_import_methods - Add tests for attributes starting with double underscore - Bump Moose prereq to 0.94, add repository - add TODO.org 0.01 2010-07-15 - Initial release - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05 diff --git a/README b/README index a114c65..01aa866 100644 --- a/README +++ b/README @@ -1,71 +1,71 @@ NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with "_set_". If you deckare an attribute with a leading underscore, then the set method will start with "_set_". If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be "use"d after Moose. SEE ALSO There are a number of similar modules on the CPAN. Moose The original. A single mutator method is generated with the same name as the attribute itself. MooseX::Accessors::ReadWritePrivate Changes the parsing of the "is" clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you "_get_baz()" and "_set_baz". MooseX::FollowPBP Names accessors in the style recommended by *Perl Best Practices*: "get_size" and "set_size". - MooseX::SemiAffordanceAccsessor + MooseX::SemiAffordanceAccessor Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with "set_". AUTHOR brian greenfield "<[email protected]>" BUGS Please report any bugs or feature requests to "[email protected]", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/TODO.org b/TODO.org index f37e20f..bac5231 100644 --- a/TODO.org +++ b/TODO.org @@ -1,11 +1,11 @@ * [[TODO]] *** Study MooseX::Accessors::ReadWritePrivate and perhaps implement (steal) his ideas *** test consistent use of versions *** test package name matches path to file * [[DONE]] *** Add repository -*** Modernise as per SemiAffordanceAccsessor etc +*** Modernise as per SemiAffordanceAccessor etc *** Add SEE ALSO * [[WON'T DO/STALLED]] *** Add RATIONALE - sick of writing reader=>'...', writer=>'...' diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index e371a42..8226f8b 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,114 +1,114 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.05'; +our $VERSION = '0.06'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); $metaroles{role_metaroles} = { applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], } if $Moose::VERSION >= 1.9900; Moose::Exporter->setup_import_methods(%metaroles); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. -=head2 L<MooseX::SemiAffordanceAccsessor> +=head2 L<MooseX::SemiAffordanceAccessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 1876695..5bc0366 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.05'; +our $VERSION = '0.06'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
81b058e0c458a97dcc45ba0f5373324e80e3d0ba
Fix minimum perl version (RT#67749)
diff --git a/Build.PL b/Build.PL index 68bc550..ef2dd1b 100644 --- a/Build.PL +++ b/Build.PL @@ -1,23 +1,23 @@ use strict; use warnings; -require 5.00601; +require 5.008003; use Module::Build; my $builder = Module::Build->new( build_requires => { 'Test::More' => '0', }, configure_requires => { 'Module::Build' => '0', }, create_makefile_pl => 'traditional', create_readme => 1, license => 'perl', meta_merge => { resources => { repository => 'http://github.com/briang/MooseX-PrivateSetters' } }, module_name => 'MooseX::PrivateSetters', requires => { 'Moose' => '0.94', }, ); $builder->create_build_script(); diff --git a/CHANGES b/CHANGES index beff4db..b95f583 100644 --- a/CHANGES +++ b/CHANGES @@ -1,21 +1,24 @@ +0.05 2011-05-09 + - Fix minimum perl version (RT#67749). Now requires perl 5.8.3 + 0.04 2011-04-04 - Make compatable with upcoming Moose 2.0 (code provided my Dave Rolsky). See http://blog.moose.perl.org/2011/03/changes-to-moosex-modules-with-moose-20.html for details. 0.03 2010-07-25 - Minor documentation changes 0.02 2010-07-24 - Update TODO - Improve documentation - Modernise by using class_metaroles in Moose::Exporter->setup_import_methods - Add tests for attributes starting with double underscore - Bump Moose prereq to 0.94, add repository - add TODO.org 0.01 2010-07-15 - Initial release - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05 diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 3fea246..e371a42 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,114 +1,114 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.04'; +our $VERSION = '0.05'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); $metaroles{role_metaroles} = { applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], } if $Moose::VERSION >= 1.9900; Moose::Exporter->setup_import_methods(%metaroles); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 317abf2..1876695 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.04'; +our $VERSION = '0.05'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
cf931bb542254a6042066f3120aac5579c8870bd
make compatable with Moose 2.0
diff --git a/CHANGES b/CHANGES index 3703993..beff4db 100644 --- a/CHANGES +++ b/CHANGES @@ -1,19 +1,21 @@ -0.04 - - This module can be used from inside roles with Moose 1.9900+ (Dave - Rolsky) +0.04 2011-04-04 + - Make compatable with upcoming Moose 2.0 (code provided my + Dave Rolsky). See + http://blog.moose.perl.org/2011/03/changes-to-moosex-modules-with-moose-20.html + for details. 0.03 2010-07-25 - Minor documentation changes 0.02 2010-07-24 - Update TODO - Improve documentation - Modernise by using class_metaroles in Moose::Exporter->setup_import_methods - Add tests for attributes starting with double underscore - Bump Moose prereq to 0.94, add repository - add TODO.org 0.01 2010-07-15 - Initial release - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05 diff --git a/README b/README index 59ffe16..a114c65 100644 --- a/README +++ b/README @@ -1,71 +1,71 @@ NAME - MooseX::PrivateSetters - Name your accessors foo() and _set_foo() + MooseX::PrivateSetters - Names your accessors foo() and _set_foo() SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with "_set_". If you deckare an attribute with a leading underscore, then the set method will start with "_set_". If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be "use"d after Moose. SEE ALSO There are a number of similar modules on the CPAN. Moose The original. A single mutator method is generated with the same name as the attribute itself. MooseX::Accessors::ReadWritePrivate Changes the parsing of the "is" clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you "_get_baz()" and "_set_baz". MooseX::FollowPBP Names accessors in the style recommended by *Perl Best Practices*: "get_size" and "set_size". MooseX::SemiAffordanceAccsessor Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with "set_". AUTHOR brian greenfield "<[email protected]>" BUGS Please report any bugs or feature requests to "[email protected]", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 4388d7d..3fea246 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,108 +1,114 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.03'; +our $VERSION = '0.04'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; -Moose::Exporter->setup_import_methods( +my %metaroles = ( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); +$metaroles{role_metaroles} = { + applied_attribute => ['MooseX::PrivateSetters::Role::Attribute'], +} if $Moose::VERSION >= 1.9900; + +Moose::Exporter->setup_import_methods(%metaroles); + 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 74434d7..317abf2 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.03'; +our $VERSION = '0.04'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
ed57a7665f96b21fadc7bb6f2cdd039cfaacae3f
Changes for 0.04
diff --git a/CHANGES b/CHANGES index de0b7a7..3703993 100644 --- a/CHANGES +++ b/CHANGES @@ -1,15 +1,19 @@ +0.04 + - This module can be used from inside roles with Moose 1.9900+ (Dave + Rolsky) + 0.03 2010-07-25 - Minor documentation changes 0.02 2010-07-24 - Update TODO - Improve documentation - Modernise by using class_metaroles in Moose::Exporter->setup_import_methods - Add tests for attributes starting with double underscore - Bump Moose prereq to 0.94, add repository - add TODO.org 0.01 2010-07-15 - Initial release - Based on Dave Rolsky's MooseX-SemiAffordanceAccessor-0.05
briang/MooseX-PrivateSetters
74e1adbcc4d9c69c2abd0871a696f005950b6621
Minor change to abstract for PrivateSetters.pm
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index ade01d5..4388d7d 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,108 +1,108 @@ package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.03'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); 1; __END__ =pod =head1 NAME -MooseX::PrivateSetters - Name your accessors foo() and _set_foo() +MooseX::PrivateSetters - Names your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
briang/MooseX-PrivateSetters
5732da7fb715027a9e320ad9db9a4a6f6cb5eb27
Add VERSIONs to tests
diff --git a/t/010-load.t b/t/010-load.t index f9187a6..c3b6d7a 100644 --- a/t/010-load.t +++ b/t/010-load.t @@ -1,34 +1,34 @@ use strict; use warnings; #use FindBin; #use lib "$FindBin::Bin/../lib"; #use Data::Dump 'pp'; my @mods; BEGIN { @mods = qw( MooseX::PrivateSetters MooseX::PrivateSetters::Role::Attribute ); } use Test::More tests => scalar @mods; +use Moose; use_ok $_ for @mods; -for my $mod (@mods){ - my $file = $INC{$mod}; -} +diag "testing MooseX::PrivateSetters ", MooseX::PrivateSetters->VERSION, + " on perl $] and Moose ", Moose->VERSION; # Should check %INC to make sure we've loaded the right modules but # it's looking fairly hacky. So, I'll just leave the got/expectd # string here as comments. # what they shouldn't look like # "MooseX/PrivateSetters.pm" => "/home/bri/lib/perl/MooseX/PrivateSetters.pm", # "MooseX/PrivateSetters/Role/Attribute.pm" => "/home/bri/lib/perl/MooseX/PrivateSetters/Role/Attribute.pm", # what they should look like # "MooseX/PrivateSetters.pm" => "/home/bri/git/+cpan-mods/MooseX-PrivateSetters/t/../lib/MooseX/PrivateSetters.pm", # "MooseX/PrivateSetters/Role/Attribute.pm" => "/home/bri/git/+cpan-mods/MooseX-PrivateSetters/t/../lib/MooseX/PrivateSetters/Role/Attribute.pm",
briang/MooseX-PrivateSetters
dbc3e9f1e08d5f57023b8362b1416e40beef85f2
Add t/010-load.t
diff --git a/t/010-load.t b/t/010-load.t new file mode 100644 index 0000000..f9187a6 --- /dev/null +++ b/t/010-load.t @@ -0,0 +1,34 @@ +use strict; +use warnings; + +#use FindBin; +#use lib "$FindBin::Bin/../lib"; +#use Data::Dump 'pp'; + +my @mods; +BEGIN { + @mods = qw( + MooseX::PrivateSetters + MooseX::PrivateSetters::Role::Attribute + ); +} + +use Test::More tests => scalar @mods; + +use_ok $_ for @mods; + +for my $mod (@mods){ + my $file = $INC{$mod}; +} + +# Should check %INC to make sure we've loaded the right modules but +# it's looking fairly hacky. So, I'll just leave the got/expectd +# string here as comments. + +# what they shouldn't look like +# "MooseX/PrivateSetters.pm" => "/home/bri/lib/perl/MooseX/PrivateSetters.pm", +# "MooseX/PrivateSetters/Role/Attribute.pm" => "/home/bri/lib/perl/MooseX/PrivateSetters/Role/Attribute.pm", + +# what they should look like +# "MooseX/PrivateSetters.pm" => "/home/bri/git/+cpan-mods/MooseX-PrivateSetters/t/../lib/MooseX/PrivateSetters.pm", +# "MooseX/PrivateSetters/Role/Attribute.pm" => "/home/bri/git/+cpan-mods/MooseX-PrivateSetters/t/../lib/MooseX/PrivateSetters/Role/Attribute.pm",
briang/MooseX-PrivateSetters
9d1e914f364bee147e98c6b100e015f5ec1ed6c5
Bump version to 0.03
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 534b6ef..ade01d5 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,108 +1,108 @@ package MooseX::PrivateSetters; use strict; use warnings; -our $VERSION = '0.02'; +our $VERSION = '0.03'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set method will start with C<_set_>. If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index cc5f230..74434d7 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; -our $VERSION = '0.02'; +our $VERSION = '0.03'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
8b1acbb16d1731a2fa438242de3fb29d7ffa86cd
Regenerate README
diff --git a/README b/README index a975a5c..59ffe16 100644 --- a/README +++ b/README @@ -1,70 +1,71 @@ NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); - ... + package main; + sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name - as the accessor, while set methods are prefixed with "<_set_">. + as the accessor, while set methods are prefixed with "_set_". - If you define an attribute with a leading underscore, then the set - method will start with "<_set_">. + If you deckare an attribute with a leading underscore, then the set + method will start with "_set_". - If you explicitly set a "<reader"> or "<writer"> name when creating an + If you explicitly set a "reader" or "writer" name when creating an attribute, then that attribute's naming scheme is left unchanged. - Load order of this module is important. It must be "<use">d after Moose. + Load order of this module is important. It must be "use"d after Moose. SEE ALSO There are a number of similar modules on the CPAN. Moose - The original. A single mutator method with the same name as the - attribute itself + The original. A single mutator method is generated with the same name as + the attribute itself. MooseX::Accessors::ReadWritePrivate - Changes the parsing of the "<is"> clause, making new options available. + Changes the parsing of the "is" clause, making new options available. For example, - has baz => ( is => 'rpwp', # is private reader, is private writer + has baz => ( is => 'rpwp', # private reader, private writer - gets you "<_get_baz()"> and "<_set_baz">. + gets you "_get_baz()" and "_set_baz". MooseX::FollowPBP Names accessors in the style recommended by *Perl Best Practices*: - "<get_size"> and "<set_size">. + "get_size" and "set_size". MooseX::SemiAffordanceAccsessor Has separate methods for getting and setting. The getter has the same - name as the attribute, and the setter is prefixed with "<set_">. + name as the attribute, and the setter is prefixed with "set_". AUTHOR - brian greenfield, "<[email protected]>" + brian greenfield "<[email protected]>" BUGS Please report any bugs or feature requests to "[email protected]", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
74e29ae0dac02e30998fdbea48b426b1fcb638a9
Ignore build files
diff --git a/.gitignore b/.gitignore index b25c15b..dedf2aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,14 @@ *~ +*.bak + +blib/ +Build +_build/ +cover_db/ +Makefile +Makefile.PL +MANIFEST +MANIFEST.SKIP +META.yml +MooseX-PrivateSetters-* +MYMETA.yml
briang/MooseX-PrivateSetters
44f6a7a5dd5b85d7d47fca37440ded13af3dcf65
Change C<< ... >> to C< ... > in all pod
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index addac37..534b6ef 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,108 +1,108 @@ package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.02'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); ... package main; sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name -as the accessor, while set methods are prefixed with C<<_set_>>. +as the accessor, while set methods are prefixed with C<_set_>. If you deckare an attribute with a leading underscore, then the set -method will start with C<<_set_>>. +method will start with C<_set_>. -If you explicitly set a C<<reader>> or C<<writer>> name when creating +If you explicitly set a C<reader> or C<writer> name when creating an attribute, then that attribute's naming scheme is left unchanged. -Load order of this module is important. It must be C<<use>>d after +Load order of this module is important. It must be C<use>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> The original. A single mutator method is generated with the same name as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> -Changes the parsing of the C<<is>> clause, making new options +Changes the parsing of the C<is> clause, making new options available. For example, has baz => ( is => 'rpwp', # private reader, private writer -gets you C<<_get_baz()>> and C<<_set_baz>>. +gets you C<_get_baz()> and C<_set_baz>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: -C<<get_size>> and C<<set_size>>. +C<get_size> and C<set_size>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same -name as the attribute, and the setter is prefixed with C<<set_>>. +name as the attribute, and the setter is prefixed with C<set_>. =head1 AUTHOR -brian greenfield, C<< <[email protected]> >> +brian greenfield C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/MooseX/PrivateSetters/Role/Attribute.pm b/lib/MooseX/PrivateSetters/Role/Attribute.pm index 25927ab..cc5f230 100644 --- a/lib/MooseX/PrivateSetters/Role/Attribute.pm +++ b/lib/MooseX/PrivateSetters/Role/Attribute.pm @@ -1,76 +1,76 @@ package MooseX::PrivateSetters::Role::Attribute; use strict; use warnings; our $VERSION = '0.02'; use Moose::Role; before '_process_options' => sub { my $class = shift; my $name = shift; my $options = shift; if ( exists $options->{is} && ! ( exists $options->{reader} || exists $options->{writer} ) ) { if ( $options->{is} eq 'ro' ) { $options->{reader} = $name; delete $options->{is}; } elsif ( $options->{is} eq 'rw' ) { $options->{reader} = $name; my $prefix = $name =~ /^_/ ? '_set' : '_set_'; $options->{writer} = $prefix . $name; delete $options->{is}; } } }; no Moose::Role; 1; =head1 NAME MooseX::PrivateSetters::Role::Attribute - Names setters as such, and makes them private =head1 SYNOPSIS Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); =head1 DESCRIPTION This role applies a method modifier to the C<_process_options()> method, and tweaks the writer parameters so that they are private with an explicit '_set_attr' method. Getters are left unchanged. This role copes with attributes intended to be private (ie, starts with an underscore), with no double-underscore in the setter. For example: | Code | Reader | Writer | |---------------------------+--------+-------------| | has 'baz' => (is 'rw'); | baz() | _set_baz() | | has 'baz' => (is 'ro'); | baz() | | | has '_baz' => (is 'rw'); | _baz() | _set_baz() | | has '__baz' => (is 'rw'); | _baz() | _set__baz() | You probably don't want to use this module. You probably should be looking at L<MooseX::PrivateSetters> instead. =head1 AUTHOR -brian greenfield, C<< <[email protected]> >> +brian greenfield C<< <[email protected]> >> =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
briang/MooseX-PrivateSetters
4e6fc96d13f5d8a740add49664c20061e9be7be1
Add a couple of TODOs
diff --git a/TODO.org b/TODO.org index 8da220d..f37e20f 100644 --- a/TODO.org +++ b/TODO.org @@ -1,9 +1,11 @@ * [[TODO]] *** Study MooseX::Accessors::ReadWritePrivate and perhaps implement (steal) his ideas +*** test consistent use of versions +*** test package name matches path to file * [[DONE]] *** Add repository *** Modernise as per SemiAffordanceAccsessor etc *** Add SEE ALSO * [[WON'T DO/STALLED]] *** Add RATIONALE - sick of writing reader=>'...', writer=>'...'
briang/MooseX-PrivateSetters
611c8c059f6cb16e83f6b8fed5c6a283ba93c730
Minor documentation changes
diff --git a/lib/MooseX/PrivateSetters.pm b/lib/MooseX/PrivateSetters.pm index 76be9dc..addac37 100644 --- a/lib/MooseX/PrivateSetters.pm +++ b/lib/MooseX/PrivateSetters.pm @@ -1,107 +1,108 @@ package MooseX::PrivateSetters; use strict; use warnings; our $VERSION = '0.02'; use Moose 0.94 (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::PrivateSetters::Role::Attribute; Moose::Exporter->setup_import_methods( class_metaroles => { attribute => ['MooseX::PrivateSetters::Role::Attribute'], }, ); 1; __END__ =pod =head1 NAME MooseX::PrivateSetters - Name your accessors foo() and _set_foo() =head1 SYNOPSIS use Moose; use MooseX::PrivateSetters; # make some attributes has 'foo' => ( is => 'rw' ); - ... + package main; + sub bar { $self = shift; $self->_set_foo(1) unless $self->foo } =head1 DESCRIPTION This module does not provide any methods. Simply loading it changes the default naming policy for the loading class so that accessors are separated into get and set methods. The get methods have the same name as the accessor, while set methods are prefixed with C<<_set_>>. -If you define an attribute with a leading underscore, then the set +If you deckare an attribute with a leading underscore, then the set method will start with C<<_set_>>. If you explicitly set a C<<reader>> or C<<writer>> name when creating an attribute, then that attribute's naming scheme is left unchanged. Load order of this module is important. It must be C<<use>>d after L<Moose>. =head1 SEE ALSO There are a number of similar modules on the CPAN. =head2 L<Moose> -The original. A single mutator method with the same name as the -attribute itself +The original. A single mutator method is generated with the same name +as the attribute itself. =head2 L<MooseX::Accessors::ReadWritePrivate> Changes the parsing of the C<<is>> clause, making new options available. For example, - has baz => ( is => 'rpwp', # is private reader, is private writer + has baz => ( is => 'rpwp', # private reader, private writer gets you C<<_get_baz()>> and C<<_set_baz>>. =head2 L<MooseX::FollowPBP> Names accessors in the style recommended by I<Perl Best Practices>: C<<get_size>> and C<<set_size>>. =head2 L<MooseX::SemiAffordanceAccsessor> Has separate methods for getting and setting. The getter has the same name as the attribute, and the setter is prefixed with C<<set_>>. =head1 AUTHOR brian greenfield, C<< <[email protected]> >> =head1 BUGS Please report any bugs or feature requests to C<[email protected]>, or through the web interface at L<http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 COPYRIGHT & LICENSE Copyright 2010 brian greenfield This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
briang/MooseX-PrivateSetters
9899c9e6065990b08d183c67dab2a53b2b7a61de
Add README to keep github happy
diff --git a/README b/README new file mode 100644 index 0000000..a975a5c --- /dev/null +++ b/README @@ -0,0 +1,70 @@ +NAME + MooseX::PrivateSetters - Name your accessors foo() and _set_foo() + +SYNOPSIS + use Moose; + use MooseX::PrivateSetters; + + # make some attributes + + has 'foo' => ( is => 'rw' ); + + ... + + sub bar { + $self = shift; + $self->_set_foo(1) unless $self->foo + } + +DESCRIPTION + This module does not provide any methods. Simply loading it changes the + default naming policy for the loading class so that accessors are + separated into get and set methods. The get methods have the same name + as the accessor, while set methods are prefixed with "<_set_">. + + If you define an attribute with a leading underscore, then the set + method will start with "<_set_">. + + If you explicitly set a "<reader"> or "<writer"> name when creating an + attribute, then that attribute's naming scheme is left unchanged. + + Load order of this module is important. It must be "<use">d after Moose. + +SEE ALSO + There are a number of similar modules on the CPAN. + + Moose + The original. A single mutator method with the same name as the + attribute itself + + MooseX::Accessors::ReadWritePrivate + Changes the parsing of the "<is"> clause, making new options available. + For example, + + has baz => ( is => 'rpwp', # is private reader, is private writer + + gets you "<_get_baz()"> and "<_set_baz">. + + MooseX::FollowPBP + Names accessors in the style recommended by *Perl Best Practices*: + "<get_size"> and "<set_size">. + + MooseX::SemiAffordanceAccsessor + Has separate methods for getting and setting. The getter has the same + name as the attribute, and the setter is prefixed with "<set_">. + +AUTHOR + brian greenfield, "<[email protected]>" + +BUGS + Please report any bugs or feature requests to + "[email protected]", or through the web interface at + <http://rt.cpan.org>. I will be notified, and then you'll automatically + be notified of progress on your bug as I make changes. + +COPYRIGHT & LICENSE + Copyright 2010 brian greenfield + + This program is free software; you can redistribute it and/or modify it + under the same terms as Perl itself. +