summary refs log blame commit diff stats
path: root/plugins/perl/lib/HexChat/Embed.pm
blob: c033d3c931bdac669fee2bd22940d544f7ae5ed4 (plain) (tree)
075cc61c ^
pre { line-height: 125%; } td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*

  Copyright (c) 2010 Samuel Lidén Borell <samuel@kodafritt.se>

  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.

*/

#ifdef __APPLE__
#define __AVAILABILITYMACROS__
#define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER
#endif

#include <stdlib.h>
#include <string.h>
#include <openssl/blowfish.h>

#include "keystore.h"
#include "fish.h"

#define IB 64
static const char fish_base64[64] = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const signed char fish_unbase64[256] = {
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB,IB,IB,
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB,IB,IB,
//      !  "  #  $  %  &  '  (    )  *  +  ,  -  .  /
    IB,IB,IB,IB,IB,IB,IB,IB,  IB,IB,IB,IB,IB,IB, 0, 1,
//   0  1  2  3  4  5  6  7    8  9  :  ;  <  =  >  ?
     2, 3, 4, 5, 6, 7, 8, 9,  10,11,IB,IB,IB,IB,IB,IB,
//   @  A  B  C  D  E  F  G    H  I  J  K  L  M  N  O
    IB,38,39,40,41,42,43,44,  45,46,47,48,49,50,51,52,
//   P  Q  R  S  T  U  V  W    X  Y  Z  [  \  ]  ^  _
    53,54,55,56,57,58,59,60,  61,62,63,IB,IB,IB,IB,IB,
//   `  a  b  c  d  e  f  g    h  i  j  k  l  m  n  o
    IB,12,13,14,15,16,17,18,  19,20,21,22,23,24,25,26,
//   p  q  r  s  t  u  v  w    x  y  z  {  |  }  ~  <del>
    27,28,29,30,31,32,33,34,  35,36,37,IB,IB,IB,IB,IB,
};

#define GET_BYTES(dest, source) do { \
    *((dest)++) = ((source) >> 24) & 0xFF; \
    *((dest)++) = ((source) >> 16) & 0xFF; \
    *((dest)++) = ((source) >> 8) & 0xFF; \
    *((dest)++) = (source) & 0xFF; \
} while (0);


char *fish_encrypt(const char *key, size_t keylen, const char *message) {
    BF_KEY bfkey;
    size_t messagelen;
    size_t i;
    int j;
    char *encrypted;
    char *end;
    unsigned char bit;
    unsigned char word;
    unsigned char d;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    messagelen = strlen(message);
    if (messagelen == 0) return NULL;
    encrypted = malloc(((messagelen-1)/8)*12 + 12 + 1); // each 8-byte block becomes 12 bytes
    end = encrypted;
    if (!encrypted) return NULL;
     
    while (*message) {
        // Read 8 bytes (a Blowfish block)
        BF_LONG binary[2] = { 0, 0 };
        unsigned char c;
        for (i = 0; i < 8; i++) {
            c = message[i];
            binary[i >> 2] |= c << 8*(3 - (i&3));
            if (c == '\0') break;
        }
        message += 8;
        
        // Encrypt block
        BF_encrypt(binary, &bfkey);
        
        // Emit FiSH-BASE64
        bit = 0;
        word = 1;
        for (j = 0; j < 12; j++) {
            d = fish_base64[(binary[word] >> bit) & 63];
            *(end++) = d;
            bit += 6;
            if (j == 5) {
                bit = 0;
                word = 0;
            }
        }
        
        // Stop if a null terminator was found
        if (c == '\0') break;
    }
    *end = '\0';
    return encrypted;
}


char *fish_decrypt(const char *key, size_t keylen, const char *data) {
    BF_KEY bfkey;
    size_t i;
    char *decrypted;
    char *end;
    unsigned char bit;
    unsigned char word;
    unsigned char d;
    BF_set_key(&bfkey, keylen, (const unsigned char*)key);
    
    decrypted = malloc(strlen(data)+1);
    end = decrypted;
    if (!decrypted) return NULL;
    
    while (*data) {
        // Convert from FiSH-BASE64
        BF_LONG binary[2] = { 0, 0 };
        bit = 0;
        word = 1;
        for (i = 0; i < 12; i++) {
            d = fish_unbase64[(const unsigned char)*(data++)];
            if (d == IB) goto decrypt_end;
            binary[word] |= d << bit;
            bit += 6;
            if (i == 5) {
                bit = 0;
                word = 0;
            }
        }
        
        // Decrypt block
        BF_decrypt(binary, &bfkey);
        
        // Copy to buffer
        GET_BYTES(end, binary[0]);
        GET_BYTES(end, binary[1]);
    }
    
  decrypt_end:
    *end = '\0';
    return decrypted;
}

/**
 * Encrypts a message (see fish_decrypt). The key is searched for in the
 * key store.
 */
char *fish_encrypt_for_nick(const char *nick, const char *data) {
    char *key;
    char *encrypted;

    // Look for key
    key = keystore_get_key(nick);
    if (!key) return NULL;
    
    // Encrypt
    encrypted = fish_encrypt(key, strlen(key), data);
    
    free(key);
    return encrypted;
}

/**
 * Decrypts a message (see fish_decrypt). The key is searched for in the
 * key store.
 */
char *fish_decrypt_from_nick(const char *nick, const char *data) {
    char *key;
    char *decrypted;
    // Look for key
    key = keystore_get_key(nick);
    if (!key) return NULL;
    
    // Decrypt
    decrypted = fish_decrypt(key, strlen(key), data);
    
    free(key);
    return decrypted;
}
'>
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
                       

             
                 
                                                     





                                                                       
                                                                           














                                                                           

             








                                                                               






                                                                                 
                                


                                                             
                               











                                                                                
                                                                                     
                                   


                                                                    




























                                                                                                       
                                                         



                                 









                                                                                   

                                                                                 



                                                                
                                                            


                                                                
 


                                                     
                                                                         




                                                                                     
                                                                
































                                                                           
                                                                   


                         



                                                                   



                                                                          

                                                   
                                        
                

                                                               







                                                         
                                













                                                  
                                


                
                                                    


















                                                                                     





















                                                  
















                                                                        
                                             










                                               
                                                                   

                         
               





                                                                 
                                                                    


                         




                                                    



                                        

                                                                                 
                                                          

                 









                                                                                    
                                             
                  
                                                        

                                 




                                                                                            






                                          










                                           
 
package HexChat::Embed;
use strict;
use warnings;
use Data::Dumper;
# list of loaded scripts keyed by their package names
# The package names are generated from the filename of the script using
# the file2pkg() function.
# The values of this hash are hash references with the following keys:
#   filename
#     The full path to the script.
#   gui_entry
#     This is hexchat_plugin pointer that is used to remove the script from
#     Plugins and Scripts window when a script is unloaded. This has also
#     been converted with the PTR2IV() macro.
#   hooks
#     This is an array of hooks that are associated with this script.
#     These are pointers that have been converted with the PTR2IV() macro.
#   inner_packages
#     Other packages that are defined in a script. This is not recommended
#     partly because these will also get removed when a script is unloaded.
#   loaded_at
#     A timestamp of when the script was loaded. The value is whatever
#     Time::HiRes::time() returns. This is used to retain load order when
#     using the RELOADALL command.
#   shutdown
#     This is either a code ref or undef. It will be executed just before a
#     script is unloaded.
our %scripts;

# This is a mapping of "inner package" => "containing script package"
our %owner_package;

# used to keep track of which package a hook belongs to, if the normal way of
# checking which script is calling a hook function fails this will be used
# instead. When a hook is created this will be copied to the HookData structure
# and when a callback is invoked this it will be used to set this value.
our $current_package;

sub load {
	my $file = expand_homedir( shift @_ );
	my $package = file2pkg( $file );
	
	if( exists $scripts{$package} ) {
		my $pkg_info = pkg_info( $package );
		my $filename = File::Basename::basename( $pkg_info->{filename} );
		HexChat::printf(
			qq{'%s' already loaded from '%s'.\n},
			$filename, $pkg_info->{filename}
		);
		HexChat::print(
			'If this is a different script then it rename and try '.
			'loading it again.'
		);
		return 2;
	}
	
	if( open my $source_handle, $file ) {
		my $source = do {local $/; <$source_handle>};
		close $source_handle;
		# we shouldn't care about things after __END__
		$source =~ s/^__END__.*//ms;
		
		# this must come before the eval or the filename will not be found in
		# HexChat::register
		$scripts{$package}{filename} = $file;
		$scripts{$package}{loaded_at} = Time::HiRes::time();

		# this must be done before the error check so the unload will remove
		# any inner packages defined by the script. if a script fails to load
		# then any inner packages need to be removed as well.
		my @inner_packages = $source =~
			m/^\s*package \s+
				((?:[^\W:]+(?:::)?)+)\s*? # package name
				# strict version number
				(?:\d+(?:[.]\d+) # positive integer or decimal-fraction
					|v\d+(?:[.]\d+){2,})? # dotted-decimal v-string
				[{;]
			/mgx;

		# check if any inner package defined in the to be loaded script has
		# already been defined by another script
		my @conflicts;
		for my $inner ( @inner_packages ) {
			if( exists $owner_package{ $inner } ) {
				push @conflicts, $inner;
			}
		}

		# report conflicts and bail out
		if( @conflicts ) {
			my $error_message =
				"'$file' won't be loaded due to conflicting inner packages:\n";
			for my $conflict_package ( @conflicts ) {
				$error_message .= "   $conflict_package already defined in " .
					pkg_info($owner_package{ $conflict_package })->{filename}."\n";
			}
			HexChat::print( $error_message );

			return 2;
		}

		my $full_path = File::Spec->rel2abs( $file );
		$source =~ s/^/#line 1 "$full_path"\n\x7Bpackage $package;/;

		# make sure we add the closing } even if the last line is a comment
		if( $source =~ /^#.*\Z/m ) {
			$source =~ s/^(?=#.*\Z)/\x7D/m;
		} else {
			$source =~ s/\Z/\x7D/;
		}

		$scripts{$package}{inner_packages} = [ @inner_packages ];
		@owner_package{ @inner_packages } = ($package) x @inner_packages;
		_do_eval( $source );

		unless( exists $scripts{$package}{gui_entry} ) {
			$scripts{$package}{gui_entry} =
				HexChat::Internal::register(
					"", "unknown", "", $file
				);
		}

		if( $@ ) {
			# something went wrong
			$@ =~ s/\(eval \d+\)/$file/g;
			HexChat::print( "Error loading '$file':\n$@\n" );
			# make sure the script list doesn't contain false information
			unload( $scripts{$package}{filename} );
			return 1;
		}
	} else {
		HexChat::print( "Error opening '$file': $!\n" );
		return 2;
	}

	return 0;
}

sub _do_eval {
	no strict;
	no warnings;
	eval $_[0];
}

sub unload {
	my $file = shift @_;
	my $package = file2pkg( $file );
	my $pkg_info = pkg_info( $package );

	if( $pkg_info ) {	
		# take care of the shutdown callback
		if( exists $pkg_info->{shutdown} ) {
			# allow incorrectly written scripts to be unloaded
			eval {
				if( ref $pkg_info->{shutdown} eq 'CODE' ) {
					$pkg_info->{shutdown}->();
				} elsif ( $pkg_info->{shutdown} ) {
					no strict 'refs';
					&{$pkg_info->{shutdown}};
				}
			};
		}

		if( exists $pkg_info->{hooks} ) {
			for my $hook ( @{$pkg_info->{hooks}} ) {
				HexChat::unhook( $hook, $package );
			}
		}

		if( exists $pkg_info->{gui_entry} ) {
			plugingui_remove( $pkg_info->{gui_entry} );
		}
		
		delete @owner_package{ @{$pkg_info->{inner_packages}} };
		for my $inner_package ( @{$pkg_info->{inner_packages}} ) {
			Symbol::delete_package( $inner_package );
		}
		Symbol::delete_package( $package );
		delete $scripts{$package};
		return HexChat::EAT_ALL;
	} else {
		HexChat::print( qq{"$file" is not loaded.\n} );
		return HexChat::EAT_NONE;
	}
}

sub unload_all {
	for my $package ( keys %scripts ) {
		unload( $scripts{$package}->{filename} );
	}
	
	return HexChat::EAT_ALL;
}

sub reload {
	my $file = shift @_;
	my $package = file2pkg( $file );
	my $pkg_info = pkg_info( $package );
	my $fullpath = $file;
	
	if( $pkg_info ) {
		$fullpath = $pkg_info->{filename};
		unload( $file );
	}
	
	load( $fullpath );
	return HexChat::EAT_ALL;
}

sub reload_all {
	my @dirs = HexChat::get_info( "configdir" );
	push @dirs, File::Spec->catdir( $dirs[0], "plugins" );
	for my $dir ( @dirs ) {
		my $auto_load_glob = File::Spec->catfile( $dir, "*.pl" );
		my @scripts = map { $_->{filename} }
			sort { $a->{loaded_at} <=> $b->{loaded_at} } values %scripts;
		push @scripts, File::Glob::bsd_glob( $auto_load_glob );

		my %seen;
		@scripts = grep { !$seen{ $_ }++ } @scripts;

		unload_all();
		for my $script ( @scripts ) {
			if( !pkg_info( file2pkg( $script ) ) ) {
				load( $script );
			}
		}
	}
}

sub evaluate {
	my ($code) = @_;

	my @results = eval $code;
	HexChat::print $@ if $@; #print warnings

	local $Data::Dumper::Sortkeys = 1;
	local $Data::Dumper::Terse    = 1;

	if (@results > 1) {
		HexChat::print Dumper \@results;
	}
	elsif (ref $results[0] || !$results[0]) {
		HexChat::print Dumper $results[0];
	}
	else {
		HexChat::print $results[0];
	}

	return HexChat::EAT_HEXCHAT;
};

sub expand_homedir {
	my $file = shift @_;

	if ( $^O eq "MSWin32" ) {
		$file =~ s/^~/$ENV{USERPROFILE}/;
	} else {
		$file =~ s{^~}{
			(getpwuid($>))[7] ||  $ENV{HOME} || $ENV{LOGDIR}
		}ex;
	}
	return $file;
}

sub file2pkg {
	my $string = File::Basename::basename( shift @_ );
	$string =~ s/\.pl$//i;
	$string =~ s|([^A-Za-z0-9/])|'_'.unpack("H*",$1)|eg;
	return "HexChat::Script::" . $string;
}

sub pkg_info {
	my $package = shift @_;
	return $scripts{$package};
}

sub find_external_pkg {
	my $level = 1;

	while( my @frame = caller( $level ) ) {
		return @frame if $frame[0] !~ /(?:^IRC$|^HexChat)/;
		$level++;
	}
	return;
}

sub find_pkg {
	my $level = 1;

	while( my ($package, $file, $line) = caller( $level ) ) {
		return $package if $package =~ /^HexChat::Script::/;
		$level++;
	}

	my $current_package = get_current_package();
	if( defined $current_package ) {
		return $current_package;
	}

	my @frame = find_external_pkg();
	my $location;

	if( $frame[0] or $frame[1] ) {
		my $calling_package = $frame[0];
		if( defined( my $owner = $owner_package{ $calling_package } ) ) {
			return ($owner, $calling_package);
		}

		$location = $frame[1] ? $frame[1] : "package $frame[0]";
		$location .= " line $frame[2]";
	} else {
		$location = "unknown location";
	}

	die "Unable to determine which script this hook belongs to. at $location\n";

}

# convert function names into code references
sub fix_callback {
	my ($package, $calling_package, $callback) = @_;
	
	unless( ref $callback ) {
		unless( $callback =~ /::/ ) {
			my $prefix = defined $calling_package ? $calling_package : $package;
			$callback =~ s/^/${prefix}::/;
		}

		no strict 'subs';
		$callback = \&{$callback};
	}
	
	return $callback;
}

sub get_current_package {
	return $current_package;
}

sub set_current_package {
	my $old_package = $current_package;
	$current_package = shift;

	return $old_package;
}

1