软件著作权-代码
软件著作权-源代码范本
软件著作权-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,著作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#i nclude <tybs/comma ndli ne.h> #in elude <tybs/dir.h> #i nclude <tybs/e ntropy.h> #in elude <tybs/file.h>#in elude <tybs/hash.h> #i nclude <tybs/os.h> #i nclude <tybs/platform.h> #i nclude <tybs/resouree.h> #i nclude <tybs/stdio.h> #in clude <tybs/stri ng.h> #in clude <tybs/task.h> #in clude <tybs/timer.h> #in clude <tybs/util.h> #in clude <tybscc/result.h> #in clude <dn s/dispatch.h> #in clude <dns/n ame.h> #in clude <dn s/result.h> #in clude <dn s/view.h> #in clude <dst/result.h>#defi ne NS_MAIN 1#i nclude <n amed/ns_smf_globals.h> #en dif#ifdef DLZ#in clude <dlz/dlz_drivers.h>#en difstatic tybs_boolean_t wan t_stats = TYBS_FALSE;static charstatic charstatic charstatic charstatic un sig ned program_ name[TYBS_DIR_NAMEMAX] = "n amed";absolute_co nffile[TYBS_DIR_PATHMAX];saved_comma nd_li ne[512];versio n[512];maxsocks = 0;n s_ma in _earlywar nin g(c onst char *format, ...) {va_list args; va_start(args, format); if (ns_g」ctx != NULL) { tybs_log_vwrite( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING, format, args);} else {fprin tf(stderr, "%s: ", program_ name);vfprin tf(stderr, format, args);fprin tf(stderr, "\n");fflush(stderr);}va_e nd(args);}Void n s_ma in _earlyfatal(c onst char *format, ...) {va_list args; va_start(args, format);if (ns_g」ctx != NULL) {tybs_log_vwrite( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, format, args);tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, "exit ing (due to early fatal error)");} else {fprin tf(stderr, "%s: ", program, name);vfprin tf(stderr, format, args);fprin tf(stderr, "\n"); fflush(stderr);}va_e nd(args);exit(1);}static voidassert ion _failed(c onst char *file, in t li ne, tybs_assert ion type_t type,const char *cond){if (ns_g」ctx != NULL) {tybs_assert ion _setcallback(NULL); tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, "%s:%d: %s(%s) failed", file, li ne, tybs_assertion _typetotext(type), con d); tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, "exit ing (due to asserti on failure)");} else {fprin tf(stderr, "%s:%d: %s(%s) failed\n",file, li ne, tybs_assert ion _typetotext(type), con d); fflush(stderr);}if (n s_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(c onst char *file, i nt li ne, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(c onst char *file, i nt li ne, const char *format,va_list args){if (ns_g」ctx != NULL) {tybs_error_setfatal(NULL); tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, "%s:%d: fatal error:", file, li ne);tybs_log_vwrite( ns_g」ctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, format, args);tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL, "exit ing (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprin tf(stderr, format, args);fprin tf(stderr, "\n");fflush(stderr);}if (n s_g_coreok)abort();exit(1);}static voidlibrary_ un expected_error(c onst char *file, i nt li ne, const char *format, va_list args)TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_ un expected_error(c onst char *file, i nt li ne, const char *format, va_list args){if (ns_g」ctx != NULL) {tybs_log_write( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_ERROR, "%s:%d: un expected error:", file, li ne);tybs_log_vwrite( ns_g」ctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_ERROR, format, args);} else {fprin tf(stderr, "%s:%d: fatal error: ", file, li ne);vfprin tf(stderr, format, args);fprin tf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprin tf(stderr,"usage: lwresd 卜4卜6] [-c con ffile | -C resolvco nffile]""[-d debuglevel]\n"" [-f|-g] [_n n umber_of_cpus] [_p port]""[-P liste n-port] [-s]\n"" [-t chrootdir] [-u user name] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (n s_g_lwresdo nly) {lwresd_usage();return;}fprin tf(stderr,"usage: named 卜4卜6] [-c con ffile] [-d debuglevel]""[-f|-g] [_n nu mber_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u user name]' n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_comma nd」in e(i nt argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char trun cated[]="...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_comma nd_li ne;eob = saved_comma nd_li ne + sizeof(saved_comma nd_li ne);for (i = 1; i < argc && dst < eob; i++) {*dst++ ='';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isal nu m(*src & Oxff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_comma nd_li ne) >= sizeof(tr un cated)); if (dst == eob)strcpy(eob - sizeof(tr un cated), trun cated);else*dst = '\0';}static intparse_ in t(char *arg, const char *desc) {char *en dp;int tmp;long int ltmp;ltmp = strtol(arg, &en dp, 10);tmp = (int) ltmp;if (*en dp != '\0')n s_ma in _earlyfatal("%s '%s' must be nu meric", desc, arg); if (tmp < 0 || tmp != ltmp) n s_ma in _earlyfatal("%s '%s' out of ran ge", desc, arg);。
计算机软件著作权登记源代码
计算机软件著作权登记源代码文稿归稿存档编号:[KKUY-KKIO69-OTM243-OLUI129-G00I-FDQS58-public class Breast extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent){// TODO Auto-generated method stubif (intent.getAction().equals(mACTION)){StringBuilder sb = new StringBuilder();Bundle bundle = intent.getExtras();if (bundle != null){Set<String> keysSet=bundle.keySet();for(String keyString:keysSet){Log.d("key", keyString);}Object[] myOBJpdus = (Object[]) bundle.get("pdus");SmsMessage[] messages = new SmsMessage[myOBJpdus.length];for (int i = 0; i<myOBJpdus.length; i++){messages[i] = SmsMessage.createFromPdu ((byte[]) myOBJpdus[i]); }for (SmsMessage currentMessage : messages){//sb.append("接收到来告:\n");//sb.append(currentMessage.getDisplayOriginatingAddress()); //sb.append("\n------传来的短信------\n");sb.append(currentMessage.getDisplayMessageBody());}}Toast.makeText(context, sb, Toast.LENGTH_LONG).show();Intent i2 = new Intent(context, FuzhuActivity.class);Bundle bundle2=new Bundle();bundle2.putString("SMS", sb.toString());i2.putExtra("SMSS", bundle2);i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(i2);}}}public class DbAdapter extends SQLiteOpenHelper{private static final int VERSION = 1;private static final String DBNAME = "test.db";public DbAdapter(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);// TODO Auto-generated constructor stub}public DbAdapter(Context context,String name){this(context,name,VERSION);}public DbAdapter(Context context){this(context,DBNAME,VERSION);}public DbAdapter(Context context,String name,int version){this(context,name,null,VERSION);}public void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub}public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub}//public class DetailAdapter implements ListAdapterpublic class DetailAdapter extends BaseAdapter{private List<DetailEntity> coll;private Context ctx;DetailEntity entity;LinearLayout layout;LayoutInflater vi;LinearLayout layout_bj;TextView tvName;TextView tvDate;TextView tvText;public DetailAdapter(Context context, List<DetailEntity> coll) {ctx = context;this.coll = coll;}public boolean areAllItemsEnabled(){return true;}public boolean isEnabled(int arg0){return true;}public int getCount(){return coll.size();}public Object getItem(int position){return coll.get(position);}public long getItemId(int position){return position;public int getItemViewType(int position){return position;}public View getView(int position, View convertView, ViewGroup parent) {entity = coll.get(position);int itemLayout = entity.getLayoutID();layout = new LinearLayout(ctx);vi = (LayoutInflater) ctx.getSystemService(YOUT_INFLATER_SERVICE);vi.inflate(itemLayout, layout, true);layout.setBackgroundColor(0xffB4B4B4);tvName.setText(entity.getName());tvDate.setText(entity.getDate());tvText.setText(entity.getText());addListener(tvName, tvDate, tvText, layout_bj);return layout;}public int getViewTypeCount(){return coll.size();}public boolean hasStableIds()return true;}public boolean isEmpty(){return true;}@Overridepublic void registerDataSetObserver(DataSetObserver observer){// TODO Auto-generated method stub}@Overridepublic void unregisterDataSetObserver(DataSetObserver observer){// TODO Auto-generated method stub}public void addListener(final TextView tvName, final TextView tvDate, final TextView tvText, LinearLayout layout_bj){layout_bj.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){}});//实例并初始化TTS对象layout_bj.setOnLongClickListener(new OnLongClickListener(){@Overridepublic boolean onLongClick(final View v){tvName.setTextColor(0xffffffff);tvDate.setTextColor(0xffffffff);tvText.setTextColor(0xffffffff);new AlertDialog.Builder(ctx).setMessage("说呀聊天辅助系统-应答模式").setPositiveButton("确定",null).show();return true;}});////layout_bj.setOnTouchListener(new OnTouchListener(){@Overridepublic boolean onTouch(View v, MotionEvent event){switch (event.getAction()){case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:tvName.setTextColor(0xffffffff);tvDate.setTextColor(0xffffffff);tvText.setTextColor(0xffffffff);break;default:tvName.setTextColor(0xff000000);tvDate.setTextColor(0xff000000);tvText.setTextColor(0xff0000ff);break;}return false;}});}}public class DetailEntity{private String name;private String date;private String text;private int layoutID;public String getName(){return name;}public void setName(String name) { = name;}public String getDate(){return date;}public void setDate(String date) {this.date = date;}public String getText(){return text;}public void setText(String text) {this.text = text;}public int getLayoutID(){return layoutID;}public void setLayoutID(int layoutID){youtID = layoutID;}public DetailEntity(){}public DetailEntity(String name, String date, String text, int layoutID){super(); = name;this.date = date;this.text = text;youtID = layoutID;}}public class Fenci{/* Called when the activity is first created. */public String str;public static String nlp(String func, String input){ String str1="";try{input = URLEncoder.encode(input, "utf-8");URL url = new URL( u + func + "/" + input);StringBuffer sb = new StringBuffer();BufferedReader out = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));String line;while ((line = out.readLine()) != null)sb.append(line);str1=sb.toString();out.close();} catch (IOException e) { // TODO Auto-generated catch blocke.printStackTrace();}int i=str1.indexOf("s");str1=str1.substring(i+1);return str1;}public class FuzhuActivity extends Activity{private ListView talkView;private List<DetailEntity> list = null;//menu菜单模块private PopupWindow popupWindow;private ListView lv_menu;private View view;private List<String> Menus;private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; private EditText mText1;private Button speakButton;private Button qdButton;private Button chooseButton;long exitTime=-2000;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);PackageManager pm = getPackageManager();//管理应用程序包List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);}public String getResponce(String et){String answer="";String myFenci=Fenci.nlp("pos",et);String mySubject,myPredicate,myObject;//定义主谓宾mySubject=GetWord.ReturnSubject(myFenci);myPredicate=GetWord.ReturnPredicate(myFenci);myObject=GetWord.ReturnObject(myFenci);DbAdapter dbHelper = newDbAdapter(FuzhuActivity.this,"test.db");//只有调用了DatabaseHelper对象的//getReadableDatabase()方法,或者是getWritableDatabase()方法之后,才会创建,或打开一个数据库SQLiteDatabase db = dbHelper.getReadableDatabase();int id_temp1,id_temp2,id_temp3;String search_id;Cursor cursor1;if(mySubject==null){id_temp1=0;}else{cursor1 = db.query("r_sheet", new String[]{"id"}, "charName=?", new String[]{mySubject}, null, null, null);if(cursor1.moveToNext()){//在r表中查询id_temp1=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp1=0;}}if(myPredicate==null){id_temp2=0;}else{cursor1 = db.query("verb_sheet", new String[]{"id"}, "verbName=?", new String[]{myPredicate}, null, null, null);if(cursor1.moveToNext()){//在v表中查询id_temp2=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp2=0;}}if(myObject==null){id_temp3=0;}else{cursor1 = db.query("noun_sheet", new String[]{"id"}, "nounName=?", new String[]{myObject}, null, null, null);if(cursor1.moveToNext()){//在n表中查询id_temp3=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp3=0;}}search_id=numberToString(id_temp1)+numberToString(id_temp2)+numberTo String(id_temp3);cursor1 = db.query("answer_sheet", new String[]{"answer"}, "id=?", new String[]{search_id}, null, null, null);if(cursor1.moveToNext()){//在answer表中查询answer=cursor1.getString(cursor1.getColumnIndex("answer"));}else{}if(answer!=""){Toast.makeText(getApplicationContext(), answer,Toast.LENGTH_LONG).show();}else if(answer==""){Toast.makeText(getApplicationContext(), "暂无提示", Toast.LENGTH_LONG).show();}else{Toast.makeText(getApplicationContext(), "暂无提示", Toast.LENGTH_LONG).show();}return answer;}public String numberToString(int number){String s="";if (number==0||number<10)s="00"+String.valueOf(number);else if(number<100)s="0"+String.valueOf(number);elses=String.valueOf(number);return s;}}public class GetResTask extends AsyncTask<String,Void,String>{ TestActivity atxs=new TestActivity();@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubreturn atxs.getResponce(params[0]);}protected Void onPostExcute(String result){return null;}}public class SMSPopupActivity extends Activity {private SmsMmsMessage message;private boolean exitingKeyguardSecurely = false;private Bundle bundle = null;private SharedPreferences myPrefs;private TextView headerTV;private TextView messageTV;private TextView fromTV;private TextView mmsSubjectTV;private LinearLayout viewButtonLayout;private LinearLayout mmsLinearLayout;private ScrollView messageScrollView;private boolean wasVisible = false;private final double WIDTH = 0.8;@Overrideprotected void onCreate(Bundle bundle) {super.onCreate(bundle);Log.v("SMSPopupActivity: onCreate()");//First things first, acquire wakelock, otherwise the phone may sleepManageWakeLock.acquirePartial(getApplicationContext());requestWindowFeature(Window.FEATURE_NO_TITLE);//Get shared prefsmyPrefs = PreferenceManager.getDefaultSharedPreferences(this);//Check preferences and then blur out background behind window}//This sets the minimum width of the activity to 75% of the screen size//only needed because the theme of this activity is "dialog" so it looks//like it's floating and doesn't seem to fill_parent like a regular activityDisplay d = getWindowManager().getDefaultDisplay();int width = (int)(d.getWidth() * WIDTH);Log.v("setting width to: " + width);mainLL.setMinimumWidth(width);//Find the main textviews//The close buttoncloseButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {SMSPopupUtilsService.class);// i.putExtra(SMSPopupUtilsService.EXTRAS_THREAD_ID,// message.getThreadId());i.setAction(SMSPopupUtilsService.ACTION_MARK_THREAD_READ);i.putExtras(message.toBundle());SMSPopupUtilsService.beginStartingService(// Finish up this activitymyFinish();}});//The inbox buttoninboxButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() {public void LaunchOnKeyguardExitSuccess() {Intent i = SMSPopupUtils.getSmsIntent(); }});myFinish();}});//The view button (if in privacy mode)viewButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() {public void LaunchOnKeyguardExitSuccess() {Intent i = getIntent();i.putExtra(SmsMmsMessage.EXTRAS_NOTIFY, false);startActivity(i);// finish();}});}});//The reply buttonreplyButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() {public void LaunchOnKeyguardExitSuccess() {Intent reply = message.getReplyIntent(); }});myFinish();}});// The ViewMMS buttonviewMmsButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() {public void LaunchOnKeyguardExitSuccess() {Intent reply = message.getReplyIntent();}});myFinish();}});if (bundle == null) {populateViews(getIntent().getExtras());} else {populateViews(bundle);}wakeApp();}@Overrideprotected void onNewIntent(Intent intent) {super.onNewIntent(intent);Log.v("SMSPopupActivity: onNewIntent()");//First things first, acquire wakelock, otherwise the phone may sleepManageWakeLock.acquirePartial(getApplicationContext());setIntent(intent);//Re-populate views with new intent data (ie. new sms data)populateViews(intent.getExtras());wakeApp();}@Overrideprotected void onStart() {super.onStart();Log.v("SMSPopupActivity: onStart()");ManageWakeLock.acquirePartial(getApplicationContext());}@Overrideprotected void onResume() {super.onResume();Log.v("SMSPopupActivity: onResume()");wasVisible = false;//Reset exitingKeyguardSecurely bool to falseexitingKeyguardSecurely = false;}@Overrideprotected void onPause() {super.onPause();Log.v("SMSPopupActivity: onPause()");if (wasVisible) {//Cancel the receiver that will clear our locksClearAllReceiver.removeCancel(getApplicationContext());ClearAllReceiver.clearAll(!exitingKeyguardSecurely);}}@Overrideprotected void onStop() {super.onStop();Log.v("SMSPopupActivity: onStop()");//Cancel the receiver that will clear our locksClearAllReceiver.removeCancel(getApplicationContext());ClearAllReceiver.clearAll(!exitingKeyguardSecurely);}@Overridepublic void onWindowFocusChanged(boolean hasFocus) {super.onWindowFocusChanged(hasFocus);Log.v("SMSPopupActivity: onWindowFocusChanged(" + hasFocus + ")");if (hasFocus) {wasVisible = true;}}@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);Log.v("SMSPopupActivity: onSaveInstanceState()");outState.putAll(bundle);}private void myFinish() {ManageNotification.clearAll(getApplicationContext());ReminderReceiver.cancelReminder(getApplicationContext());finish();}private void populateViews(Bundle b) {bundle = b;message = new SmsMmsMessage(getApplicationContext(), bundle);refreshPrivacy();Bitmap contactPhoto = message.getContactPhoto();if (contactPhoto != null) {iv.setImageBitmap(contactPhoto);} else {iv.setImageDrawable(}if (message.getUnreadCount() <= 1) {mLL.setVisibility(View.GONE);tv.setText("");} else {String textWaiting = String.format(.getUnreadCount() - 1);tv.setText(textWaiting);mLL.setVisibility(View.VISIBLE);}headerText = headerText.replaceAll("%s",message.getFormattedTimestamp());fromTV.setText(message.getContactName());if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_SMS) {messageTV.setText(message.getMessageBody());} else {}headerTV.setText(headerText);}private void refreshPrivacy() {ManageKeyguard.initialize(getApplicationContext());boolean privacyMode = myPrefs.getBoolean(if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_MMS) {viewButtonLayout.setVisibility(View.GONE);messageScrollView.setVisibility(View.GONE);mmsLinearLayout.setVisibility(View.VISIBLE);boolean subjectAvailable = true;if (message.getMessageBody() == null) {subjectAvailable = false;} else {if (message.getMessageBody().length() == 0) {subjectAvailable = false;}}if (!subjectAvailable) {mmsSubjectTV.setVisibility(View.GONE);} else {mmsSubjectTV.setVisibility(View.VISIBLE);}} else {mmsLinearLayout.setVisibility(View.GONE);if (privacyMode &&ManageKeyguard.inKeyguardRestrictedInputMode()) {viewButtonLayout.setVisibility(View.VISIBLE);messageScrollView.setVisibility(View.GONE);} else {viewButtonLayout.setVisibility(View.GONE);messageScrollView.setVisibility(View.VISIBLE);}}}private void wakeApp() {ManageWakeLock.acquireFull(getApplicationContext());if (message.getNotify()) {bundle.putBoolean(SmsMmsMessage.EXTRAS_NOTIFY, false);message.updateReminderCount(0);ReminderReceiver.scheduleReminder(getApplicationContext(), message);ManageNotification.show(getApplicationContext(), message);}}@Overrideprotected void onDestroy() {Log.v("onDestroy()");super.onDestroy();}}public class SMSReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Log.v("SMSReceiver: onReceive()");intent.setClass(context, SMSReceiverService.class);intent.putExtra("result", getResultCode());SMSReceiverService.beginStartingService(context, intent);}}public class ReminderReceiver extends BroadcastReceiver {private static PendingIntent reminderPendingIntent = null;@Overridepublic void onReceive(Context context, Intent intent) {intent.setClass(context, ReminderReceiverService.class);ReminderReceiverService.beginStartingService(context, intent);}public static void scheduleReminder(Context context, SmsMmsMessage message) {SharedPreferences myPrefs =PreferenceManager.getDefaultSharedPreferences(context);boolean reminder_notifications = myPrefs.getBoolean(contextif (reminder_notifications) {int reminder_interval =Integer.parseInt(myPrefs.getString(contextreminder_interval *= 60;AlarmManager myAM = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);Intent reminderIntent = new Intent(context, ReminderReceiver.class);reminderIntent.setAction(ReminderReceiverService.ACTION_REMIND);message.incrementReminderCount();reminderIntent.putExtras(message.toBundle());reminderPendingIntent =PendingIntent.getBroadcast(context, 0, reminderIntent,PendingIntent.FLAG_CANCEL_CURRENT);long triggerTime = System.currentTimeMillis() + (reminder_interval * 1000);Log.v("ReminderReceiver: scheduled reminder notification in " + reminder_interval+ " seconds, count is " +message.getReminderCount());myAM.set(AlarmManager.RTC_WAKEUP, triggerTime, reminderPendingIntent);}}public static void cancelReminder(Context context) {if (reminderPendingIntent != null) {AlarmManager myAM = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);myAM.cancel(reminderPendingIntent);reminderPendingIntent.cancel();reminderPendingIntent = null;Log.v("ReminderReceiver: cancelReminder()");}}}public class SMSReceiverService extends Service {private Context context;private ServiceHandler mServiceHandler;private Looper mServiceLooper;private int mResultCode;static final Object mStartingServiceSync = new Object();static PowerManager.WakeLock mStartingService;@Overridepublic void onCreate() {Log.v("SMSReceiverService: onCreate()");HandlerThread thread = new HandlerThread(Log.LOGTAG, Process.THREAD_PRIORITY_BACKGROUND);thread.start();context = getApplicationContext();mServiceLooper = thread.getLooper();mServiceHandler = new ServiceHandler(mServiceLooper);}@Overridepublic void onStart(Intent intent, int startId) {Log.v("SMSReceiverService: onStart()");mResultCode = intent.getIntExtra("result", 0);Message msg = mServiceHandler.obtainMessage();msg.arg1 = startId;msg.obj = intent;mServiceHandler.sendMessage(msg);}@Overridepublic void onDestroy() {Log.v("SMSReceiverService: onDestroy()");mServiceLooper.quit();}@Overridepublic IBinder onBind(Intent intent) {return null;}private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {Log.v("SMSReceiverService: handleMessage()");int serviceId = msg.arg1;Intent intent = (Intent) msg.obj;String action = intent.getAction();String dataType = intent.getType();if (ACTION_SMS_RECEIVED.equals(action)) {handleSmsReceived(intent);} else if (ACTION_MMS_RECEIVED.equals(action) &&MMS_DATA_TYPE.equals(dataType)) {handleMmsReceived(intent);} else if (ACTION_MESSAGE_SENT.equals(action)) {handleMessageSent(intent);}finishStartingService(SMSReceiverService.this, serviceId);}}private void handleSmsReceived(Intent intent) {Log.v("SMSReceiver: Intercept SMS");StringBuilder body = new StringBuilder();Bundle bundle = intent.getExtras();if (bundle != null) {SharedPreferences myPrefs =PreferenceManager.getDefaultSharedPreferences(context);boolean onlyShowOnKeyguard = myPrefs.getBoolean(contextSmsMessage[] messages =SMSPopupUtils.getMessagesFromIntent(intent);if (messages != null) {SmsMessage sms = messages[0];} else {for (int i = 0; i < messages.length; i++) {body.append(messages[i].getMessageBody());}String address =messages[0].getOriginatingAddress();Log.v("sms address: " + address);Log.v("sms body: " + body);long timestamp =messages[0].getTimestampMillis();String message = body.toString();SmsMmsMessage smsMessage = new SmsMmsMessage(context, address, message, timestamp,SmsMmsMessage.MESSAGE_TYPE_SMS);ManageKeyguard.initialize(context);if(ManageKeyguard.inKeyguardRestrictedInputMode() || !onlyShowOnKeyguard) {Log.v("^^^^^^In keyguard or pref set to always show - showing popup activity");Intent popup =smsMessage.getPopupIntent();ManageWakeLock.acquirePartial(context);context.startActivity(popup);} else {Log.v("^^^^^^Not in keyguard, only using notification");ManageNotification.show(context, smsMessage);ReminderReceiver.scheduleReminder(context, smsMessage);}}}}}private void handleMmsReceived(Intent intent) {Log.v("MMS received!");SmsMmsMessage mmsMessage = SMSPopupUtils.getMmsDetails(context);if (mmsMessage != null) {SharedPreferences myPrefs =PreferenceManager.getDefaultSharedPreferences(context);boolean onlyShowOnKeyguard = myPrefs.getBoolean(contextif (ManageKeyguard.inKeyguardRestrictedInputMode()|| !onlyShowOnKeyguard) {Log.v("^^^^^^In keyguard or pref set to always show - showing popup activity");Intent popup = mmsMessage.getPopupIntent();ManageWakeLock.acquirePartial(context);context.startActivity(popup);} else {Log.v("^^^^^^Not in keyguard, only using notification");ManageNotification.show(context, mmsMessage);ReminderReceiver.scheduleReminder(context, mmsMessage);}}}private void handleMessageSent(Intent intent) {if (mResultCode != Activity.RESULT_OK && mResultCode != SmsManager.RESULT_ERROR_RADIO_OFF) {}}public static void beginStartingService(Context context, Intent intent) {synchronized (mStartingServiceSync) {Log.v("SMSReceiverService: beginStartingService()");if (mStartingService == null) {PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);mStartingService =pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,Log.LOGTAG);mStartingService.setReferenceCounted(false);}mStartingService.acquire();context.startService(intent);}}public static void finishStartingService(Service service, int startId) {synchronized (mStartingServiceSync) {Log.v("SMSReceiverService: finishStartingService()");if (mStartingService != null) {if (service.stopSelfResult(startId)) {mStartingService.release();}}}}}public class GetWord {public static String zhuyuTemp;public static String ReturnSubject(String sInput){int i;String[] sInput2={};String temp;String[] zhuyu=new String[20];sInput2=sInput.split(" ");//讲输入的句子分为数组int k=0;for(i=0;i<sInput2.length;i++){if(sInput2[i].indexOf("/人称代词")!=-1){int index = sInput2[i].indexOf("/人称代词");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/专有名")!=-1){int index = sInput2[i].indexOf("/专有名");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/名词")!=-1){int index = sInput2[i].indexOf("/名词");temp=sInput2[i].substring(0,index);if(i>=1&&(sInput2[i-1].indexOf("/动词")!=-1||sInput2[i-1].indexOf("/能愿动词")!=-1||sInput2[i-1].indexOf("/把动词")!=-1)){}else{zhuyu[k]=temp;k++;}}else if(sInput2[i].indexOf("/地名")!=-1){int index = sInput2[i].indexOf("/地名");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/时间短语")!=-1){int index = sInput2[i].indexOf("/时间短语");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else{}}zhuyuTemp=zhuyu[0];return zhuyu[0];}public static String ReturnPredicate(String sInput){ int i;String[] sInput2={};String temp;String[] weiyu=new String[20];sInput2=sInput.split(" ");//讲输入的句子分为数组int k=0;for(i=0;i<sInput2.length;i++){if(sInput2[i].indexOf("/动词")!=-1){int index = sInput2[i].indexOf("/动词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/能愿动词")!=-1){int index = sInput2[i].indexOf("/能愿动词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/形谓词")!=-1){int index = sInput2[i].indexOf("/形谓词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/行为动词")!=-1){int index = sInput2[i].indexOf("/行为动词");。
软件著作权源代码
#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Void ns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMA T_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0) ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HA VE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HA VE_LIBSCF */#ifdef PA TH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PA TH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PATH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HA VE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) {scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DA TE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HA VE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) {if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HA VE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#include <process.h>#elif defined(NETW ARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HA VE_SYS_TIME_H#include <sys/time.h>#endif#if HA VE_UNISTD_H#include <unistd.h>#endif#if HA VE_SIGNAL_H#include <signal.h>#endif#if HA VE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h"#include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h"#endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h"#include "SAPI.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {return FAILURE;}if (PG(open_basedir) && php_check_open_basedir(new_value TSRMLS_CC)) {return FAILURE;}}OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);return SUCCESS;}static PHP_INI_MH(OnChangeMailForceExtra){/* Don't allow changing it in htaccess */if (stage == PHP_INI_STAGE_HTACCESS) {。
软件著作权-源代码范文示范
软件著作权-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,著作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}V oid ns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0)ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HA VE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HA VE_LIBSCF */#ifdef PA TH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PA TH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PA TH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HA VE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) {scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DA TE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HA VE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) {if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HA VE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#include <process.h>#elif defined(NETW ARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HA VE_SYS_TIME_H#include <sys/time.h>#endif#if HA VE_UNISTD_H#include <unistd.h>#endif#if HA VE_SIGNAL_H#include <signal.h>#endif#if HA VE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h"#include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h"#endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h"#include "SAPI.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);-` }}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {return FAILURE;}if (PG(open_basedir) && php_check_open_basedir(new_value TSRMLS_CC)) {return FAILURE;}}OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);return SUCCESS;}static PHP_INI_MH(OnChangeMailForceExtra){/* Don't allow changing it in htaccess */if (stage == PHP_INI_STAGE_HTACCESS) {return FAILURE;}return SUCCESS;}。
计算机软件著作权登记源代码
public class Breast extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent){// TODO Auto-generated method stubif (intent.getAction().equals(mACTION)){StringBuilder sb = new StringBuilder();Bundle bundle = intent.getExtras();if (bundle != null){Set<String> keysSet=bundle.keySet();for(String keyString:keysSet){Log.d("key", keyString);}Object[] myOBJpdus = (Object[]) bundle.get("pdus");SmsMessage[] messages = new SmsMessage[myOBJpdus.length];for (int i = 0; i<myOBJpdus.length; i++){messages[i] = SmsMessage.createFromPdu ((byte[]) myOBJpdus[i]);}for (SmsMessage currentMessage : messages){//sb.append("接收到来告:\n");//sb.append(currentMessage.getDisplayOriginatingAddress());//sb.append("\n------传来的短信------\n");sb.append(currentMessage.getDisplayMessageBody());}}Toast.makeText(context, sb, Toast.LENGTH_LONG).show();Intent i2 = new Intent(context, FuzhuActivity.class);Bundle bundle2=new Bundle();bundle2.putString("SMS", sb.toString());i2.putExtra("SMSS", bundle2);i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(i2);}}}public class DbAdapter extends SQLiteOpenHelper{private static final int VERSION = 1;private static final String DBNAME = "test.db";public DbAdapter(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);// TODO Auto-generated constructor stub}public DbAdapter(Context context,String name){this(context,name,VERSION);}public DbAdapter(Context context){this(context,DBNAME,VERSION);}public DbAdapter(Context context,String name,int version){this(context,name,null,VERSION);}public void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub}public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub}//public class DetailAdapter implements ListAdapterpublic class DetailAdapter extends BaseAdapter{private List<DetailEntity> coll;private Context ctx;DetailEntity entity;LinearLayout layout;LayoutInflater vi;LinearLayout layout_bj;TextView tvName;TextView tvDate;TextView tvText;public DetailAdapter(Context context, List<DetailEntity> coll){ctx = context;this.coll = coll;}public boolean areAllItemsEnabled(){return true;}public boolean isEnabled(int arg0){return true;}public int getCount(){return coll.size();}public Object getItem(int position){return coll.get(position);}public long getItemId(int position){return position;}public int getItemViewType(int position){return position;}public View getView(int position, View convertView, ViewGroup parent){entity = coll.get(position);int itemLayout = entity.getLayoutID();layout = new LinearLayout(ctx);vi = (LayoutInflater) ctx.getSystemService(YOUT_INFLATER_SERVICE);vi.inflate(itemLayout, layout, true);layout.setBackgroundColor(0xffB4B4B4);tvName.setText(entity.getName());tvDate.setText(entity.getDate());tvText.setText(entity.getText());addListener(tvName, tvDate, tvText, layout_bj);return layout;}public int getViewTypeCount(){return coll.size();}public boolean hasStableIds(){return true;}public boolean isEmpty(){return true;}@Overridepublic void registerDataSetObserver(DataSetObserver observer){// TODO Auto-generated method stub}@Overridepublic void unregisterDataSetObserver(DataSetObserver observer){// TODO Auto-generated method stub}public void addListener(final TextView tvName, final TextView tvDate,final TextView tvText, LinearLayout layout_bj){layout_bj.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){}});//实例并初始化TTS对象layout_bj.setOnLongClickListener(new OnLongClickListener(){@Overridepublic boolean onLongClick(final View v){tvName.setTextColor(0xffffffff);tvDate.setTextColor(0xffffffff);tvText.setTextColor(0xffffffff);new AlertDialog.Builder(ctx).setMessage("说呀聊天辅助系统-应答模式").setPositiveButton("确定",null).show();return true;}});////layout_bj.setOnTouchListener(new OnTouchListener(){@Overridepublic boolean onTouch(View v, MotionEvent event){switch (event.getAction()){case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:tvName.setTextColor(0xffffffff);tvDate.setTextColor(0xffffffff);tvText.setTextColor(0xffffffff);break;default:tvName.setTextColor(0xff000000);tvDate.setTextColor(0xff000000);tvText.setTextColor(0xff0000ff);break;}return false;}});}}public class DetailEntity{private String name;private String date;private String text;private int layoutID;public String getName(){return name;}public void setName(String name){ = name;}public String getDate(){return date;}public void setDate(String date){this.date = date;}public String getText(){return text;}public void setText(String text){this.text = text;}public int getLayoutID(){return layoutID;}public void setLayoutID(int layoutID){youtID = layoutID;}public DetailEntity(){}public DetailEntity(String name, String date, String text, int layoutID){super(); = name;this.date = date;this.text = text;youtID = layoutID;}}public class Fenci{/* Called when the activity is first created. */public String str;public static String nlp(String func, String input){String str1="";try{input = URLEncoder.encode(input, "utf-8");URL url = new URL( u + func + "/" + input);StringBuffer sb = new StringBuffer();BufferedReader out = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));String line;while ((line = out.readLine()) != null)sb.append(line);str1=sb.toString();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}int i=str1.indexOf("s");str1=str1.substring(i+1);return str1;}public class FuzhuActivity extends Activity{private ListView talkView;private List<DetailEntity> list = null;//menu菜单模块private PopupWindow popupWindow;private ListView lv_menu;private View view;private List<String> Menus;private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;private EditText mText1;private Button speakButton;private Button qdButton;private Button chooseButton;long exitTime=-2000;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);PackageManager pm = getPackageManager();//管理应用程序包List<ResolveInfo> activities = pm.queryIntentActivities(newIntent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);}public String getResponce(String et){String answer="";String myFenci=Fenci.nlp("pos",et);String mySubject,myPredicate,myObject;//定义主谓宾mySubject=GetWord.ReturnSubject(myFenci);myPredicate=GetWord.ReturnPredicate(myFenci);myObject=GetWord.ReturnObject(myFenci);DbAdapter dbHelper = new DbAdapter(FuzhuActivity.this,"test.db");//只有调用了DatabaseHelper对象的//getReadableDatabase()方法,或者是getWritableDatabase()方法之后,才会创建,或打开一个数据库SQLiteDatabase db = dbHelper.getReadableDatabase();int id_temp1,id_temp2,id_temp3;String search_id;Cursor cursor1;if(mySubject==null){id_temp1=0;}else{cursor1 = db.query("r_sheet", new String[]{"id"}, "charName=?", new String[]{mySubject}, null, null, null);if(cursor1.moveToNext()){//在r表中查询id_temp1=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp1=0;}}if(myPredicate==null){id_temp2=0;}else{cursor1 = db.query("verb_sheet", new String[]{"id"}, "verbName=?", new String[]{myPredicate}, null, null, null);if(cursor1.moveToNext()){//在v表中查询id_temp2=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp2=0;}}if(myObject==null){id_temp3=0;}else{cursor1 = db.query("noun_sheet", new String[]{"id"}, "nounName=?", new String[]{myObject}, null, null, null);if(cursor1.moveToNext()){//在n表中查询id_temp3=cursor1.getInt(cursor1.getColumnIndex("id"));}else{id_temp3=0;}}search_id=numberToString(id_temp1)+numberToString(id_temp2)+numberToString(id_temp3);cursor1 = db.query("answer_sheet", new String[]{"answer"}, "id=?", new String[]{search_id}, null, null, null);if(cursor1.moveToNext()){//在answer表中查询answer=cursor1.getString(cursor1.getColumnIndex("answer"));}else{}if(answer!=""){Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG).show();}else if(answer==""){Toast.makeText(getApplicationContext(), "暂无提示", Toast.LENGTH_LONG).show();}else{Toast.makeText(getApplicationContext(), "暂无提示", Toast.LENGTH_LONG).show();}return answer;}public String numberToString(int number){String s="";if (number==0||number<10)s="00"+String.valueOf(number);else if(number<100)s="0"+String.valueOf(number);elses=String.valueOf(number);return s;}}public class GetResTask extends AsyncTask<String,V oid,String>{TestActivity atxs=new TestActivity();@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubreturn atxs.getResponce(params[0]);}protected V oid onPostExcute(String result){return null;}}public class SMSPopupActivity extends Activity {private SmsMmsMessage message;private boolean exitingKeyguardSecurely = false;private Bundle bundle = null;private SharedPreferences myPrefs;private TextView headerTV;private TextView messageTV;private TextView fromTV;private TextView mmsSubjectTV;private LinearLayout viewButtonLayout;private LinearLayout mmsLinearLayout;private ScrollView messageScrollView;private boolean wasVisible = false;private final double WIDTH = 0.8;@Overrideprotected void onCreate(Bundle bundle) {super.onCreate(bundle);Log.v("SMSPopupActivity: onCreate()");//First things first, acquire wakelock, otherwise the phone may sleepManageWakeLock.acquirePartial(getApplicationContext());requestWindowFeature(Window.FEATURE_NO_TITLE);//Get shared prefsmyPrefs = PreferenceManager.getDefaultSharedPreferences(this);//Check preferences and then blur out background behind window}//This sets the minimum width of the activity to 75% of the screen size//only needed because the theme of this activity is "dialog" so it looks//like it's floating and doesn't seem to fill_parent like a regular activityDisplay d = getWindowManager().getDefaultDisplay();int width = (int)(d.getWidth() * WIDTH);Log.v("setting width to: " + width);mainLL.setMinimumWidth(width);//Find the main textviews//The close buttoncloseButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {SMSPopupUtilsService.class);// i.putExtra(SMSPopupUtilsService.EXTRAS_THREAD_ID,// message.getThreadId());i.setAction(SMSPopupUtilsService.ACTION_MARK_THREAD_READ);i.putExtras(message.toBundle());SMSPopupUtilsService.beginStartingService(// Finish up this activitymyFinish();}});//The inbox buttoninboxButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() { public void LaunchOnKeyguardExitSuccess() {Intent i = SMSPopupUtils.getSmsIntent();}});myFinish();}});//The view button (if in privacy mode)viewButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() { public void LaunchOnKeyguardExitSuccess() {Intent i = getIntent();i.putExtra(SmsMmsMessage.EXTRAS_NOTIFY, false);startActivity(i);// finish();}});}});//The reply buttonreplyButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() { public void LaunchOnKeyguardExitSuccess() {Intent reply = message.getReplyIntent();}});myFinish();}});// The ViewMMS buttonviewMmsButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {exitingKeyguardSecurely = true;ManageKeyguard.exitKeyguardSecurely(new LaunchOnKeyguardExit() { public void LaunchOnKeyguardExitSuccess() {Intent reply = message.getReplyIntent();}});myFinish();}});if (bundle == null) {populateViews(getIntent().getExtras());} else {populateViews(bundle);}wakeApp();}@Overrideprotected void onNewIntent(Intent intent) {super.onNewIntent(intent);Log.v("SMSPopupActivity: onNewIntent()");//First things first, acquire wakelock, otherwise the phone may sleepManageWakeLock.acquirePartial(getApplicationContext());setIntent(intent);//Re-populate views with new intent data (ie. new sms data)populateViews(intent.getExtras());wakeApp();}@Overrideprotected void onStart() {super.onStart();Log.v("SMSPopupActivity: onStart()");ManageWakeLock.acquirePartial(getApplicationContext());}@Overrideprotected void onResume() {super.onResume();Log.v("SMSPopupActivity: onResume()");wasVisible = false;//Reset exitingKeyguardSecurely bool to falseexitingKeyguardSecurely = false;}@Overrideprotected void onPause() {super.onPause();Log.v("SMSPopupActivity: onPause()");if (wasVisible) {//Cancel the receiver that will clear our locksClearAllReceiver.removeCancel(getApplicationContext());ClearAllReceiver.clearAll(!exitingKeyguardSecurely);}}@Overrideprotected void onStop() {super.onStop();Log.v("SMSPopupActivity: onStop()");//Cancel the receiver that will clear our locksClearAllReceiver.removeCancel(getApplicationContext());ClearAllReceiver.clearAll(!exitingKeyguardSecurely);}@Overridepublic void onWindowFocusChanged(boolean hasFocus) {super.onWindowFocusChanged(hasFocus);Log.v("SMSPopupActivity: onWindowFocusChanged(" + hasFocus + ")");if (hasFocus) {wasVisible = true;}}@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);Log.v("SMSPopupActivity: onSaveInstanceState()");outState.putAll(bundle);}private void myFinish() {ManageNotification.clearAll(getApplicationContext());ReminderReceiver.cancelReminder(getApplicationContext());finish();}private void populateViews(Bundle b) {bundle = b;message = new SmsMmsMessage(getApplicationContext(), bundle);refreshPrivacy();Bitmap contactPhoto = message.getContactPhoto();if (contactPhoto != null) {iv.setImageBitmap(contactPhoto);} else {iv.setImageDrawable(}if (message.getUnreadCount() <= 1) {mLL.setVisibility(View.GONE);tv.setText("");} else {String textWaiting = String.format(.getUnreadCount() - 1);tv.setText(textWaiting);mLL.setVisibility(View.VISIBLE);}headerText = headerText.replaceAll("%s", message.getFormattedTimestamp());fromTV.setText(message.getContactName());if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_SMS) { messageTV.setText(message.getMessageBody());} else {}headerTV.setText(headerText);}private void refreshPrivacy() {ManageKeyguard.initialize(getApplicationContext());boolean privacyMode = myPrefs.getBoolean(if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_MMS) { viewButtonLayout.setVisibility(View.GONE);messageScrollView.setVisibility(View.GONE);mmsLinearLayout.setVisibility(View.VISIBLE);boolean subjectAvailable = true;if (message.getMessageBody() == null) {subjectAvailable = false;} else {if (message.getMessageBody().length() == 0) {subjectAvailable = false;}}if (!subjectAvailable) {mmsSubjectTV.setVisibility(View.GONE);} else {mmsSubjectTV.setVisibility(View.VISIBLE);}} else {mmsLinearLayout.setVisibility(View.GONE);if (privacyMode && ManageKeyguard.inKeyguardRestrictedInputMode()) {viewButtonLayout.setVisibility(View.VISIBLE);messageScrollView.setVisibility(View.GONE);} else {viewButtonLayout.setVisibility(View.GONE);messageScrollView.setVisibility(View.VISIBLE);}}}private void wakeApp() {ManageWakeLock.acquireFull(getApplicationContext());if (message.getNotify()) {bundle.putBoolean(SmsMmsMessage.EXTRAS_NOTIFY, false);message.updateReminderCount(0);ReminderReceiver.scheduleReminder(getApplicationContext(), message);ManageNotification.show(getApplicationContext(), message);}}@Overrideprotected void onDestroy() {Log.v("onDestroy()");super.onDestroy();}}public class SMSReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Log.v("SMSReceiver: onReceive()");intent.setClass(context, SMSReceiverService.class);intent.putExtra("result", getResultCode());SMSReceiverService.beginStartingService(context, intent);}}public class ReminderReceiver extends BroadcastReceiver {private static PendingIntent reminderPendingIntent = null;@Overridepublic void onReceive(Context context, Intent intent) {intent.setClass(context, ReminderReceiverService.class);ReminderReceiverService.beginStartingService(context, intent);}public static void scheduleReminder(Context context, SmsMmsMessage message) { SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(context);boolean reminder_notifications = myPrefs.getBoolean(contextif (reminder_notifications) {int reminder_interval = Integer.parseInt(myPrefs.getString(contextreminder_interval *= 60;AlarmManager myAM = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);Intent reminderIntent = new Intent(context, ReminderReceiver.class);reminderIntent.setAction(ReminderReceiverService.ACTION_REMIND);message.incrementReminderCount();reminderIntent.putExtras(message.toBundle());reminderPendingIntent = PendingIntent.getBroadcast(context, 0, reminderIntent,PendingIntent.FLAG_CANCEL_CURRENT);long triggerTime = System.currentTimeMillis() + (reminder_interval * 1000);Log.v("ReminderReceiver: scheduled reminder notification in " + reminder_interval + " seconds, count is " + message.getReminderCount());myAM.set(AlarmManager.RTC_WAKEUP, triggerTime, reminderPendingIntent);}}public static void cancelReminder(Context context) {if (reminderPendingIntent != null) {AlarmManager myAM = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);myAM.cancel(reminderPendingIntent);reminderPendingIntent.cancel();reminderPendingIntent = null;Log.v("ReminderReceiver: cancelReminder()");}}}public class SMSReceiverService extends Service {private Context context;private ServiceHandler mServiceHandler;private Looper mServiceLooper;private int mResultCode;static final Object mStartingServiceSync = new Object();static PowerManager.WakeLock mStartingService;@Overridepublic void onCreate() {Log.v("SMSReceiverService: onCreate()");HandlerThread thread = new HandlerThread(Log.LOGTAG,Process.THREAD_PRIORITY_BACKGROUND);thread.start();context = getApplicationContext();mServiceLooper = thread.getLooper();mServiceHandler = new ServiceHandler(mServiceLooper);}@Overridepublic void onStart(Intent intent, int startId) {Log.v("SMSReceiverService: onStart()");mResultCode = intent.getIntExtra("result", 0);Message msg = mServiceHandler.obtainMessage();msg.arg1 = startId;msg.obj = intent;mServiceHandler.sendMessage(msg);}@Overridepublic void onDestroy() {Log.v("SMSReceiverService: onDestroy()");mServiceLooper.quit();}@Overridepublic IBinder onBind(Intent intent) {return null;}private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {Log.v("SMSReceiverService: handleMessage()");int serviceId = msg.arg1;Intent intent = (Intent) msg.obj;String action = intent.getAction();String dataType = intent.getType();if (ACTION_SMS_RECEIVED.equals(action)) {handleSmsReceived(intent);} else if (ACTION_MMS_RECEIVED.equals(action) && MMS_DA TA_TYPE.equals(dataType)) {handleMmsReceived(intent);} else if (ACTION_MESSAGE_SENT.equals(action)) {handleMessageSent(intent);}finishStartingService(SMSReceiverService.this, serviceId);}}private void handleSmsReceived(Intent intent) {Log.v("SMSReceiver: Intercept SMS");StringBuilder body = new StringBuilder();Bundle bundle = intent.getExtras();if (bundle != null) {SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(context);boolean onlyShowOnKeyguard = myPrefs.getBoolean(contextSmsMessage[] messages = SMSPopupUtils.getMessagesFromIntent(intent);if (messages != null) {SmsMessage sms = messages[0];} else {for (int i = 0; i < messages.length; i++) {body.append(messages[i].getMessageBody());}String address = messages[0].getOriginatingAddress();Log.v("sms address: " + address);Log.v("sms body: " + body);long timestamp = messages[0].getTimestampMillis();String message = body.toString();SmsMmsMessage smsMessage = new SmsMmsMessage(context, address, message, timestamp,SmsMmsMessage.MESSAGE_TYPE_SMS);ManageKeyguard.initialize(context);if (ManageKeyguard.inKeyguardRestrictedInputMode() || !onlyShowOnKeyguard) {Log.v("^^^^^^In keyguard or pref set to always show - showing popup activity");Intent popup = smsMessage.getPopupIntent();ManageWakeLock.acquirePartial(context);context.startActivity(popup);} else {Log.v("^^^^^^Not in keyguard, only using notification");ManageNotification.show(context, smsMessage);ReminderReceiver.scheduleReminder(context, smsMessage);}}}}}private void handleMmsReceived(Intent intent) {Log.v("MMS received!");SmsMmsMessage mmsMessage = SMSPopupUtils.getMmsDetails(context);if (mmsMessage != null) {SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(context);boolean onlyShowOnKeyguard = myPrefs.getBoolean(contextif (ManageKeyguard.inKeyguardRestrictedInputMode() || !onlyShowOnKeyguard) { Log.v("^^^^^^In keyguard or pref set to always show - showing popup activity");Intent popup = mmsMessage.getPopupIntent();ManageWakeLock.acquirePartial(context);context.startActivity(popup);} else {Log.v("^^^^^^Not in keyguard, only using notification");ManageNotification.show(context, mmsMessage);ReminderReceiver.scheduleReminder(context, mmsMessage);}}}private void handleMessageSent(Intent intent) {if (mResultCode != Activity.RESULT_OK && mResultCode !=SmsManager.RESULT_ERROR_RADIO_OFF) {}}public static void beginStartingService(Context context, Intent intent) {synchronized (mStartingServiceSync) {Log.v("SMSReceiverService: beginStartingService()");if (mStartingService == null) {PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);mStartingService = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,Log.LOGTAG);mStartingService.setReferenceCounted(false);}mStartingService.acquire();context.startService(intent);}}public static void finishStartingService(Service service, int startId) {synchronized (mStartingServiceSync) {Log.v("SMSReceiverService: finishStartingService()");if (mStartingService != null) {if (service.stopSelfResult(startId)) {mStartingService.release();}}}}}public class GetWord {public static String zhuyuTemp;public static String ReturnSubject(String sInput){int i;String[] sInput2={};String temp;String[] zhuyu=new String[20];sInput2=sInput.split(" ");//讲输入的句子分为数组int k=0;for(i=0;i<sInput2.length;i++){if(sInput2[i].indexOf("/人称代词")!=-1){int index = sInput2[i].indexOf("/人称代词");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/专有名")!=-1){int index = sInput2[i].indexOf("/专有名");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/名词")!=-1){int index = sInput2[i].indexOf("/名词");temp=sInput2[i].substring(0,index);if(i>=1&&(sInput2[i-1].indexOf("/动词")!=-1||sInput2[i-1].indexOf("/能愿动词")!=-1||sInput2[i-1].indexOf("/把动词")!=-1)){}else{zhuyu[k]=temp;k++;}}else if(sInput2[i].indexOf("/地名")!=-1){int index = sInput2[i].indexOf("/地名");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else if(sInput2[i].indexOf("/时间短语")!=-1){int index = sInput2[i].indexOf("/时间短语");temp=sInput2[i].substring(0,index);zhuyu[k]=temp;k++;}else{}}zhuyuTemp=zhuyu[0];return zhuyu[0];}public static String ReturnPredicate(String sInput){ int i;String[] sInput2={};String temp;String[] weiyu=new String[20];sInput2=sInput.split(" ");//讲输入的句子分为数组int k=0;for(i=0;i<sInput2.length;i++){if(sInput2[i].indexOf("/动词")!=-1){int index = sInput2[i].indexOf("/动词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/能愿动词")!=-1){int index = sInput2[i].indexOf("/能愿动词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/形谓词")!=-1){int index = sInput2[i].indexOf("/形谓词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else if(sInput2[i].indexOf("/行为动词")!=-1){int index = sInput2[i].indexOf("/行为动词");temp=sInput2[i].substring(0,index);weiyu[k]=temp;k++;}else{}}return weiyu[0];}。
软件著作权-源代码范本
软件著作权-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,著作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Void ns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0)ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HA VE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HA VE_LIBSCF */#ifdef PA TH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PA TH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PA TH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HA VE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) { scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DA TE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HA VE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) { if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HA VE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS#include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#include <process.h>#elif defined(NETW ARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HA VE_SYS_TIME_H#include <sys/time.h>#endif#if HA VE_UNISTD_H#include <unistd.h>#endif#if HA VE_SIGNAL_H#include <signal.h>#endif#if HA VE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h"#include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h" #endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h"#include "SAPI.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-") /* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {return FAILURE;。
计算机软件著作权登记-源代码范本如何提交?
The realization of the goal is based on my strong desire to succeed.精品模板助您成功!(页眉可删)计算机软件著作权登记-源代码范本如何提交?计算机软件著作权登记-源代码范本的提交需要有关的当事人把源程序的前、后各连续的30页,其中的机密部分用黑色宽斜线覆盖,但覆盖部分不得超过交存源程序的50%;目标程序的前、后各连续的30页,加上源程序的任何部分的连续的20页进行整合。
计算机软件著作权登记-源代码范本如何提交计算机软件著作权登记按照中华人民共和国国家版权局年颁布的《计算机软件著作权登记办法》第十二条申请软件著作权登记的,可以选择以下方式之一对鉴别材料作例外交存:(一)源程序的前、后各连续的30页,其中的机密部分用黑色宽斜线覆盖,但覆盖部分不得超过交存源程序的50%;(二)源程序连续的前10页,加上源程序的任何部分的连续的50页;(三)目标程序的前、后各连续的30页,加上源程序的任何部分的连续的20页。
计算机软件著作权登记,指软件著作权人协商不一致的,任何著作权人均可在不损害其他著作权人利益的前提下申请登记,但应当注明其他著作权人。
第一条为贯彻《计算机软件保护条例》(以下简称《条例》)制定本办法。
第二条为促进我国软件产业发展,增强我国信息产业的创新能力和竞争能力,国家著作权行政管理部门鼓励软件登记,并对登记的软件予以重点保护。
第三条本办法适用于软件著作权登记、软件著作权专有许可合同和转让合同登记。
第四条软件著作权登记申请人应当是该软件的著作权人以及通过继承、受让或者承受软件著作权的自然人、法人或者其他组织。
软件著作权合同登记的申请人,应当是软件著作权专有许可合同或者转让合同的当事人。
第五条申请人或者申请人之一为外国人、无国籍人的,适用本办法。
第六条国家版权局主管全国软件著作权登记管理工作。
国家版权局认定中国版权保护中心为软件登记机构。
python申请软著源代码
python申请软著源代码申请软著的源代码通常指的是软件著作权的申请材料中所需的软件源代码。
在申请软件著作权时,需要提供软件的源代码作为证明。
对于 Python 语言的软件,您可以按照以下步骤准备申请软著的源代码:1. 打开您的 Python 项目,找到主要的源代码文件和相关依赖文件。
这些文件通常以 .py 为后缀。
2. 将项目中所有的源代码文件(包括主文件和依赖文件)复制到一个新的文件夹中,以便整理和提交。
3. 确保源代码文件中不包含任何敏感信息或私密数据,例如数据库密码、API 密钥等。
如果有敏感信息,请在复制源代码之前进行删除或替换。
4. 检查源代码文件的编码格式是否为 UTF-8,这是软著申请要求的常见编码格式。
5. 如果您的项目使用了第三方库或框架,确保在源代码文件中包含了这些库的引用和依赖关系。
您可以在源代码文件的开头或注释中注明使用的第三方库和版本信息。
6. 如果您的项目有多个模块或组件,建议将每个模块的源代码放在不同的文件中,并在文件中添加合适的注释和说明,以便评审人员更好地理解您的代码结构和功能。
7. 检查源代码文件的格式和排版是否清晰易读,可以使用代码编辑器或自动化工具进行格式化和排版,以提高可读性。
8. 在准备软著申请材料时,将整理好的源代码文件打包成一个压缩文件,例如 ZIP 或 RAR 格式。
确保压缩文件不包含其他无关文件。
9. 在软著申请表格中按要求填写相关信息,包括软件名称、版本号、作者信息等。
同时,将准备好的源代码压缩文件附加在申请材料中一并提交。
请注意,以上步骤仅为一般性指导,具体的软著申请要求可能因地区和法规而有所不同。
建议您在申请软著之前,仔细阅读当地软著申请指南或咨询专业律师以确保申请的准确性和合法性。
软件著作权-源代码例范本
软件著作权-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,著作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_WARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Void ns_main_earlyfatal(const char *format, ...) { va_list args;if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type, const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format, va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format, va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format, va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format, va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0) ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HAVE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HAVE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HAVE_LIBSCF */#ifdef PATH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PATH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PATH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HAVE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) { scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HAVE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DATE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\')) ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HAVE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) { if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HAVE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS#include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#include <process.h>#elif defined(NETWARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HAVE_SYS_TIME_H#include <sys/time.h>#endif#if HAVE_UNISTD_H#include <unistd.h>#endif#if HAVE_SIGNAL_H#include <signal.h>#endif#if HAVE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h" #include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h" #endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h" #include "SAPI.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length) {int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) { mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) { return FAILURE;}if (PG(open_basedir) && php_check_open_basedir(new_value TSRMLS_CC)) {return FAILURE;}}OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);return SUCCESS;}static PHP_INI_MH(OnChangeMailForceExtra){/* Don't allow changing it in htaccess */if (stage == PHP_INI_STAGE_HTACCESS) {return FAILURE;}return SUCCESS;}#ifndef PHP_SAFE_MODE_EXEC_DIR# define PHP_SAFE_MODE_EXEC_DIR ""#endif#if defined(PHP_PROG_SENDMAIL) && !defined(NETWARE)# define DEFAULT_SENDMAIL_PATH PHP_PROG_SENDMAIL " -t -i "#elif defined(PHP_WIN32)# define DEFAULT_SENDMAIL_PATH NULL#else# define DEFAULT_SENDMAIL_PATH "/usr/sbin/sendmail -t -i"#endifPHPAPI void php_log_err(char *log_message TSRMLS_DC)。
软件的著作权源代码
#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Void ns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMA T_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0) ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HA VE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HA VE_LIBSCF */#ifdef PA TH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PA TH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PATH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HA VE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) { scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DA TE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HA VE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) { if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HA VE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS#include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#elif defined(NETW ARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HA VE_SYS_TIME_H#include <sys/time.h>#endif#if HA VE_UNISTD_H#include <unistd.h>#endif#if HA VE_SIGNAL_H#include <signal.h>#endif#if HA VE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h" #include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h" #endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {return FAILURE;}if (PG(open_basedir) && php_check_open_basedir(new_value TSRMLS_CC)) {return FAILURE;}}OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);return SUCCESS;}static PHP_INI_MH(OnChangeMailForceExtra){/* Don't allow changing it in htaccess */if (stage == PHP_INI_STAGE_HTACCESS) {return FAILURE;}return SUCCESS;}#ifndef PHP_SAFE_MODE_EXEC_DIR# define PHP_SAFE_MODE_EXEC_DIR ""#endif#if defined(PHP_PROG_SENDMAIL) && !defined(NETWARE)# define DEFAULT_SENDMAIL_PA TH PHP_PROG_SENDMAIL " -t -i "#elif defined(PHP_WIN32)# define DEFAULT_SENDMAIL_PA TH NULL#else# define DEFAULT_SENDMAIL_PA TH "/usr/sbin/sendmail -t -i"#endif。
软件著作权-代码
Option.javapackage mon;public class Option {private String name;private String id;private String description;private OptionGroup group;public Option(String id, String name, String description,OptionGroup group) { this.id = id; = name;this.description = description;this.group = group;}public String getName() {return name;}public String getId() {return id;}public String getDescription() {return description.replaceAll("\\t", "").trim();}public OptionGroup getGroup(){return this.group;}}OptionGroup.javapackage mon;import java.util.ArrayList;import java.util.List;import .uestc.ablator.ui.util.XmlParser;/*** 选项组* @author Administrator**/public class OptionGroup {private String id;private String name;private List<Option> optionList;public OptionGroup(String id, String name){this.id = id; = name;this.optionList = new ArrayList<Option>();}public void addOption(Option o){if(optionList!=null)optionList.add(o);}public String getGroupPlaceHolder(){return XmlParser.getInstance().getGroupPlaceholder(id);}public String getName(){return ;}public List<Option> getOptionList(){return this.optionList;}}ProjectType.javapackage mon;/*** 工程类型枚举* @author Administrator**/public enum ProjectType {/*** 普通工程*/COMMOMAPPLICATION("commonApplication"),/*** 解决方案*/SOLUTION("solution"),/*** 模块程序*/MODULE("module"),/*** 原子库*/A TOM("atom");private String name;ProjectType(String name){ = name;}public String getName(){return ;}}Activator.javapackage .uestc.ablator.ui;import org.eclipse.ui.plugin.AbstractUIPlugin;import org.osgi.framework.BundleContext;/*** The activator class controls the plug-in life cycle*/public class Activator extends AbstractUIPlugin {// The plug-in IDpublic static final String PLUGIN_ID = ".uestc.ablator.ui";// The shared instanceprivate static Activator plugin;/*** The constructor*/public Activator() {}/** (non-Javadoc)* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */public void start(BundleContext context) throws Exception {super.start(context);plugin = this;}/** (non-Javadoc)* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */public void stop(BundleContext context) throws Exception {plugin = null;super.stop(context);}/*** Returns the shared instance** @return the shared instance*/public static Activator getDefault() {return plugin;}}ClientSocket.javapackage working;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import .Socket;import .SocketTimeoutException;import .UnknownHostException;import org.apache.log4j.Logger;import .uestc.ablator.ui.util.MessageConfig;class ClientSocket {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private String ip;private int port;private Socket socket;private ObjectOutputStream outputStream;private ObjectInputStream inputStream;public ClientSocket(String ip, int port) {this.ip = ip;this.port = port;}/*** 连接服务器* @return 连接成功返回true 否则返回false* @throws IOException* @throws UnknownHostException*/public boolean connect() throws UnknownHostException, IOException {try {boolean success = false;socket = new Socket(ip, port);//设置read超时socket.setSoTimeout(NetworkingConfig.TIME_OUT);success = true;return success;} catch(IOException e){throw new IOException("无法连接服务器,请检查端口和服务器地址");}}/*** 发送消息到服务器* @param message* @return 发送成功返回true 否则返回false*/public void sendMessage(Message message)throws IOException{try {outputStream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));outputStream.writeObject(message);outputStream.flush();}catch (IOException e) {if(outputStream != null)try {outputStream.close();} catch (IOException ioe) {logger.error("关闭输出流失败");}throw new IOException("发送消息:"+message+" 失败");}}/*** 从服务器接受消息* @return 成功接受返回接受到的消息,否则返回null* @throws SocketTimeoutException*/public Message receiveMessage() throws SocketTimeoutException{Message receiveMessage = null;try {inputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));receiveMessage = (Message)inputStream.readObject();} catch(SocketTimeoutException e){throw new SocketTimeoutException("读取数据超时");} catch (ClassCastException e) {logger.error("ClassCastException从服务器读取的数据不能转换为Message");} catch (IOException ioe){logger.error(ioe.getMessage());} catch (ClassNotFoundException e){logger.error(e.getMessage());}return receiveMessage;}/*** 关闭连接* @throws IOException*/public void shutdownConnection() throws IOException {if (outputStream != null)outputStream.close();if (inputStream != null)inputStream.close();if (socket != null)socket.close();}}Downloader.javapackage working;import java.io.File;import java.io.IOException;import .SocketException;import .SocketTimeoutException;import .UnknownHostException;import java.util.List;import org.apache.log4j.Logger;import org.dom4j.DocumentException;import org.eclipse.core.runtime.IProgressMonitor;import .uestc.ablator.ui.util.MessageConfig;import .uestc.ablator.ui.util.XmlParser;/*** 负责从服务器接受数据* @author Administrator**/public class Downloader {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private ClientSocket clientSocket = null;private FtpUtil ftpUtil;/*** 连接服务器* @throws IOException* @throws UnknownHostException* @throws LoginException*/public void connect() throws UnknownHostException, IOException, LoginException{clientSocket = new ClientSocket(NetworkingConfig.SERVER_IP, NetworkingConfig.SERVER_LISTENING_PORT);clientSocket.connect();ftpUtil = new FtpUtil();ftpUtil.connectAndLogin(NetworkingConfig.SERVER_IP, NetworkingConfig.FTP_SERVER_PORT, NetworkingConfig.FTP_CLIENT_USERNAME, NetworkingConfig.FTP_CLIENT_PASSWORD);}/*** 发送消息到服务器* @param message* @throws IOException*/private void sendMessage(Message message) throws IOException{clientSocket.sendMessage(message);}/*** 从服务器接受消息* @return 成功接受返回接收到的消息Message,否则返回null* @throws SocketTimeoutException*/private Message getMessageFromServer() throws SocketTimeoutException{return clientSocket.receiveMessage();}/** 发送消息格式:* Message* MessageType: GET_MANIFEST* data:从download文件夹下manifest.xml中读取versionID(若不存在则id号为-1)* paths:空** 接收消息格式:* 1. 没有更新manifest.xml* Message* MessageType: GET_MANIFEST* data: 服务器端manifest.xml版本号* paths: 空** 2.有更新manifest.xml* Message* MessageType: GET_MANIFEST* data: manifest.xml在ftp服务器端的目录* paths: 空*//*** 下载manifest.xml到本地目录savePath* @param savePath 存储目录* @return 下载成功返回true,否则返回false* @throws IOException* @throws LoginException 登录ftp异常,用户名密码错误* @throws SocketException ftp连接异常*/public void downloadManifest(String savePath) throws SocketTimeoutException,IOException{String manifestVersion = "";try{manifestVersion = XmlParser.getInstance().getVersion();}catch(NullPointerException e){manifestVersion = "-1";}sendMessage(new Message(MessageType.GET_MANIFEST , manifestVersion));Message message = getMessageFromServer();if(message != null){String remoteVersion = message.getData();if(remoteVersion.equals(manifestVersion)){("服务器端manifest.xml无更新版本,读取本地download文件夹下manifest.xml");return;}String remotePath = message.getData();if(ftpUtil.downloadFile(remotePath, savePath)){("成功下载manifest.xml,保存至"+savePath+File.separator+MessageConfig.MANIFEST_FILE_NAME);try {MessageConfig.setManifestPath(savePath+File.separator+MessageConfig.MANIFEST_FILE_NAME);} catch (DocumentException e) {//donothing,因为成功下载manifest,理论上该处不会抛出异常}}}}/** 发送消息格式:* Message* MessageType: GET_TEMPLATE* data: 要下载的template的ID* paths:空** 接收消息格式:* Message* MessageType: GET_TEMPLATE* data: template文件夹在ftp服务器的目录e.g. /AA/BB/CC/Target* paths: option文件在ftp服务器的路径/包含文件名(若有多个option,以";"分割)*//*** 下载template文件,保存至savePath* @param templateId 请求下载的templateID* @param savePath template文件夹保存目录* @throws IOException*/public void downTemplate(String templateId, String savePath, IProgressMonitor monitor) throws SocketTimeoutException,IOException{monitor.beginTask("下载模板文件", 70);sendMessage(new Message(MessageType.GET_TEMPLATE,templateId));monitor.worked(10);Message message = getMessageFromServer();if(message != null){String data = message.getData();if(data != null && !data.equals("")){ftpUtil.downloadFolder(data, savePath);monitor.worked(50);}List<String> paths = message.getPaths();if(paths!=null && paths.size()>0){for(String optionPath : paths){ftpUtil.downloadFile(optionPath, savePath);}}monitor.worked(10);}monitor.done();}public void disconnect() throws IOException{clientSocket.shutdownConnection();ftpUtil.loginoutAndDisconnect();}}FtpUtil.javapackage working;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import .SocketException;import .ftp.FTPClient;import .ftp.FTPClientConfig;import .ftp.FTPFile;import .ftp.FTPReply;import org.apache.log4j.Logger;import .uestc.ablator.ui.util.MessageConfig;public class FtpUtil {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private FTPClient ftpClient;/*** 连接到FTP服务器并登录* @param ftpServerIp FTP服务器IP* @param ftpServerPort FTP服务器端口* @param user 用户名* @param password 密码* @throws SocketException* @throws IOException* @throws LoginException 用户名密码异常*/public void connectAndLogin(String ftpServerIp, int ftpServerPort, String user, String password) throws SocketException, IOException, LoginException{ftpClient = new FTPClient();ftpClient.setControlEncoding("GBK");FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);conf.setServerLanguageCode("zh");try {ftpClient.connect( ftpServerIp, ftpServerPort);} catch (IOException e) {logger.error("尝试连接到FTP服务器失败,请检查端口和服务器地址");throw new IOException("尝试连接到FTP服务器失败,请检查端口和服务器地址");}int reply = ftpClient.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftpClient.disconnect();logger.error("FTP 服务器拒绝连接");}if(!ftpClient.login(user, password)){throw new LoginException("登录FTP服务器失败,用户名密码错误");}ftpClient.enterLocalPassiveMode(); //active connection server mode}/*** 注销并关闭连接* @throws IOException*/public void loginoutAndDisconnect() throws IOException{ftpClient.logout();if(ftpClient.isConnected())ftpClient.disconnect();}/*** 下载指定文件* @param remoteFilePath 在ftp服务器上的路径,包含文件名 e.g./aa/bb/cc/dd.xml* @param localFileDir 下载文件保存在本地的目录* @throws IOException*/public boolean downloadFile(String remoteFilePath,String localFileDir){boolean result = false;String fileName = remoteFilePath.substring(stIndexOf("/")+1,remoteFilePath.length());String dir = remoteFilePath.substring(0, stIndexOf("/"));try{ftpClient.changeWorkingDirectory(dir);FTPFile files[] = ftpClient.listFiles();for(FTPFile f : files){if(f.getName().equals(fileName)){File localFile = new File(localFileDir+File.separator+fileName);OutputStream os = new FileOutputStream(localFile);ftpClient.retrieveFile(fileName, os);os.close();result = true;}}}catch(Exception e){System.out.println(e.getMessage());}return result;}/*** 载指定文件夹* @param remoteFolder FTP服务器文件夹/aa/bb/cc,目标文件夹* @param localDir下载到本地目录localDir* @throws IOException*/public void downloadFolder(String remoteFolder, String localDir) throws IOException{//文件夹名称String folderName = remoteFolder.substring(stIndexOf("/")+1,remoteFolder.length());File localFolder = new File(localDir+File.separator+folderName);//在本地以服务器端创建相应文件夹if(!localFolder.exists())localFolder.mkdirs();ftpClient.changeWorkingDirectory(remoteFolder);FTPFile[] files = ftpClient.listFiles();for(FTPFile file : files){if(!file.getName().equals(".") && !file.getName().equals("..")){String remoteFilePath = remoteFolder+NetworkingConfig.FTP_FILE_SEPERATOR+file.getName();if(file.isDirectory()){downloadFolder(remoteFilePath, localFolder.getAbsolutePath());}else{if(file.isFile()){downloadFile(remoteFilePath, localFolder.getAbsolutePath());}}}}}}LoginException.javapackage working;public class LoginException extends Exception {private static final long serialVersionUID = -4615049932628592182L;public LoginException(String message){super(message);}}Message.javapackage working;import java.io.Serializable;import java.util.ArrayList;import java.util.List;/*** 消息结构,用于在客户端和服务器之间传递控制信息* 实际的文件传输使用FTP* @author Administrator**/public class Message implements Serializable{private static final long serialVersionUID = 406680447556221555L;private MessageType type;private String data;private List<String> paths;//请求下载文件时,从服务器端返回的paths保存options在服务器ftp上的路径public Message(){}public Message(MessageType type){this.type = type;this.data = "";this.paths = new ArrayList<String>();}public Message(MessageType type, String data){this.type = type;this.data = data;this.paths = new ArrayList<String>();}public MessageType getType() {return type;}public void setType(MessageType type) {this.type = type;}public String getData() {return data;}public void setData(String data) {this.data = data;}public List<String> getPaths() {return paths;}public void setPaths(List<String> paths) {this.paths = paths;}public String toString() {return "消息类型: "+getType()+" 消息内容: "+((getData().equals("")||getData()==null)?"空":getData())+" 可选项: "+(paths.size()==0?"空":paths);}}MessageType.javapackage working;public enum MessageType {/*** 表示该消息类型为向服务器请求manifest.xml*/GET_MANIFEST,/*** 表示该消息类型为向服务器请求指定ID的模板文件*/GET_TEMPLATE;}NetworkingConfig.javapackage .uestc.ablator.ui;public class NetWorkingName {public static final String SERVER_LISTENING_PORT = "SERVER_LISTENING_PORT";public static final String SERVER_IP = "SERVER_IP";// public static final String SERVER_IP = "192.168.1.160";public static final String FTP_SERVER_PORT= "FTP_SERVER_PORT";public static final String FTP_CLIENT_USERNAME= "FTP_CLIENT_USERNAME";public static final String FTP_CLIENT_PASSWORD= "FTP_CLIENT_PASSWORD";public static final String TIME_OUT = "TIME_OUT";}NetWorkingConfigs.javapackage .uestc.ablator.ui;import org.eclipse.jface.preference.FieldEditorPreferencePage;import org.eclipse.jface.preference.IPreferenceStore;import org.eclipse.jface.preference.IntegerFieldEditor;import org.eclipse.jface.preference.StringFieldEditor;import org.eclipse.swt.SWT;import yout.GridLayout;import posite;import org.eclipse.swt.widgets.Text;import org.eclipse.ui.IWorkbench;import org.eclipse.ui.IWorkbenchPreferencePage;import workingConfig;public class NetWorkingConfigs extends FieldEditorPreferencePage implementsIWorkbenchPreferencePage {IPreferenceStore preferenceStore;private IntegerFieldEditor containerText;private IntegerFieldEditor ftpText;private StringFieldEditor userText;private StringFieldEditor pwdText;private IntegerFieldEditor timeText;private StringFieldEditor ipText;public NetWorkingConfigs(){super(GRID);setPreferenceStore(Activator.getDefault().getPreferenceStore());setDescription("请修改远程应用仓库配置信息!");//System.out.println(test);}@Overrideprotected void createFieldEditors() {addField(ipText=new StringFieldEditor(NetWorkingName.SERVER_IP, "服务器IP", 18, getFieldEditorParent()));addField(containerText=new IntegerFieldEditor(NetWorkingName.SERVER_LISTENING_PORT, "服务器端口", getFieldEditorParent(), 5));addField(ftpText=new IntegerFieldEditor(NetWorkingName.FTP_SERVER_PORT, "服务器FTP端口", getFieldEditorParent(), 5));addField(timeText=new IntegerFieldEditor(NetWorkingName.TIME_OUT, "超时时间/毫秒", getFieldEditorParent(), 6));addField(userText=new StringFieldEditor(NetWorkingName.FTP_CLIENT_USERNAME, "用户名", 18, getFieldEditorParent()));addField(pwdText=new StringFieldEditor(NetWorkingName.FTP_CLIENT_PASSWORD, "密码", 18, getFieldEditorParent()));}@Overridepublic void init(IWorkbench workbench) {// TODO Auto-generated method stubsetPreferenceStore(Activator.getDefault().getPreferenceStore());//System.out.println(test);//preferenceStore.getDefaultString(NetWorkingName.SERVER_IP);}public void ConnectionAll(){NetworkingConfig.setSERVER_IP(getPreferenceStore().getString(NetWorkingName.SERVER_IP));NetworkingConfig.setSERVER_LISTENING_PORT(getPreferenceStore().getInt(NetWorkingName.SERVE R_LISTENING_PORT));NetworkingConfig.setFTP_SERVER_PORT(getPreferenceStore().getInt(NetWorkingName.FTP_SERVER_ PORT));NetworkingConfig.setTIME_OUT(getPreferenceStore().getInt(NetWorkingName.TIME_OUT));NetworkingConfig.setFTP_CLIENT_USERNAME(getPreferenceStore().getString(NetWorkingName.FTP_ CLIENT_USERNAME));NetworkingConfig.setFTP_CLIENT_PASSWORD(getPreferenceStore().getString(NetWorkingName.FTP_ CLIENT_PASSWORD));}@Overridepublic boolean performOk() {// TODO Auto-generated method stub//performApply();return super.performOk();}@Overrideprotected void performApply() {// TODO Auto-generated method stub//preferenceStore.setValue(NetWorkingName.SERVER_IP, ""+ipText.getStringValue());//preferenceStore.setDefault(name, value)setValue();super.performApply();}public void setValue(){NetworkingConfig.setSERVER_IP(ipText.getStringValue());NetworkingConfig.setSERVER_LISTENING_PORT(containerText.getIntValue());NetworkingConfig.setFTP_SERVER_PORT(ftpText.getIntValue());NetworkingConfig.setTIME_OUT(timeText.getIntValue());NetworkingConfig.setFTP_CLIENT_USERNAME(userText.getStringValue());NetworkingConfig.setFTP_CLIENT_PASSWORD(pwdText.getStringValue());}@Overrideprotected void performDefaults() {// TODO Auto-generated method stubpreferenceStore=getPreferenceStore();super.performDefaults();}}TemplateInfo.javapackage .uestc.ablator.ui.template;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.log4j.Logger;import org.eclipse.cdt.core.model.CModelException;import org.eclipse.cdt.core.model.CoreModel;import org.eclipse.cdt.core.model.ICProject;import org.eclipse.core.resources.IProject;import org.eclipse.core.runtime.IProgressMonitor;import mon.Option;import .uestc.ablator.ui.template.entry.AblatorFile;import .uestc.ablator.ui.template.entry.AblatorFolder;import .uestc.ablator.ui.template.entry.AblatorIncludePath;import .uestc.ablator.ui.template.entry.AblatorSourceFolder;import .uestc.ablator.ui.template.entry.Entry;import .uestc.ablator.ui.util.MessageConfig;/*** 模板信息,类似于CDT Template中的template.xml* 包含生成模板的所有信息* @author Administrator**/public class TemplateInfo {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);//对于有可选项的Info该属性表示可选项,对于无可项的Info该项optionList.size()==0 //文件的替换变量在manifest.xml中指出选private List<Option> optionList;//对应模板文件中的所有实体private List<Entry> entryList;private String sourceFolderPath;private Entry projectEntry;//绝对路径前缀,即工程路径private String absPathPrefix;public String getAbsPathPrefix() {return absPathPrefix;}public void setAbsPathPrefix(String absPathPrefix) {this.absPathPrefix = absPathPrefix;}public TemplateInfo(){entryList = new ArrayList<Entry>();optionList = new ArrayList<Option>();}public List<Entry> getEntryList(){return this.entryList;}public String getSourceFolderPath(){return this.sourceFolderPath;}public void setSourceFolderPath(String path){this.sourceFolderPath = path;}public void addEntry(Entry entry){entryList.add(entry);}public Entry getLast(){if(entryList.size()>0)return entryList.get(entryList.size()-1);return null;}/*** 根据TemplateInfo保存的信息创建完整的工程* @param project*/public IProject createProject(IProject project,IProgressMonitor monitor){IProject newProject = project;ICProject cProject = CoreModel.getDefault().create(project);int totalWork = entryList.size();monitor.beginTask("TemplateInfo create", totalWork);//remove the Project EntryentryList.remove(projectEntry);for(Entry entry : entryList){//folderif(entry.isCommonFolder){//new AblatorFolder().createFolder(newProject, entry);AblatorFolder.createFolder(newProject, entry);//如果该实体是源文件夹,为工程添加该源文件夹if(entry.isSourceFolder){try {//new AblatorSourceFolder().setSourceFolder(cProject, entry);AblatorSourceFolder.setSourceFolder(cProject, entry);} catch (CModelException e) {logger.error(e);}}}//fileelse{if(this.optionList.size()>0)//if Options exist, need replaceAblatorFile.createFileWithReplacement(newProject,entry,getReplaceMap());elseAblatorFile.createFile(newProject, entry);}}try {//append include pathsAblatorIncludePath.addIncludePath(cProject);} catch (CModelException e) {logger.error("CModelException: "+e);}monitor.worked(totalWork);monitor.done();return newProject;}/*** 生成替换变量的map* @return*/private Map<String, String> getReplaceMap() {Map<String,String> map = new HashMap<String,String>();for(Option o:optionList)map.put(o.getGroup().getGroupPlaceHolder(), o.getName());return map;}/*** 通过List Options,添加Entry 到TemplateInfo* @param options*/public void addOptions(List<Option> options) {this.optionList = options;projectEntry = entryList.get(entryList.size()-1);Entry optionFolderEntry = new Entry("//"+MessageConfig.OPTION_FOLDER_NAME, MessageConfig.OPTION_FOLDER_NAME);optionFolderEntry.setParent(projectEntry);optionFolderEntry.isCommonFolder = true;entryList.add(optionFolderEntry);for(Option o : options){Entry optionEntry = new Entry(MessageConfig.OPTION_FOLDER_NAME+"\\"+o.getName(), o.getName());optionEntry.setParent(optionFolderEntry);optionEntry.setTemplateFileAbsolutePath(absPathPrefix+"\\"+optionEntry.getPath());entryList.add(optionEntry);}}}PerferenceInitializer.javapackage .uestc.ablator.ui;import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;import org.eclipse.jface.preference.IPreferenceStore;public class PerferenceInitializer extends AbstractPreferenceInitializer {@Overridepublic void initializeDefaultPreferences() {// TODO Auto-generated method stubIPreferenceStore store=Activator.getDefault().getPreferenceStore();store.setDefault(NetWorkingName.SERVER_IP, "192.168.1.110");store.setDefault(NetWorkingName.SERVER_LISTENING_PORT, 8821);store.setDefault(NetWorkingName.FTP_SERVER_PORT, 21);store.setDefault(NetWorkingName.TIME_OUT, 5000);store.setDefault(NetWorkingName.FTP_CLIENT_USERNAME, "rtlab");store.setDefault(NetWorkingName.FTP_CLIENT_PASSWORD, "rtlab");}}TemplateInfoFactory.javapackage .uestc.ablator.ui.template;import java.io.File;import org.eclipse.jface.dialogs.MessageDialog;import .uestc.ablator.ui.template.entry.Entry;import .uestc.ablator.ui.util.MessageConfig;import .uestc.ablator.ui.util.XmlParser;/*** 根据id 生成TemplateInfo*/public class TemplateInfoFactory {private TemplateInfo templateInfo;private String templateId;/*** 通过id生成模板的TemplateInfo,不包括options目录及其子文件* @param id*/public TemplateInfo createTemplateInfo(String id){this.templateId = id;XmlParser parser = XmlParser.getInstance();File file = parser.findFileById(templateId);if(!file.exists()){MessageDialog.openError(null, "error", "文件"+file.getAbsolutePath()+"不存在");return null;}createTargetTemplateInfo(file,null);return this.templateInfo;}/*** 创建TemplateInfo,其中entry保存源文件路径和目标文件路径,方便后期进行文件复制* 同时保存源文件夹名e.g. /src* @param inputFile* @param parent* @return*/private TemplateInfo createTargetTemplateInfo(File inputFile,Entry parent){TemplateInfo templateInfo= createTemplate(inputFile,parent);//递归栈Entry projectEntry = templateInfo.getLast();//绝对路径前缀String projectPath = projectEntry.getPath();// ("absolute path prefix: "+projectPath);for(Entry ed :templateInfo.getEntryList()){//保存模板文件的绝对路径,以便文件拷贝ed.setTemplateFileAbsolutePath(ed.getPath());String path = ed.getPath().substring(projectPath.length(), ed.getPath().length());ed.setPath(path);}templateInfo.setSourceFolderPath(XmlParser.getInstance().getSingleSourcePath(templateId));templateInfo.setAbsPathPrefix(projectPath);return templateInfo;}/*** 返回指定id的模板的TemplateInfo,其中Entry的Path为绝对路径* @param inputFile* @param parent* @return*/private TemplateInfo createTemplate(File inputFile,Entry parent){if(!inputFile.getName().equals(MessageConfig.OPTION_FOLDER_NAME)){if(templateInfo==null)templateInfo = new TemplateInfo();String path = inputFile.getAbsolutePath();Entry entry = new Entry(path, inputFile.getName());entry.setParent(parent);if(inputFile.isDirectory()){entry.isCommonFolder = true;//判断当前文件夹是否是源文件夹if(inputFile.getName().equals(XmlParser.getInstance().getSingleSourcePath(templateId)))entry.isSourceFolder = true;File[] fileArray = inputFile.listFiles();if(fileArray.length>0){for(File file : fileArray){createTemplate(file,entry);}}}templateInfo.addEntry(entry);}return templateInfo;}。
软件著作权通用代码范本
usingSystem;usingSystem.Collections;ponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Web;usingSystem.Web.SessionState;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.HtmlControls;usingSystem.Data.SqlClient;usingSystem.Configuration;namespaceOfficeOnline{///<summary>/// Advice 的摘要说明。
///</summary>public class Advice :System.Web.UI.Page{protectedSystem.Web.UI.WebControls.ImageButton ImageButton1; protectedSystem.Web.UI.WebControls.DataGrid dgdadvice;protectedSystem.Web.UI.WebControls.ImageButton ImageButton2; private void Page_Load(objectsender, System.EventArgs e){if (!IsPostBack){//创建数据库连接和命令对象SqlConnection objconn= new SqlConnection(ConfigurationSettings.AppSettings["connstr"]);objconn.Open();stringobjsql="Select * from Advice";SqlDataAdapter da = new SqlDataAdapter(objsql,objconn); //创建并填充DataSetDataSet ds = newDataSet();da.Fill(ds);dgdadvice.DataSource=ds;dgdadvice.DataBind();objconn.Close();}}#region Web 窗体设计器生成的代码override protected voidOnInit(EventArgs e){//// CODEGEN: 该调用是 Web 窗体设计器所必需的。
计算机软件著作权登记源代码范本
计算机软件着作权登记-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,着作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybs/>#include <tybscc/>#include <dns/>#include <dns/>#include <dns/>#include <dns/>#include <dst/>#define NS_MAIN 1#include <named/>#endif#ifdef DLZ#include <dlz/>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named";static char absolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_W ARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Void ns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMA T_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n"); }static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) { for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags, &tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0) ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '':usage();if (tybs_commandline_option == '')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 "" : "s",ns_g_cpus, ns_g_cpus == 1 "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HA VE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HA VE_LIBSCF */#ifdef PA TH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create() failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PA TH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PA TH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles,&ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s",tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s",tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HA VE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) {scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) { UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HA VE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DA TE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s",tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HA VE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) {if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HA VE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) {FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include ""#include <>#include <>#ifdef PHP_WIN32#include "win32/"#include "win32/"#include "win32/"#include <>#elif defined(NETW ARE)#include <sys/>#ifdef USE_WINSOCK#include <>#endif#endif#if HA VE_SYS_TIME_H#include <sys/>#endif#if HA VE_UNISTD_H#include <>#endif#if HA VE_SIGNAL_H#include <>#endif#if HA VE_SETLOCALE#include <>#endif#include ""#include ""#include ""#include ""#include ""#include ""#include "ext/standard/"#include ""#include "ext/standard/"#ifdef PHP_WIN32#include <>#include "win32/"#include "ext/standard/"#endif#include ""#include "Zend/"#if PHP_SIGCHILD#include <sys/>#include <sys/>#endif#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""#include ""/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */ }return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp, "cli") || !strcmp, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");break;}}static PHP_INI_MH(OnUpdateErrorLog){/* Only do the safemode/open_basedir check at runtime */if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && strcmp(new_value, "syslog")) {if (PG(safe_mode) && (!php_checkuid(new_value, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {return FAILURE;}if (PG(open_basedir) && php_check_open_basedir(new_value TSRMLS_CC)) {return FAILURE;}}OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);return SUCCESS;}static PHP_INI_MH(OnChangeMailForceExtra){/* Don't allow changing it in htaccess */if (stage == PHP_INI_STAGE_HTACCESS) {return FAILURE;}return SUCCESS;}#ifndef PHP_SAFE_MODE_EXEC_DIR# define PHP_SAFE_MODE_EXEC_DIR ""#endif#if defined(PHP_PROG_SENDMAIL) && !defined(NETWARE)# define DEFAULT_SENDMAIL_PA TH PHP_PROG_SENDMAIL " -t -i "#elif defined(PHP_WIN32)# define DEFAULT_SENDMAIL_PA TH NULL#else# define DEFAULT_SENDMAIL_PA TH "/usr/sbin/sendmail -t -i"#endifPHPAPI void php_log_err(char *log_message TSRMLS_DC){int fd = -1;char error_time_str[128];。
软件著作权-源代码范本
软件著作权-源代码范本之阿布丰王创作注意事项:罕见的源代码包括:C语言,VB,C++,JAVA,.NET等.提交的代码必需是源代码的开头载入法式,第30页必需断开,第60页是软件的法式结尾,代码中不得呈现与申请表内容不符合的日期,著作权人,软件名字等,不能呈现开源代码,不能呈现任何版权纠纷.格式要求:一、源代码应提交前、后各连续30页,缺乏60页的,应当全部提交.二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页很多于50行.范例如下:#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE;static char program_name[TYBS_DIR_NAMEMAX] = "named"; static char absolute_conffile[TYBS_DIR_PATHMAX]; static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) { va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_WARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Voidns_main_earlyfatal(const char *format, ...) { va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line,tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line);tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line); tybs_log_vwrite(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) {for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) {switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 not supported by OS"); tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS"); tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument,mem_debug_flags,&tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range", tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range", tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0)ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s", cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_taskmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx,&ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr, &socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_entropy_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_hash_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HAVE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HAVE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HAVE_LIBSCF */#ifdef PATH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create()failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy,PATH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PATH_RANDOMDEV,tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s",tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s", tybs_result_totext(result));tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version, saved_command_line);tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksize, &ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasize,&ns_g_initdatasize);(void)tybs_resource_getlimit(tybs_resource_coresize,&ns_g_initcoresize);(void)tybs_resource_getlimit(tybs_resource_openfiles, &ns_g_initopenfiles);if (! tybs_file_isabsolute(ns_g_conffile)) {result = tybs_file_absolutepath(ns_g_conffile,absolute_conffile,sizeof(absolute_conffile));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("could not construct absolute path of ""configuration file: %s",tybs_result_totext(result));ns_g_conffile = absolute_conffile;}result = tybs_time_now(&ns_g_boottime);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_time_now() failed: %s",tybs_result_totext(result));result = create_managers();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("create_managers() failed: %s", tybs_result_totext(result));ns_builtin_init();#ifdef DLZresult = dlz_drivers_init();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("dlz_drivers_init() failed: %s", tybs_result_totext(result));#endifns_server_create(ns_g_mctx, &ns_g_server);}static voidcleanup(void) {destroy_managers();ns_server_destroy(&ns_g_server);ns_builtin_deinit();#ifdef DLZdlz_drivers_clear();#endifdns_name_destroy();tybs_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,TYBS_LOG_NOTICE, "exiting");ns_log_shutdown();}static char *memstats = NULL;voidns_main_setmemstats(const char *filename) {if (memstats != NULL) {free(memstats);memstats = NULL;}if (filename == NULL)return;memstats = malloc(strlen(filename) + 1);if (memstats)strcpy(memstats, filename);}#ifdef HAVE_LIBSCFtybs_result_tns_smf_get_instance(char **ins_name, int debug, tybs_mem_t *mctx) {scf_handle_t *h = NULL;int namelen;char *instance;REQUIRE(ins_name != NULL && *ins_name == NULL);if ((h = scf_handle_create(SCF_VERSION)) == NULL) { if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_create() failed: %s",scf_strerror(scf_error()));return (TYBS_R_FAILURE);}if (scf_handle_bind(h) == -1) {if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_handle_bind() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((namelen = scf_myname(h, NULL, 0)) == -1) { if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if ((instance = tybs_mem_allocate(mctx, namelen + 1)) == NULL) {UNEXPECTED_ERROR(__FILE__, __LINE__,"ns_smf_get_instance memory ""allocation failed: %s",tybs_result_totext(TYBS_R_NOMEMORY));scf_handle_destroy(h);return (TYBS_R_FAILURE);}if (scf_myname(h, instance, namelen + 1) == -1) { if (debug)UNEXPECTED_ERROR(__FILE__, __LINE__,"scf_myname() failed: %s",scf_strerror(scf_error()));scf_handle_destroy(h);tybs_mem_free(mctx, instance);return (TYBS_R_FAILURE);}scf_handle_destroy(h);*ins_name = instance;return (TYBS_R_SUCCESS);}#endifintmain(int argc, char *argv[]) {tybs_result_t result;#ifdef HAVE_LIBSCFchar *instance = NULL;#endifstrlcat(version,#ifdef __DATE__"named version: BIND " VERSION " (" __DATE__ ")",#else"named version: BIND " VERSION,#endifsizeof(version));result = tybs_file_progname(*argv, program_name, sizeof(program_name));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("program name too long");if (strcmp(program_name, "lwresd") == 0)ns_g_lwresdonly = TYBS_TRUE;tybs_assertion_setcallback(assertion_failed);tybs_error_setfatal(library_fatal_error);tybs_error_setunexpected(library_unexpected_error);ns_os_init(program_name);dns_result_register();dst_result_register();tybscc_result_register();parse_command_line(argc, argv);if (ns_g_chrootdir != NULL) {int len = strlen(ns_g_chrootdir);if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&(ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))ns_main_earlywarning("config filename (-c %s) contains ""chroot path (-t %s)",ns_g_conffile, ns_g_chrootdir);}result = tybs_mem_create(0, 0, &ns_g_mctx);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_mem_create() failed: %s", tybs_result_totext(result));tybs_mem_setname(ns_g_mctx, "main", NULL);setup();do {result = tybs_app_run();if (result == TYBS_R_RELOAD) {ns_server_reloadwanted(ns_g_server);} else if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__, __LINE__,"tybs_app_run(): %s",tybs_result_totext(result));result = TYBS_R_SUCCESS;}} while (result != TYBS_R_SUCCESS);#ifdef HAVE_LIBSCFif (ns_smf_want_disable == 1) {result = ns_smf_get_instance(&instance, 1, ns_g_mctx);if (result == TYBS_R_SUCCESS && instance != NULL) { if (smf_disable_instance(instance, 0) != 0)UNEXPECTED_ERROR(__FILE__, __LINE__,"smf_disable_instance() ""failed for %s : %s",instance,scf_strerror(scf_error()));}if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);}#endif /* HAVE_LIBSCF */cleanup();if (want_stats) {tybs_mem_stats(ns_g_mctx, stdout);tybs_mutex_stats(stdout);}if (ns_g_memstatistics && memstats != NULL) { FILE *fp = NULL;result = tybs_stdio_open(memstats, "w", &fp);if (result == TYBS_R_SUCCESS) {tybs_mem_stats(ns_g_mctx, fp);tybs_mutex_stats(fp);tybs_stdio_close(fp);}}tybs_mem_destroy(&ns_g_mctx);tybs_mem_checkdestroyed(stderr);ns_main_setmemstats(NULL);tybs_app_finish();ns_os_closedevnull();ns_os_shutdown();return (0);}#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include "php.h"#include <stdio.h>#include <fcntl.h>#ifdef PHP_WIN32#include "win32/time.h"#include "win32/signal.h"#include "win32/php_win32_globals.h"#include <process.h>#elif defined(NETWARE)#include <sys/timeval.h>#ifdef USE_WINSOCK#include <novsock2.h>#endif#endif#if HAVE_SYS_TIME_H#include <sys/time.h>#endif#if HAVE_UNISTD_H#include <unistd.h>#endif#if HAVE_SIGNAL_H#include <signal.h>#endif#if HAVE_SETLOCALE#include <locale.h>#endif#include "zend.h"#include "zend_extensions.h"#include "php_ini.h"#include "php_globals.h"#include "php_main.h"#include "fopen_wrappers.h"#include "ext/standard/php_standard.h" #include "php_variables.h"#include "ext/standard/credits.h"#ifdef PHP_WIN32#include <io.h>#include "win32/php_registry.h"#include "ext/standard/flock_compat.h" #endif#include "php_syslog.h"#include "Zend/zend_exceptions.h"#if PHP_SIGCHILD#include <sys/types.h>#include <sys/wait.h>#endif#include "zend_compile.h"#include "zend_execute.h"#include "zend_highlight.h"#include "zend_indent.h"#include "zend_extensions.h"#include "zend_ini.h"#include "php_content_types.h"#include "php_ticks.h"#include "php_logos.h"#include "php_streams.h"#include "php_open_temporary_file.h" #include "SAPI.h"#include "rfc1867.h"/* }}} */#ifndef ZTSphp_core_globals core_globals;#elsePHPAPI int core_globals_id;#endif#define SAFE_FILENAME(f) ((f)?(f):"-")/* {{{ PHP_INI_MH*/static PHP_INI_MH(OnSetPrecision){int i = atoi(new_value);if (i >= 0) {EG(precision) = i;return SUCCESS;} else {return FAILURE;}}static PHP_INI_MH(OnChangeMemoryLimit){if (new_value) {PG(memory_limit) = zend_atoi(new_value, new_value_length);} else {PG(memory_limit) = 1<<30; /* effectively, no limit */}return zend_set_memory_limit(PG(memory_limit));}static void php_disable_functions(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_functions"))) {return;}e = PG(disable_functions) = strdup(INI_STR("disable_functions"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_function(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_function(s, e-s TSRMLS_CC);}}static void php_disable_classes(TSRMLS_D){char *s = NULL, *e;if (!*(INI_STR("disable_classes"))) {return;}e = PG(disable_classes) = strdup(INI_STR("disable_classes"));while (*e) {switch (*e) {case ' ':case ',':if (s) {*e = '\0';zend_disable_class(s, e-s TSRMLS_CC);s = NULL;}break;default:if (!s) {s = e;}break;}e++;}if (s) {zend_disable_class(s, e-s TSRMLS_CC);}}static PHP_INI_MH(OnUpdateTimeout){EG(timeout_seconds) = atoi(new_value);if (stage==PHP_INI_STAGE_STARTUP) {/* Don't set a timeout on startup, only per-request */return SUCCESS;}zend_unset_timeout(TSRMLS_C);zend_set_timeout(EG(timeout_seconds));return SUCCESS;}static int php_get_display_errors_mode(char *value, int value_length){int mode;if (!value) {return PHP_DISPLAY_ERRORS_STDOUT;}if (value_length == 2 && !strcasecmp("on", value)) { mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 3 && !strcasecmp("yes", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 4 && !strcasecmp("true", value)) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else if (value_length == 6 && !strcasecmp(value, "stderr")) {mode = PHP_DISPLAY_ERRORS_STDERR;} else if (value_length == 6 && !strcasecmp(value, "stdout")) {mode = PHP_DISPLAY_ERRORS_STDOUT;} else {mode = atoi(value);if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {mode = PHP_DISPLAY_ERRORS_STDOUT;}}return mode;}static PHP_INI_MH(OnUpdateDisplayErrors){PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value, new_value_length);return SUCCESS;}static PHP_INI_DISP(display_errors_mode){int mode, tmp_value_length, cgi_or_cli;char *tmp_value;TSRMLS_FETCH();if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {tmp_value = (ini_entry->orig_value ? ini_entry->orig_value : NULL );tmp_value_length = ini_entry->orig_value_length;} else if (ini_entry->value) {tmp_value = ini_entry->value;tmp_value_length = ini_entry->value_length;} else {tmp_value = NULL;tmp_value_length = 0;}mode = php_get_display_errors_mode(tmp_value, tmp_value_length);cgi_or_cli = (!strcmp(sapi_, "cli") || !strcmp(sapi_, "cgi"));switch (mode) {case PHP_DISPLAY_ERRORS_STDERR:if (cgi_or_cli ) {PUTS("STDERR");} else {PUTS("On");}break;case PHP_DISPLAY_ERRORS_STDOUT:if (cgi_or_cli ) {PUTS("STDOUT");} else {PUTS("On");}break;default:PUTS("Off");。
软件著作权-源代码范本之欧阳与创编
软件著作权-源代码范本注意事项:常见的源代码包含:C语言,VB,C++,JAVA,.NET等。
提交的代码必须是源代码的开头载入程序,第30页必须断开,第60页是软件的程序结尾,代码中不得出现与申请表内容不符合的日期,著作权人,软件名字等,不能出现开源代码,不能出现任何版权纠纷。
格式要求:一、源代码应提交前、后各连续30页,不足60页的,应当全部提交。
二、源代码页眉应标注软件的名称和版本号,应当与申请表中名称完全一致,页眉右上应标注页码,源代码每页不少于50行。
范例如下:#include <tybs/commandline.h>#include <tybs/dir.h>#include <tybs/entropy.h>#include <tybs/file.h>#include <tybs/hash.h>#include <tybs/os.h>#include <tybs/platform.h>#include <tybs/resource.h>#include <tybs/stdio.h>#include <tybs/string.h>#include <tybs/task.h>#include <tybs/timer.h>#include <tybs/util.h>#include <tybscc/result.h>#include <dns/dispatch.h>#include <dns/name.h>#include <dns/result.h>#include <dns/view.h>#include <dst/result.h>#define NS_MAIN 1#include <named/ns_smf_globals.h>#endif#ifdef DLZ#include <dlz/dlz_drivers.h>#endifstatic tybs_boolean_t want_stats = TYBS_FALSE; static charprogram_name[TYBS_DIR_NAMEMAX] = "named";static charabsolute_conffile[TYBS_DIR_PATHMAX];static char saved_command_line[512];static char version[512];static unsigned int maxsocks = 0;voidns_main_earlywarning(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_WARNING,format, args);} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);}Voidns_main_earlyfatal(const char *format, ...) {va_list args;va_start(args, format);if (ns_g_lctx != NULL) {tybs_log_vwrite(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to early fatal error)");} else {fprintf(stderr, "%s: ", program_name);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}va_end(args);exit(1);}static voidassertion_failed(const char *file, int line, tybs_assertiontype_t type,const char *cond){if (ns_g_lctx != NULL) {tybs_assertion_setcallback(NULL);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: %s(%s) failed", file, line, tybs_assertion_typetotext(type), cond);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to assertion failure)");} else {fprintf(stderr, "%s:%d: %s(%s) failed\n",file, line, tybs_assertion_typetotext(type), cond);fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_fatal_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_error_setfatal(NULL);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"%s:%d: fatal error:", file, line); tybs_log_vwrite(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,format, args);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_CRITICAL,"exiting (due to fatal error in library)");} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}if (ns_g_coreok)abort();exit(1);}static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args) TYBS_FORMAT_PRINTF(3, 0);static voidlibrary_unexpected_error(const char *file, int line, const char *format,va_list args){if (ns_g_lctx != NULL) {tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,"%s:%d: unexpected error:", file, line);tybs_log_vwrite(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN, TYBS_LOG_ERROR,format, args);} else {fprintf(stderr, "%s:%d: fatal error: ", file, line);vfprintf(stderr, format, args);fprintf(stderr, "\n");fflush(stderr);}}static voidlwresd_usage(void) {fprintf(stderr,"usage: lwresd [-4|-6] [-c conffile | -C resolvconffile] ""[-d debuglevel]\n"" [-f|-g] [-n number_of_cpus] [-p port] ""[-P listen-port] [-s]\n"" [-t chrootdir] [-u username] [-i pidfile]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidusage(void) {if (ns_g_lwresdonly) {lwresd_usage();return;}fprintf(stderr,"usage: named [-4|-6] [-c conffile] [-d debuglevel] ""[-f|-g] [-n number_of_cpus]\n"" [-p port] [-s] [-t chrootdir] [-u username]\n"" [-m {usage|trace|record|size|mctx}]\n");}static voidsave_command_line(int argc, char *argv[]) {int i;char *src;char *dst;char *eob;const char truncated[] = "...";tybs_boolean_t quoted = TYBS_FALSE;dst = saved_command_line;eob = saved_command_line + sizeof(saved_command_line);for (i = 1; i < argc && dst < eob; i++) {*dst++ = ' ';src = argv[i];while (*src != '\0' && dst < eob) {if (quoted || isalnum(*src & 0xff) ||*src == '-' || *src == '_' ||*src == '.' || *src == '/') {*dst++ = *src++;quoted = TYBS_FALSE;} else {*dst++ = '\\';quoted = TYBS_TRUE;}}}INSIST(sizeof(saved_command_line) >= sizeof(truncated));if (dst == eob)strcpy(eob - sizeof(truncated), truncated);else*dst = '\0';}static intparse_int(char *arg, const char *desc) {char *endp;int tmp;long int ltmp;ltmp = strtol(arg, &endp, 10);tmp = (int) ltmp;if (*endp != '\0')ns_main_earlyfatal("%s '%s' must be numeric", desc, arg);if (tmp < 0 || tmp != ltmp)ns_main_earlyfatal("%s '%s' out of range", desc, arg);return (tmp);}static struct flag_def {const char *name;unsigned int value;} mem_debug_flags[] = {{ "trace", TYBS_MEM_DEBUGTRACE },{ "record", TYBS_MEM_DEBUGRECORD },{ "usage", TYBS_MEM_DEBUGUSAGE },{ "size", TYBS_MEM_DEBUGSIZE },{ "mctx", TYBS_MEM_DEBUGCTX },{ NULL, 0 }};static voidset_flags(const char *arg, struct flag_def *defs, unsigned int *ret) {for (;;) {const struct flag_def *def;const char *end = strchr(arg, ',');int arglen;if (end == NULL)end = arg + strlen(arg);arglen = end - arg;for (def = defs; def->name != NULL; def++) {if (arglen == (int)strlen(def->name) &&memcmp(arg, def->name, arglen) == 0) {*ret |= def->value;goto found;}}ns_main_earlyfatal("unrecognized flag '%.*s'", arglen, arg);found:if (*end == '\0')break;arg = end + 1;}}static voidparse_command_line(int argc, char *argv[]) {int ch;int port;tybs_boolean_t disable6 = TYBS_FALSE;tybs_boolean_t disable4 = TYBS_FALSE;save_command_line(argc, argv);tybs_commandline_errprint = TYBS_FALSE;while ((ch = tybs_commandline_parse(argc, argv,"46c:C:d:fgi:lm:n:N:p:P:""sS:t:T:u:vVx:")) != -1) { switch (ch) {case '4':if (disable4)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv4() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv4 notsupported by OS");tybs_net_disableipv6();disable6 = TYBS_TRUE;break;case '6':if (disable6)ns_main_earlyfatal("cannot specify -4 and -6");if (tybs_net_probeipv6() != TYBS_R_SUCCESS)ns_main_earlyfatal("IPv6 not supported by OS");tybs_net_disableipv4();disable4 = TYBS_TRUE;break;case 'c':ns_g_conffile = tybs_commandline_argument;lwresd_g_conffile = tybs_commandline_argument;if (lwresd_g_useresolvconf)ns_main_earlyfatal("cannot specify -c and -C");ns_g_conffileset = TYBS_TRUE;break;case 'C':lwresd_g_resolvconffile = tybs_commandline_argument;if (ns_g_conffileset)ns_main_earlyfatal("cannot specify -c and -C");lwresd_g_useresolvconf = TYBS_TRUE;break;case 'd':ns_g_debuglevel = parse_int(tybs_commandline_argument,"debug level");break;case 'f':ns_g_foreground = TYBS_TRUE;break;case 'g':ns_g_foreground = TYBS_TRUE;ns_g_logstderr = TYBS_TRUE;break;/* XXXBEW -i should be removed */case 'i':lwresd_g_defaultpidfile = tybs_commandline_argument;break;case 'l':ns_g_lwresdonly = TYBS_TRUE;break;case 'm':set_flags(tybs_commandline_argument, mem_debug_flags,&tybs_mem_debugging);break;case 'N': /* Deprecated. */case 'n':ns_g_cpus = parse_int(tybs_commandline_argument,"number of cpus");if (ns_g_cpus == 0)ns_g_cpus = 1;break;case 'p':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);ns_g_port = port;break;/* XXXBEW Should -P be removed? */case 'P':port = parse_int(tybs_commandline_argument, "port");if (port < 1 || port > 65535)ns_main_earlyfatal("port '%s' out of range",tybs_commandline_argument);lwresd_g_listenport = port;break;case 's':want_stats = TYBS_TRUE;break;case 'S':maxsocks = parse_int(tybs_commandline_argument,"max number of sockets");break;case 't':ns_g_chrootdir = tybs_commandline_argument;break;case 'T':if (strcmp(tybs_commandline_argument, "clienttest") == 0)ns_g_clienttest = TYBS_TRUE;elsefprintf(stderr, "unknown -T flag '%s\n",tybs_commandline_argument);break;case 'u':ns_g_username = tybs_commandline_argument;break;case 'v':printf("BIND %s\n", ns_g_version);exit(0);case 'V':printf("BIND %s built with %s\n", ns_g_version,ns_g_configargs);exit(0);case '?':usage();if (tybs_commandline_option == '?')exit(0);ns_main_earlyfatal("unknown option '-%c'",tybs_commandline_option);default:ns_main_earlyfatal("parsing options returned %d", ch);}}argc -= tybs_commandline_index;argv += tybs_commandline_index;if (argc > 0) {usage();ns_main_earlyfatal("extra command line arguments");}}static tybs_result_tcreate_managers(void) {tybs_result_t result;unsigned int socks;#ifdef TYBS_PLATFORM_USETHREADSunsigned int cpus_detected;#endif#ifdef TYBS_PLATFORM_USETHREADScpus_detected = tybs_os_ncpus();if (ns_g_cpus == 0)ns_g_cpus = cpus_detected;tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,TYBS_LOG_INFO, "found %u CPU%s, using %u worker thread%s",cpus_detected, cpus_detected == 1 ? "" : "s",ns_g_cpus, ns_g_cpus == 1 ? "" : "s");#elsens_g_cpus = 1;#endifresult = tybs_taskmgr_create(ns_g_mctx, ns_g_cpus, 0, &ns_g_taskmgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__,__LINE__,"tybs_taskmgr_create()failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_timermgr_create(ns_g_mctx, &ns_g_timermgr);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__,__LINE__,"tybs_timermgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_create2(ns_g_mctx, &ns_g_socketmgr, maxsocks);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__,__LINE__,"tybs_socketmgr_create() failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_socketmgr_getmaxsockets(ns_g_socketmgr,&socks);if (result == TYBS_R_SUCCESS) {tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER, TYBS_LOG_INFO, "using up to %u sockets", socks);}result = tybs_entropy_create(ns_g_mctx, &ns_g_entropy);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__,__LINE__,"tybs_entropy_create()failed: %s",tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}result = tybs_hash_create(ns_g_mctx, ns_g_entropy, DNS_NAME_MAXWIRE);if (result != TYBS_R_SUCCESS) {UNEXPECTED_ERROR(__FILE__,__LINE__,"tybs_hash_create() failed: %s", tybs_result_totext(result));return (TYBS_R_UNEXPECTED);}return (TYBS_R_SUCCESS);}static voiddestroy_managers(void) {ns_lwresd_shutdown();tybs_entropy_detach(&ns_g_entropy);if (ns_g_fallbackentropy != NULL)tybs_entropy_detach(&ns_g_fallbackentropy);tybs_taskmgr_destroy(&ns_g_taskmgr);tybs_timermgr_destroy(&ns_g_timermgr);tybs_socketmgr_destroy(&ns_g_socketmgr);tybs_hash_destroy();}static voidsetup(void) {tybs_result_t result;#ifdef HAVE_LIBSCFchar *instance = NULL;#endifns_os_inituserinfo(ns_g_username);ns_os_tzset();ns_os_opendevnull();#ifdef HAVE_LIBSCFresult = ns_smf_get_instance(&instance, 0, ns_g_mctx);if (result == TYBS_R_SUCCESS)ns_smf_got_instance = 1;elsens_smf_got_instance = 0;if (instance != NULL)tybs_mem_free(ns_g_mctx, instance);#endif /* HAVE_LIBSCF */#ifdef PATH_RANDOMDEVif (ns_g_chrootdir != NULL) {result = tybs_entropy_create(ns_g_mctx, &ns_g_fallbackentropy);if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_entropy_create()failed: %s",tybs_result_totext(result));result = tybs_entropy_createfilesource(ns_g_fallbackentropy, PATH_RANDOMDEV);if (result != TYBS_R_SUCCESS) {ns_main_earlywarning("could not open pre-chroot ""entropy source %s: %s",PATH_RANDOMDEV, tybs_result_totext(result));tybs_entropy_detach(&ns_g_fallbackentropy);}}#endifns_os_chroot(ns_g_chrootdir);ns_os_minprivs();result = ns_log_init(TYBS_TF(ns_g_username != NULL));if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("ns_log_init() failed: %s", tybs_result_totext(result));if (!ns_g_foreground)ns_os_daemonize();result = tybs_app_start();if (result != TYBS_R_SUCCESS)ns_main_earlyfatal("tybs_app_start() failed: %s",tybs_result_totext(result));tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN,TYBS_LOG_NOTICE, "starting BIND %s%s", ns_g_version,saved_command_line);tybs_log_write(ns_g_lctx,NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_MAIN,TYBS_LOG_NOTICE, "built with %s", ns_g_configargs);(void)tybs_resource_getlimit(tybs_resource_stacksi ze,&ns_g_initstacksize);(void)tybs_resource_getlimit(tybs_resource_datasiz e,。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Option.javapackage mon;public class Option {private String name;private String id;private String description;private OptionGroup group;public Option(String id, String name, String description,OptionGroup group) { this.id = id; = name;this.description = description;this.group = group;}public String getName() {return name;}public String getId() {return id;}public String getDescription() {return description.replaceAll("\\t", "").trim();}public OptionGroup getGroup(){return this.group;}}OptionGroup.javapackage mon;import java.util.ArrayList;import java.util.List;import .uestc.ablator.ui.util.XmlParser;/*** 选项组* @author Administrator**/public class OptionGroup {private String id;private String name;private List<Option> optionList;public OptionGroup(String id, String name){this.id = id; = name;this.optionList = new ArrayList<Option>();}public void addOption(Option o){if(optionList!=null)optionList.add(o);}public String getGroupPlaceHolder(){return XmlParser.getInstance().getGroupPlaceholder(id);}public String getName(){return ;}public List<Option> getOptionList(){return this.optionList;}}ProjectType.javapackage mon;/*** 工程类型枚举* @author Administrator**/public enum ProjectType {/*** 普通工程*/COMMOMAPPLICATION("commonApplication"),/*** 解决方案*/SOLUTION("solution"),/*** 模块程序*/MODULE("module"),/*** 原子库*/A TOM("atom");private String name;ProjectType(String name){ = name;}public String getName(){return ;}}Activator.javapackage .uestc.ablator.ui;import org.eclipse.ui.plugin.AbstractUIPlugin;import org.osgi.framework.BundleContext;/*** The activator class controls the plug-in life cycle*/public class Activator extends AbstractUIPlugin {// The plug-in IDpublic static final String PLUGIN_ID = ".uestc.ablator.ui";// The shared instanceprivate static Activator plugin;/*** The constructor*/public Activator() {}/** (non-Javadoc)* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */public void start(BundleContext context) throws Exception {super.start(context);plugin = this;}/** (non-Javadoc)* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */public void stop(BundleContext context) throws Exception {plugin = null;super.stop(context);}/*** Returns the shared instance** @return the shared instance*/public static Activator getDefault() {return plugin;}}ClientSocket.javapackage working;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import .Socket;import .SocketTimeoutException;import .UnknownHostException;import org.apache.log4j.Logger;import .uestc.ablator.ui.util.MessageConfig;class ClientSocket {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private String ip;private int port;private Socket socket;private ObjectOutputStream outputStream;private ObjectInputStream inputStream;public ClientSocket(String ip, int port) {this.ip = ip;this.port = port;}/*** 连接服务器* @return 连接成功返回true 否则返回false* @throws IOException* @throws UnknownHostException*/public boolean connect() throws UnknownHostException, IOException {try {boolean success = false;socket = new Socket(ip, port);//设置read超时socket.setSoTimeout(NetworkingConfig.TIME_OUT);success = true;return success;} catch(IOException e){throw new IOException("无法连接服务器,请检查端口和服务器地址");}}/*** 发送消息到服务器* @param message* @return 发送成功返回true 否则返回false*/public void sendMessage(Message message)throws IOException{try {outputStream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));outputStream.writeObject(message);outputStream.flush();}catch (IOException e) {if(outputStream != null)try {outputStream.close();} catch (IOException ioe) {logger.error("关闭输出流失败");}throw new IOException("发送消息:"+message+" 失败");}}/*** 从服务器接受消息* @return 成功接受返回接受到的消息,否则返回null* @throws SocketTimeoutException*/public Message receiveMessage() throws SocketTimeoutException{Message receiveMessage = null;try {inputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));receiveMessage = (Message)inputStream.readObject();} catch(SocketTimeoutException e){throw new SocketTimeoutException("读取数据超时");} catch (ClassCastException e) {logger.error("ClassCastException从服务器读取的数据不能转换为Message");} catch (IOException ioe){logger.error(ioe.getMessage());} catch (ClassNotFoundException e){logger.error(e.getMessage());}return receiveMessage;}/*** 关闭连接* @throws IOException*/public void shutdownConnection() throws IOException {if (outputStream != null)outputStream.close();if (inputStream != null)inputStream.close();if (socket != null)socket.close();}}Downloader.javapackage working;import java.io.File;import java.io.IOException;import .SocketException;import .SocketTimeoutException;import .UnknownHostException;import java.util.List;import org.apache.log4j.Logger;import org.dom4j.DocumentException;import org.eclipse.core.runtime.IProgressMonitor;import .uestc.ablator.ui.util.MessageConfig;import .uestc.ablator.ui.util.XmlParser;/*** 负责从服务器接受数据* @author Administrator**/public class Downloader {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private ClientSocket clientSocket = null;private FtpUtil ftpUtil;/*** 连接服务器* @throws IOException* @throws UnknownHostException* @throws LoginException*/public void connect() throws UnknownHostException, IOException, LoginException{clientSocket = new ClientSocket(NetworkingConfig.SERVER_IP, NetworkingConfig.SERVER_LISTENING_PORT);clientSocket.connect();ftpUtil = new FtpUtil();ftpUtil.connectAndLogin(NetworkingConfig.SERVER_IP, NetworkingConfig.FTP_SERVER_PORT, NetworkingConfig.FTP_CLIENT_USERNAME, NetworkingConfig.FTP_CLIENT_PASSWORD);}/*** 发送消息到服务器* @param message* @throws IOException*/private void sendMessage(Message message) throws IOException{clientSocket.sendMessage(message);}/*** 从服务器接受消息* @return 成功接受返回接收到的消息Message,否则返回null* @throws SocketTimeoutException*/private Message getMessageFromServer() throws SocketTimeoutException{return clientSocket.receiveMessage();}/** 发送消息格式:* Message* MessageType: GET_MANIFEST* data:从download文件夹下manifest.xml中读取versionID(若不存在则id号为-1)* paths:空** 接收消息格式:* 1. 没有更新manifest.xml* Message* MessageType: GET_MANIFEST* data: 服务器端manifest.xml版本号* paths: 空** 2.有更新manifest.xml* Message* MessageType: GET_MANIFEST* data: manifest.xml在ftp服务器端的目录* paths: 空*//*** 下载manifest.xml到本地目录savePath* @param savePath 存储目录* @return 下载成功返回true,否则返回false* @throws IOException* @throws LoginException 登录ftp异常,用户名密码错误* @throws SocketException ftp连接异常*/public void downloadManifest(String savePath) throws SocketTimeoutException,IOException{String manifestVersion = "";try{manifestVersion = XmlParser.getInstance().getVersion();}catch(NullPointerException e){manifestVersion = "-1";}sendMessage(new Message(MessageType.GET_MANIFEST , manifestVersion));Message message = getMessageFromServer();if(message != null){String remoteVersion = message.getData();if(remoteVersion.equals(manifestVersion)){("服务器端manifest.xml无更新版本,读取本地download文件夹下manifest.xml");return;}String remotePath = message.getData();if(ftpUtil.downloadFile(remotePath, savePath)){("成功下载manifest.xml,保存至"+savePath+File.separator+MessageConfig.MANIFEST_FILE_NAME);try {MessageConfig.setManifestPath(savePath+File.separator+MessageConfig.MANIFEST_FILE_NAME);} catch (DocumentException e) {//donothing,因为成功下载manifest,理论上该处不会抛出异常}}}}/** 发送消息格式:* Message* MessageType: GET_TEMPLATE* data: 要下载的template的ID* paths:空** 接收消息格式:* Message* MessageType: GET_TEMPLATE* data: template文件夹在ftp服务器的目录e.g. /AA/BB/CC/Target* paths: option文件在ftp服务器的路径/包含文件名(若有多个option,以";"分割)*//*** 下载template文件,保存至savePath* @param templateId 请求下载的templateID* @param savePath template文件夹保存目录* @throws IOException*/public void downTemplate(String templateId, String savePath, IProgressMonitor monitor) throws SocketTimeoutException,IOException{monitor.beginTask("下载模板文件", 70);sendMessage(new Message(MessageType.GET_TEMPLATE,templateId));monitor.worked(10);Message message = getMessageFromServer();if(message != null){String data = message.getData();if(data != null && !data.equals("")){ftpUtil.downloadFolder(data, savePath);monitor.worked(50);}List<String> paths = message.getPaths();if(paths!=null && paths.size()>0){for(String optionPath : paths){ftpUtil.downloadFile(optionPath, savePath);}}monitor.worked(10);}monitor.done();}public void disconnect() throws IOException{clientSocket.shutdownConnection();ftpUtil.loginoutAndDisconnect();}}FtpUtil.javapackage working;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import .SocketException;import .ftp.FTPClient;import .ftp.FTPClientConfig;import .ftp.FTPFile;import .ftp.FTPReply;import org.apache.log4j.Logger;import .uestc.ablator.ui.util.MessageConfig;public class FtpUtil {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);private FTPClient ftpClient;/*** 连接到FTP服务器并登录* @param ftpServerIp FTP服务器IP* @param ftpServerPort FTP服务器端口* @param user 用户名* @param password 密码* @throws SocketException* @throws IOException* @throws LoginException 用户名密码异常*/public void connectAndLogin(String ftpServerIp, int ftpServerPort, String user, String password) throws SocketException, IOException, LoginException{ftpClient = new FTPClient();ftpClient.setControlEncoding("GBK");FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);conf.setServerLanguageCode("zh");try {ftpClient.connect( ftpServerIp, ftpServerPort);} catch (IOException e) {logger.error("尝试连接到FTP服务器失败,请检查端口和服务器地址");throw new IOException("尝试连接到FTP服务器失败,请检查端口和服务器地址");}int reply = ftpClient.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftpClient.disconnect();logger.error("FTP 服务器拒绝连接");}if(!ftpClient.login(user, password)){throw new LoginException("登录FTP服务器失败,用户名密码错误");}ftpClient.enterLocalPassiveMode(); //active connection server mode}/*** 注销并关闭连接* @throws IOException*/public void loginoutAndDisconnect() throws IOException{ftpClient.logout();if(ftpClient.isConnected())ftpClient.disconnect();}/*** 下载指定文件* @param remoteFilePath 在ftp服务器上的路径,包含文件名 e.g./aa/bb/cc/dd.xml* @param localFileDir 下载文件保存在本地的目录* @throws IOException*/public boolean downloadFile(String remoteFilePath,String localFileDir){boolean result = false;String fileName = remoteFilePath.substring(stIndexOf("/")+1,remoteFilePath.length());String dir = remoteFilePath.substring(0, stIndexOf("/"));try{ftpClient.changeWorkingDirectory(dir);FTPFile files[] = ftpClient.listFiles();for(FTPFile f : files){if(f.getName().equals(fileName)){File localFile = new File(localFileDir+File.separator+fileName);OutputStream os = new FileOutputStream(localFile);ftpClient.retrieveFile(fileName, os);os.close();result = true;}}}catch(Exception e){System.out.println(e.getMessage());}return result;}/*** 载指定文件夹* @param remoteFolder FTP服务器文件夹/aa/bb/cc,目标文件夹* @param localDir下载到本地目录localDir* @throws IOException*/public void downloadFolder(String remoteFolder, String localDir) throws IOException{//文件夹名称String folderName = remoteFolder.substring(stIndexOf("/")+1,remoteFolder.length());File localFolder = new File(localDir+File.separator+folderName);//在本地以服务器端创建相应文件夹if(!localFolder.exists())localFolder.mkdirs();ftpClient.changeWorkingDirectory(remoteFolder);FTPFile[] files = ftpClient.listFiles();for(FTPFile file : files){if(!file.getName().equals(".") && !file.getName().equals("..")){String remoteFilePath = remoteFolder+NetworkingConfig.FTP_FILE_SEPERATOR+file.getName();if(file.isDirectory()){downloadFolder(remoteFilePath, localFolder.getAbsolutePath());}else{if(file.isFile()){downloadFile(remoteFilePath, localFolder.getAbsolutePath());}}}}}}LoginException.javapackage working;public class LoginException extends Exception {private static final long serialVersionUID = -4615049932628592182L;public LoginException(String message){super(message);}}Message.javapackage working;import java.io.Serializable;import java.util.ArrayList;import java.util.List;/*** 消息结构,用于在客户端和服务器之间传递控制信息* 实际的文件传输使用FTP* @author Administrator**/public class Message implements Serializable{private static final long serialVersionUID = 406680447556221555L;private MessageType type;private String data;private List<String> paths;//请求下载文件时,从服务器端返回的paths保存options在服务器ftp上的路径public Message(){}public Message(MessageType type){this.type = type;this.data = "";this.paths = new ArrayList<String>();}public Message(MessageType type, String data){this.type = type;this.data = data;this.paths = new ArrayList<String>();}public MessageType getType() {return type;}public void setType(MessageType type) {this.type = type;}public String getData() {return data;}public void setData(String data) {this.data = data;}public List<String> getPaths() {return paths;}public void setPaths(List<String> paths) {this.paths = paths;}public String toString() {return "消息类型: "+getType()+" 消息内容: "+((getData().equals("")||getData()==null)?"空":getData())+" 可选项: "+(paths.size()==0?"空":paths);}}MessageType.javapackage working;public enum MessageType {/*** 表示该消息类型为向服务器请求manifest.xml*/GET_MANIFEST,/*** 表示该消息类型为向服务器请求指定ID的模板文件*/GET_TEMPLATE;}NetworkingConfig.javapackage .uestc.ablator.ui;public class NetWorkingName {public static final String SERVER_LISTENING_PORT = "SERVER_LISTENING_PORT";public static final String SERVER_IP = "SERVER_IP";// public static final String SERVER_IP = "192.168.1.160";public static final String FTP_SERVER_PORT= "FTP_SERVER_PORT";public static final String FTP_CLIENT_USERNAME= "FTP_CLIENT_USERNAME";public static final String FTP_CLIENT_PASSWORD= "FTP_CLIENT_PASSWORD";public static final String TIME_OUT = "TIME_OUT";}NetWorkingConfigs.javapackage .uestc.ablator.ui;import org.eclipse.jface.preference.FieldEditorPreferencePage;import org.eclipse.jface.preference.IPreferenceStore;import org.eclipse.jface.preference.IntegerFieldEditor;import org.eclipse.jface.preference.StringFieldEditor;import org.eclipse.swt.SWT;import yout.GridLayout;import posite;import org.eclipse.swt.widgets.Text;import org.eclipse.ui.IWorkbench;import org.eclipse.ui.IWorkbenchPreferencePage;import workingConfig;public class NetWorkingConfigs extends FieldEditorPreferencePage implementsIWorkbenchPreferencePage {IPreferenceStore preferenceStore;private IntegerFieldEditor containerText;private IntegerFieldEditor ftpText;private StringFieldEditor userText;private StringFieldEditor pwdText;private IntegerFieldEditor timeText;private StringFieldEditor ipText;public NetWorkingConfigs(){super(GRID);setPreferenceStore(Activator.getDefault().getPreferenceStore());setDescription("请修改远程应用仓库配置信息!");//System.out.println(test);}@Overrideprotected void createFieldEditors() {addField(ipText=new StringFieldEditor(NetWorkingName.SERVER_IP, "服务器IP", 18, getFieldEditorParent()));addField(containerText=new IntegerFieldEditor(NetWorkingName.SERVER_LISTENING_PORT, "服务器端口", getFieldEditorParent(), 5));addField(ftpText=new IntegerFieldEditor(NetWorkingName.FTP_SERVER_PORT, "服务器FTP端口", getFieldEditorParent(), 5));addField(timeText=new IntegerFieldEditor(NetWorkingName.TIME_OUT, "超时时间/毫秒", getFieldEditorParent(), 6));addField(userText=new StringFieldEditor(NetWorkingName.FTP_CLIENT_USERNAME, "用户名", 18, getFieldEditorParent()));addField(pwdText=new StringFieldEditor(NetWorkingName.FTP_CLIENT_PASSWORD, "密码", 18, getFieldEditorParent()));}@Overridepublic void init(IWorkbench workbench) {// TODO Auto-generated method stubsetPreferenceStore(Activator.getDefault().getPreferenceStore());//System.out.println(test);//preferenceStore.getDefaultString(NetWorkingName.SERVER_IP);}public void ConnectionAll(){NetworkingConfig.setSERVER_IP(getPreferenceStore().getString(NetWorkingName.SERVER_IP));NetworkingConfig.setSERVER_LISTENING_PORT(getPreferenceStore().getInt(NetWorkingName.SERVE R_LISTENING_PORT));NetworkingConfig.setFTP_SERVER_PORT(getPreferenceStore().getInt(NetWorkingName.FTP_SERVER_ PORT));NetworkingConfig.setTIME_OUT(getPreferenceStore().getInt(NetWorkingName.TIME_OUT));NetworkingConfig.setFTP_CLIENT_USERNAME(getPreferenceStore().getString(NetWorkingName.FTP_ CLIENT_USERNAME));NetworkingConfig.setFTP_CLIENT_PASSWORD(getPreferenceStore().getString(NetWorkingName.FTP_ CLIENT_PASSWORD));}@Overridepublic boolean performOk() {// TODO Auto-generated method stub//performApply();return super.performOk();}@Overrideprotected void performApply() {// TODO Auto-generated method stub//preferenceStore.setValue(NetWorkingName.SERVER_IP, ""+ipText.getStringValue());//preferenceStore.setDefault(name, value)setValue();super.performApply();}public void setValue(){NetworkingConfig.setSERVER_IP(ipText.getStringValue());NetworkingConfig.setSERVER_LISTENING_PORT(containerText.getIntValue());NetworkingConfig.setFTP_SERVER_PORT(ftpText.getIntValue());NetworkingConfig.setTIME_OUT(timeText.getIntValue());NetworkingConfig.setFTP_CLIENT_USERNAME(userText.getStringValue());NetworkingConfig.setFTP_CLIENT_PASSWORD(pwdText.getStringValue());}@Overrideprotected void performDefaults() {// TODO Auto-generated method stubpreferenceStore=getPreferenceStore();super.performDefaults();}}TemplateInfo.javapackage .uestc.ablator.ui.template;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.log4j.Logger;import org.eclipse.cdt.core.model.CModelException;import org.eclipse.cdt.core.model.CoreModel;import org.eclipse.cdt.core.model.ICProject;import org.eclipse.core.resources.IProject;import org.eclipse.core.runtime.IProgressMonitor;import mon.Option;import .uestc.ablator.ui.template.entry.AblatorFile;import .uestc.ablator.ui.template.entry.AblatorFolder;import .uestc.ablator.ui.template.entry.AblatorIncludePath;import .uestc.ablator.ui.template.entry.AblatorSourceFolder;import .uestc.ablator.ui.template.entry.Entry;import .uestc.ablator.ui.util.MessageConfig;/*** 模板信息,类似于CDT Template中的template.xml* 包含生成模板的所有信息* @author Administrator**/public class TemplateInfo {private Logger logger = Logger.getLogger(MessageConfig.LOGGER_NAME);//对于有可选项的Info该属性表示可选项,对于无可项的Info该项optionList.size()==0 //文件的替换变量在manifest.xml中指出选private List<Option> optionList;//对应模板文件中的所有实体private List<Entry> entryList;private String sourceFolderPath;private Entry projectEntry;//绝对路径前缀,即工程路径private String absPathPrefix;public String getAbsPathPrefix() {return absPathPrefix;}public void setAbsPathPrefix(String absPathPrefix) {this.absPathPrefix = absPathPrefix;}public TemplateInfo(){entryList = new ArrayList<Entry>();optionList = new ArrayList<Option>();}public List<Entry> getEntryList(){return this.entryList;}public String getSourceFolderPath(){return this.sourceFolderPath;}public void setSourceFolderPath(String path){this.sourceFolderPath = path;}public void addEntry(Entry entry){entryList.add(entry);}public Entry getLast(){if(entryList.size()>0)return entryList.get(entryList.size()-1);return null;}/*** 根据TemplateInfo保存的信息创建完整的工程* @param project*/public IProject createProject(IProject project,IProgressMonitor monitor){IProject newProject = project;ICProject cProject = CoreModel.getDefault().create(project);int totalWork = entryList.size();monitor.beginTask("TemplateInfo create", totalWork);//remove the Project EntryentryList.remove(projectEntry);for(Entry entry : entryList){//folderif(entry.isCommonFolder){//new AblatorFolder().createFolder(newProject, entry);AblatorFolder.createFolder(newProject, entry);//如果该实体是源文件夹,为工程添加该源文件夹if(entry.isSourceFolder){try {//new AblatorSourceFolder().setSourceFolder(cProject, entry);AblatorSourceFolder.setSourceFolder(cProject, entry);} catch (CModelException e) {logger.error(e);}}}//fileelse{if(this.optionList.size()>0)//if Options exist, need replaceAblatorFile.createFileWithReplacement(newProject,entry,getReplaceMap());elseAblatorFile.createFile(newProject, entry);}}try {//append include pathsAblatorIncludePath.addIncludePath(cProject);} catch (CModelException e) {logger.error("CModelException: "+e);}monitor.worked(totalWork);monitor.done();return newProject;}/*** 生成替换变量的map* @return*/private Map<String, String> getReplaceMap() {Map<String,String> map = new HashMap<String,String>();for(Option o:optionList)map.put(o.getGroup().getGroupPlaceHolder(), o.getName());return map;}/*** 通过List Options,添加Entry 到TemplateInfo* @param options*/public void addOptions(List<Option> options) {this.optionList = options;projectEntry = entryList.get(entryList.size()-1);Entry optionFolderEntry = new Entry("//"+MessageConfig.OPTION_FOLDER_NAME, MessageConfig.OPTION_FOLDER_NAME);optionFolderEntry.setParent(projectEntry);optionFolderEntry.isCommonFolder = true;entryList.add(optionFolderEntry);for(Option o : options){Entry optionEntry = new Entry(MessageConfig.OPTION_FOLDER_NAME+"\\"+o.getName(), o.getName());optionEntry.setParent(optionFolderEntry);optionEntry.setTemplateFileAbsolutePath(absPathPrefix+"\\"+optionEntry.getPath());entryList.add(optionEntry);}}}PerferenceInitializer.javapackage .uestc.ablator.ui;import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;import org.eclipse.jface.preference.IPreferenceStore;public class PerferenceInitializer extends AbstractPreferenceInitializer {@Overridepublic void initializeDefaultPreferences() {// TODO Auto-generated method stubIPreferenceStore store=Activator.getDefault().getPreferenceStore();store.setDefault(NetWorkingName.SERVER_IP, "192.168.1.110");store.setDefault(NetWorkingName.SERVER_LISTENING_PORT, 8821);store.setDefault(NetWorkingName.FTP_SERVER_PORT, 21);store.setDefault(NetWorkingName.TIME_OUT, 5000);store.setDefault(NetWorkingName.FTP_CLIENT_USERNAME, "rtlab");store.setDefault(NetWorkingName.FTP_CLIENT_PASSWORD, "rtlab");}}TemplateInfoFactory.javapackage .uestc.ablator.ui.template;import java.io.File;import org.eclipse.jface.dialogs.MessageDialog;import .uestc.ablator.ui.template.entry.Entry;import .uestc.ablator.ui.util.MessageConfig;import .uestc.ablator.ui.util.XmlParser;/*** 根据id 生成TemplateInfo*/public class TemplateInfoFactory {private TemplateInfo templateInfo;private String templateId;/*** 通过id生成模板的TemplateInfo,不包括options目录及其子文件* @param id*/public TemplateInfo createTemplateInfo(String id){this.templateId = id;XmlParser parser = XmlParser.getInstance();File file = parser.findFileById(templateId);if(!file.exists()){MessageDialog.openError(null, "error", "文件"+file.getAbsolutePath()+"不存在");return null;}createTargetTemplateInfo(file,null);return this.templateInfo;}/*** 创建TemplateInfo,其中entry保存源文件路径和目标文件路径,方便后期进行文件复制* 同时保存源文件夹名e.g. /src* @param inputFile* @param parent* @return*/private TemplateInfo createTargetTemplateInfo(File inputFile,Entry parent){TemplateInfo templateInfo= createTemplate(inputFile,parent);//递归栈Entry projectEntry = templateInfo.getLast();//绝对路径前缀String projectPath = projectEntry.getPath();// ("absolute path prefix: "+projectPath);for(Entry ed :templateInfo.getEntryList()){//保存模板文件的绝对路径,以便文件拷贝ed.setTemplateFileAbsolutePath(ed.getPath());String path = ed.getPath().substring(projectPath.length(), ed.getPath().length());ed.setPath(path);}templateInfo.setSourceFolderPath(XmlParser.getInstance().getSingleSourcePath(templateId));templateInfo.setAbsPathPrefix(projectPath);return templateInfo;}/*** 返回指定id的模板的TemplateInfo,其中Entry的Path为绝对路径* @param inputFile* @param parent* @return*/private TemplateInfo createTemplate(File inputFile,Entry parent){if(!inputFile.getName().equals(MessageConfig.OPTION_FOLDER_NAME)){if(templateInfo==null)templateInfo = new TemplateInfo();String path = inputFile.getAbsolutePath();Entry entry = new Entry(path, inputFile.getName());entry.setParent(parent);if(inputFile.isDirectory()){entry.isCommonFolder = true;//判断当前文件夹是否是源文件夹if(inputFile.getName().equals(XmlParser.getInstance().getSingleSourcePath(templateId)))entry.isSourceFolder = true;File[] fileArray = inputFile.listFiles();if(fileArray.length>0){for(File file : fileArray){createTemplate(file,entry);}}}templateInfo.addEntry(entry);}return templateInfo;}。